payload-auth 1.0.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.md +17 -0
- package/dist/authjs/index.d.ts +1 -0
- package/dist/authjs/index.js +3 -0
- package/dist/authjs/index.js.map +1 -0
- package/dist/better-auth/adapter/dev/bin/run.d.ts +1 -0
- package/dist/better-auth/adapter/dev/bin/run.js +64 -0
- package/dist/better-auth/adapter/dev/bin/run.js.map +1 -0
- package/dist/better-auth/adapter/dev/bin/schema.d.ts +22 -0
- package/dist/better-auth/adapter/dev/bin/schema.js +160 -0
- package/dist/better-auth/adapter/dev/bin/schema.js.map +1 -0
- package/dist/better-auth/adapter/dev/collections.d.ts +3 -0
- package/dist/better-auth/adapter/dev/collections.js +212 -0
- package/dist/better-auth/adapter/dev/collections.js.map +1 -0
- package/dist/better-auth/adapter/dev/index.d.ts +3 -0
- package/dist/better-auth/adapter/dev/index.js +168 -0
- package/dist/better-auth/adapter/dev/index.js.map +1 -0
- package/dist/better-auth/adapter/generate-schema/generate-schema-builder.d.ts +23 -0
- package/dist/better-auth/adapter/generate-schema/generate-schema-builder.js +326 -0
- package/dist/better-auth/adapter/generate-schema/generate-schema-builder.js.map +1 -0
- package/dist/better-auth/adapter/generate-schema/get-payload-schema.d.ts +1 -0
- package/dist/better-auth/adapter/generate-schema/get-payload-schema.js +23 -0
- package/dist/better-auth/adapter/generate-schema/get-payload-schema.js.map +1 -0
- package/dist/better-auth/adapter/generate-schema/index.d.ts +4 -0
- package/dist/better-auth/adapter/generate-schema/index.js +19 -0
- package/dist/better-auth/adapter/generate-schema/index.js.map +1 -0
- package/dist/better-auth/adapter/generate-schema/utils.d.ts +2 -0
- package/dist/better-auth/adapter/generate-schema/utils.js +20 -0
- package/dist/better-auth/adapter/generate-schema/utils.js.map +1 -0
- package/dist/better-auth/adapter/index.d.ts +5 -0
- package/dist/better-auth/adapter/index.js +578 -0
- package/dist/better-auth/adapter/index.js.map +1 -0
- package/dist/better-auth/adapter/test/adapter.test.d.ts +1 -0
- package/dist/better-auth/adapter/test/adapter.test.js +181 -0
- package/dist/better-auth/adapter/test/adapter.test.js.map +1 -0
- package/dist/better-auth/adapter/test/better-auth-adapter-test.d.ts +7 -0
- package/dist/better-auth/adapter/test/better-auth-adapter-test.js +425 -0
- package/dist/better-auth/adapter/test/better-auth-adapter-test.js.map +1 -0
- package/dist/better-auth/adapter/test/schema.test.d.ts +1 -0
- package/dist/better-auth/adapter/test/schema.test.js +796 -0
- package/dist/better-auth/adapter/test/schema.test.js.map +1 -0
- package/dist/better-auth/adapter/test/test_payload1/schema.d.ts +23 -0
- package/dist/better-auth/adapter/test/test_payload1/schema.js +177 -0
- package/dist/better-auth/adapter/test/test_payload1/schema.js.map +1 -0
- package/dist/better-auth/adapter/test/test_payload2/schema.d.ts +23 -0
- package/dist/better-auth/adapter/test/test_payload2/schema.js +167 -0
- package/dist/better-auth/adapter/test/test_payload2/schema.js.map +1 -0
- package/dist/better-auth/adapter/test/test_payload3/schema.d.ts +23 -0
- package/dist/better-auth/adapter/test/test_payload3/schema.js +198 -0
- package/dist/better-auth/adapter/test/test_payload3/schema.js.map +1 -0
- package/dist/better-auth/adapter/transform/index.d.ts +16 -0
- package/dist/better-auth/adapter/transform/index.js +252 -0
- package/dist/better-auth/adapter/transform/index.js.map +1 -0
- package/dist/better-auth/adapter/types.d.ts +6 -0
- package/dist/better-auth/adapter/types.js +3 -0
- package/dist/better-auth/adapter/types.js.map +1 -0
- package/dist/better-auth/index.d.ts +6 -0
- package/dist/better-auth/index.js +8 -0
- package/dist/better-auth/index.js.map +1 -0
- package/dist/better-auth/plugin/collections/accounts/hooks/sync-password-to-user.d.ts +7 -0
- package/dist/better-auth/plugin/collections/accounts/hooks/sync-password-to-user.js +47 -0
- package/dist/better-auth/plugin/collections/accounts/hooks/sync-password-to-user.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/endpoints/refresh-token.d.ts +6 -0
- package/dist/better-auth/plugin/collections/users/endpoints/refresh-token.js +106 -0
- package/dist/better-auth/plugin/collections/users/endpoints/refresh-token.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-login.d.ts +11 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-login.js +71 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-login.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-logout.d.ts +6 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-logout.js +49 -0
- package/dist/better-auth/plugin/collections/users/hooks/after-logout.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/before-login.d.ts +5 -0
- package/dist/better-auth/plugin/collections/users/hooks/before-login.js +18 -0
- package/dist/better-auth/plugin/collections/users/hooks/before-login.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/clean-up-user-after-delete.d.ts +5 -0
- package/dist/better-auth/plugin/collections/users/hooks/clean-up-user-after-delete.js +33 -0
- package/dist/better-auth/plugin/collections/users/hooks/clean-up-user-after-delete.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/on-verified-change.d.ts +2 -0
- package/dist/better-auth/plugin/collections/users/hooks/on-verified-change.js +14 -0
- package/dist/better-auth/plugin/collections/users/hooks/on-verified-change.js.map +1 -0
- package/dist/better-auth/plugin/collections/users/hooks/sync-account.d.ts +7 -0
- package/dist/better-auth/plugin/collections/users/hooks/sync-account.js +82 -0
- package/dist/better-auth/plugin/collections/users/hooks/sync-account.js.map +1 -0
- package/dist/better-auth/plugin/helpers/generate-verify-email-url.d.ts +29 -0
- package/dist/better-auth/plugin/helpers/generate-verify-email-url.js +46 -0
- package/dist/better-auth/plugin/helpers/generate-verify-email-url.js.map +1 -0
- package/dist/better-auth/plugin/helpers/get-ip.d.ts +2 -0
- package/dist/better-auth/plugin/helpers/get-ip.js +31 -0
- package/dist/better-auth/plugin/helpers/get-ip.js.map +1 -0
- package/dist/better-auth/plugin/helpers/index.d.ts +1 -0
- package/dist/better-auth/plugin/helpers/index.js +3 -0
- package/dist/better-auth/plugin/helpers/index.js.map +1 -0
- package/dist/better-auth/plugin/helpers/serialize-cookie.d.ts +104 -0
- package/dist/better-auth/plugin/helpers/serialize-cookie.js +186 -0
- package/dist/better-auth/plugin/helpers/serialize-cookie.js.map +1 -0
- package/dist/better-auth/plugin/index.d.ts +7 -0
- package/dist/better-auth/plugin/index.js +64 -0
- package/dist/better-auth/plugin/index.js.map +1 -0
- package/dist/better-auth/plugin/lib/auth-strategy.d.ts +8 -0
- package/dist/better-auth/plugin/lib/auth-strategy.js +48 -0
- package/dist/better-auth/plugin/lib/auth-strategy.js.map +1 -0
- package/dist/better-auth/plugin/lib/build-collection-configs.d.ts +11 -0
- package/dist/better-auth/plugin/lib/build-collection-configs.js +1558 -0
- package/dist/better-auth/plugin/lib/build-collection-configs.js.map +1 -0
- package/dist/better-auth/plugin/lib/config.d.ts +41 -0
- package/dist/better-auth/plugin/lib/config.js +43 -0
- package/dist/better-auth/plugin/lib/config.js.map +1 -0
- package/dist/better-auth/plugin/lib/ensure-password-set-before-create.d.ts +7 -0
- package/dist/better-auth/plugin/lib/ensure-password-set-before-create.js +24 -0
- package/dist/better-auth/plugin/lib/ensure-password-set-before-create.js.map +1 -0
- package/dist/better-auth/plugin/lib/get-payload-auth.d.ts +5 -0
- package/dist/better-auth/plugin/lib/get-payload-auth.js +9 -0
- package/dist/better-auth/plugin/lib/get-payload-auth.js.map +1 -0
- package/dist/better-auth/plugin/lib/get-required-collection-slugs.d.ts +9 -0
- package/dist/better-auth/plugin/lib/get-required-collection-slugs.js +52 -0
- package/dist/better-auth/plugin/lib/get-required-collection-slugs.js.map +1 -0
- package/dist/better-auth/plugin/lib/init-better-auth.d.ts +6 -0
- package/dist/better-auth/plugin/lib/init-better-auth.js +13 -0
- package/dist/better-auth/plugin/lib/init-better-auth.js.map +1 -0
- package/dist/better-auth/plugin/lib/password.d.ts +25 -0
- package/dist/better-auth/plugin/lib/password.js +63 -0
- package/dist/better-auth/plugin/lib/password.js.map +1 -0
- package/dist/better-auth/plugin/lib/payload-access.d.ts +14 -0
- package/dist/better-auth/plugin/lib/payload-access.js +64 -0
- package/dist/better-auth/plugin/lib/payload-access.js.map +1 -0
- package/dist/better-auth/plugin/lib/prepare-session-data.d.ts +21 -0
- package/dist/better-auth/plugin/lib/prepare-session-data.js +42 -0
- package/dist/better-auth/plugin/lib/prepare-session-data.js.map +1 -0
- package/dist/better-auth/plugin/lib/respect-save-to-jwt-fields-middleware.d.ts +15 -0
- package/dist/better-auth/plugin/lib/respect-save-to-jwt-fields-middleware.js +30 -0
- package/dist/better-auth/plugin/lib/respect-save-to-jwt-fields-middleware.js.map +1 -0
- package/dist/better-auth/plugin/lib/sanitize-auth-options.d.ts +5 -0
- package/dist/better-auth/plugin/lib/sanitize-auth-options.js +298 -0
- package/dist/better-auth/plugin/lib/sanitize-auth-options.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/admin-buttons.d.ts +5 -0
- package/dist/better-auth/plugin/payload/components/admin-buttons.js +222 -0
- package/dist/better-auth/plugin/payload/components/admin-buttons.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/login-redirect.d.ts +1 -0
- package/dist/better-auth/plugin/payload/components/login-redirect.js +6 -0
- package/dist/better-auth/plugin/payload/components/login-redirect.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/logo.d.ts +1 -0
- package/dist/better-auth/plugin/payload/components/logo.js +36 -0
- package/dist/better-auth/plugin/payload/components/logo.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/logout.d.ts +1 -0
- package/dist/better-auth/plugin/payload/components/logout.js +61 -0
- package/dist/better-auth/plugin/payload/components/logout.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/sign-in.d.ts +3 -0
- package/dist/better-auth/plugin/payload/components/sign-in.js +384 -0
- package/dist/better-auth/plugin/payload/components/sign-in.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/sign-up.d.ts +6 -0
- package/dist/better-auth/plugin/payload/components/sign-up.js +502 -0
- package/dist/better-auth/plugin/payload/components/sign-up.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/styles.css +73 -0
- package/dist/better-auth/plugin/payload/components/ui/button.d.ts +10 -0
- package/dist/better-auth/plugin/payload/components/ui/button.js +42 -0
- package/dist/better-auth/plugin/payload/components/ui/button.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/card.d.ts +9 -0
- package/dist/better-auth/plugin/payload/components/ui/card.js +55 -0
- package/dist/better-auth/plugin/payload/components/ui/card.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/checkbox.d.ts +4 -0
- package/dist/better-auth/plugin/payload/components/ui/checkbox.js +23 -0
- package/dist/better-auth/plugin/payload/components/ui/checkbox.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/cn.d.ts +2 -0
- package/dist/better-auth/plugin/payload/components/ui/cn.js +7 -0
- package/dist/better-auth/plugin/payload/components/ui/cn.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/input.d.ts +3 -0
- package/dist/better-auth/plugin/payload/components/ui/input.js +14 -0
- package/dist/better-auth/plugin/payload/components/ui/input.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/label.d.ts +4 -0
- package/dist/better-auth/plugin/payload/components/ui/label.js +15 -0
- package/dist/better-auth/plugin/payload/components/ui/label.js.map +1 -0
- package/dist/better-auth/plugin/payload/components/ui/password-input.d.ts +2 -0
- package/dist/better-auth/plugin/payload/components/ui/password-input.js +55 -0
- package/dist/better-auth/plugin/payload/components/ui/password-input.js.map +1 -0
- package/dist/better-auth/plugin/payload/exports/client.d.ts +3 -0
- package/dist/better-auth/plugin/payload/exports/client.js +5 -0
- package/dist/better-auth/plugin/payload/exports/client.js.map +1 -0
- package/dist/better-auth/plugin/payload/exports/rsc.d.ts +5 -0
- package/dist/better-auth/plugin/payload/exports/rsc.js +7 -0
- package/dist/better-auth/plugin/payload/exports/rsc.js.map +1 -0
- package/dist/better-auth/plugin/payload/views/create-first-admin/index.d.ts +4 -0
- package/dist/better-auth/plugin/payload/views/create-first-admin/index.js +112 -0
- package/dist/better-auth/plugin/payload/views/create-first-admin/index.js.map +1 -0
- package/dist/better-auth/plugin/payload/views/login/index.d.ts +4 -0
- package/dist/better-auth/plugin/payload/views/login/index.js +78 -0
- package/dist/better-auth/plugin/payload/views/login/index.js.map +1 -0
- package/dist/better-auth/plugin/types.d.ts +224 -0
- package/dist/better-auth/plugin/types.js +3 -0
- package/dist/better-auth/plugin/types.js.map +1 -0
- package/dist/better-auth/types.d.ts +2 -0
- package/dist/better-auth/types.js +4 -0
- package/dist/better-auth/types.js.map +1 -0
- package/dist/clerk/index.d.ts +1 -0
- package/dist/clerk/index.js +3 -0
- package/dist/clerk/index.js.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/kinde/index.d.ts +1 -0
- package/dist/kinde/index.js +3 -0
- package/dist/kinde/index.js.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { generateVerifyEmailUrl } from './generate-verify-email-url';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/plugin/helpers/index.ts"],"sourcesContent":["export { generateVerifyEmailUrl } from './generate-verify-email-url'; "],"names":["generateVerifyEmailUrl"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,8BAA8B"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
type CookiePrefixOptions = 'host' | 'secure';
|
|
2
|
+
type CookieOptions = {
|
|
3
|
+
/**
|
|
4
|
+
* Domain of the cookie
|
|
5
|
+
*
|
|
6
|
+
* The Domain attribute specifies which server can receive a cookie. If specified, cookies are
|
|
7
|
+
* available on the specified server and its subdomains. If the it is not
|
|
8
|
+
* specified, the cookies are available on the server that sets it but not on
|
|
9
|
+
* its subdomains.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* `domain: "example.com"`
|
|
13
|
+
*/
|
|
14
|
+
domain?: string;
|
|
15
|
+
/**
|
|
16
|
+
* A lifetime of a cookie. Permanent cookies are deleted after the date specified in the
|
|
17
|
+
* Expires attribute:
|
|
18
|
+
*
|
|
19
|
+
* Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and
|
|
20
|
+
* takes precedence when both are set. The rationale behind this is that when you set an
|
|
21
|
+
* Expires date and time, they're relative to the client the cookie is being set on. If the
|
|
22
|
+
* server is set to a different time, this could cause errors
|
|
23
|
+
*/
|
|
24
|
+
expires?: Date;
|
|
25
|
+
/**
|
|
26
|
+
* Forbids JavaScript from accessing the cookie, for example, through the Document.cookie
|
|
27
|
+
* property. Note that a cookie that has been created with HttpOnly will still be sent with
|
|
28
|
+
* JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().
|
|
29
|
+
* This mitigates attacks against cross-site scripting
|
|
30
|
+
*/
|
|
31
|
+
httpOnly?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Indicates the number of seconds until the cookie expires. A zero or negative number will
|
|
34
|
+
* expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.
|
|
35
|
+
*
|
|
36
|
+
* @example 604800 - 7 days
|
|
37
|
+
*/
|
|
38
|
+
maxAge?: number;
|
|
39
|
+
/**
|
|
40
|
+
* Indicates the path that must exist in the requested URL for the browser to send the Cookie
|
|
41
|
+
* header.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* "/docs"
|
|
45
|
+
* // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.
|
|
46
|
+
*/
|
|
47
|
+
path?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Indicates that the cookie is sent to the server only when a request is made with the https:
|
|
50
|
+
* scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.
|
|
51
|
+
*/
|
|
52
|
+
secure?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Controls whether or not a cookie is sent with cross-site requests, providing some protection
|
|
55
|
+
* against cross-site request forgery attacks (CSRF).
|
|
56
|
+
*
|
|
57
|
+
* Strict - Means that the browser sends the cookie only for same-site requests, that is,
|
|
58
|
+
* requests originating from the same site that set the cookie. If a request originates from a
|
|
59
|
+
* different domain or scheme (even with the same domain), no cookies with the SameSite=Strict
|
|
60
|
+
* attribute are sent.
|
|
61
|
+
*
|
|
62
|
+
* Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load
|
|
63
|
+
* images or frames, but is sent when a user is navigating to the origin site from an external
|
|
64
|
+
* site (for example, when following a link). This is the default behavior if the SameSite
|
|
65
|
+
* attribute is not specified.
|
|
66
|
+
*
|
|
67
|
+
* None - Means that the browser sends the cookie with both cross-site and same-site requests.
|
|
68
|
+
* The Secure attribute must also be set when setting this value.
|
|
69
|
+
*/
|
|
70
|
+
sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none';
|
|
71
|
+
/**
|
|
72
|
+
* Indicates that the cookie should be stored using partitioned storage. Note that if this is
|
|
73
|
+
* set, the Secure directive must also be set.
|
|
74
|
+
*
|
|
75
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies
|
|
76
|
+
*/
|
|
77
|
+
partitioned?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Cooke Prefix
|
|
80
|
+
*
|
|
81
|
+
* - secure: `__Secure-` -> `__Secure-cookie-name`
|
|
82
|
+
* - host: `__Host-` -> `__Host-cookie-name`
|
|
83
|
+
*
|
|
84
|
+
* `secure` must be set to true to use prefixes
|
|
85
|
+
*/
|
|
86
|
+
prefix?: CookiePrefixOptions;
|
|
87
|
+
};
|
|
88
|
+
export declare const verifySignature: (base64Signature: string, value: string, secret: CryptoKey) => Promise<boolean>;
|
|
89
|
+
export declare const signCookieValue: (value: string, secret: string | BufferSource) => Promise<string>;
|
|
90
|
+
export declare const serializeCookie: (key: string, value: string, opt?: CookieOptions) => string;
|
|
91
|
+
export declare const serializeSignedCookie: (key: string, value: string, secret: string, opt?: CookieOptions) => Promise<string>;
|
|
92
|
+
export declare const getCookieKey: (key: string, prefix?: CookiePrefixOptions) => string | undefined;
|
|
93
|
+
export declare function tryDecode(str: string): string;
|
|
94
|
+
/**
|
|
95
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
96
|
+
* name-value pairs.
|
|
97
|
+
*
|
|
98
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
99
|
+
*
|
|
100
|
+
* @param str the string representing a `Cookie` header value
|
|
101
|
+
*/
|
|
102
|
+
export declare function parseCookies(str: string): Map<string, string>;
|
|
103
|
+
export declare const getSignedCookie: (key: string, secret: string, headers: Headers, prefix?: CookiePrefixOptions) => Promise<string | false | null>;
|
|
104
|
+
export {};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { subtle } from 'uncrypto';
|
|
2
|
+
export const verifySignature = async (base64Signature, value, secret)=>{
|
|
3
|
+
try {
|
|
4
|
+
const signatureBinStr = atob(base64Signature);
|
|
5
|
+
const signature = new Uint8Array(signatureBinStr.length);
|
|
6
|
+
for(let i = 0, len = signatureBinStr.length; i < len; i++){
|
|
7
|
+
signature[i] = signatureBinStr.charCodeAt(i);
|
|
8
|
+
}
|
|
9
|
+
return await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));
|
|
10
|
+
} catch (e) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
const _serialize = (key, value, opt = {})=>{
|
|
15
|
+
let cookie;
|
|
16
|
+
if (opt?.prefix === 'secure') {
|
|
17
|
+
cookie = `${`__Secure-${key}`}=${value}`;
|
|
18
|
+
} else if (opt?.prefix === 'host') {
|
|
19
|
+
cookie = `${`__Host-${key}`}=${value}`;
|
|
20
|
+
} else {
|
|
21
|
+
cookie = `${key}=${value}`;
|
|
22
|
+
}
|
|
23
|
+
if (key.startsWith('__Secure-') && !opt.secure) {
|
|
24
|
+
opt.secure = true;
|
|
25
|
+
}
|
|
26
|
+
if (key.startsWith('__Host-')) {
|
|
27
|
+
if (!opt.secure) {
|
|
28
|
+
opt.secure = true;
|
|
29
|
+
}
|
|
30
|
+
if (opt.path !== '/') {
|
|
31
|
+
opt.path = '/';
|
|
32
|
+
}
|
|
33
|
+
if (opt.domain) {
|
|
34
|
+
opt.domain = undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {
|
|
38
|
+
if (opt.maxAge > 34560000) {
|
|
39
|
+
throw new Error('Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.');
|
|
40
|
+
}
|
|
41
|
+
cookie += `; Max-Age=${Math.floor(opt.maxAge)}`;
|
|
42
|
+
}
|
|
43
|
+
if (opt.domain && opt.prefix !== 'host') {
|
|
44
|
+
cookie += `; Domain=${opt.domain}`;
|
|
45
|
+
}
|
|
46
|
+
if (opt.path) {
|
|
47
|
+
cookie += `; Path=${opt.path}`;
|
|
48
|
+
}
|
|
49
|
+
if (opt.expires) {
|
|
50
|
+
if (opt.expires.getTime() - Date.now() > 34560000_000) {
|
|
51
|
+
throw new Error('Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.');
|
|
52
|
+
}
|
|
53
|
+
cookie += `; Expires=${opt.expires.toUTCString()}`;
|
|
54
|
+
}
|
|
55
|
+
if (opt.httpOnly) {
|
|
56
|
+
cookie += '; HttpOnly';
|
|
57
|
+
}
|
|
58
|
+
if (opt.secure) {
|
|
59
|
+
cookie += '; Secure';
|
|
60
|
+
}
|
|
61
|
+
if (opt.sameSite) {
|
|
62
|
+
cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
|
|
63
|
+
}
|
|
64
|
+
if (opt.partitioned) {
|
|
65
|
+
if (!opt.secure) {
|
|
66
|
+
opt.secure = true;
|
|
67
|
+
}
|
|
68
|
+
cookie += '; Partitioned';
|
|
69
|
+
}
|
|
70
|
+
return cookie;
|
|
71
|
+
};
|
|
72
|
+
const algorithm = {
|
|
73
|
+
name: 'HMAC',
|
|
74
|
+
hash: 'SHA-256'
|
|
75
|
+
};
|
|
76
|
+
const getCryptoKey = async (secret)=>{
|
|
77
|
+
const secretBuf = typeof secret === 'string' ? new TextEncoder().encode(secret) : secret;
|
|
78
|
+
return await subtle.importKey('raw', secretBuf, algorithm, false, [
|
|
79
|
+
'sign',
|
|
80
|
+
'verify'
|
|
81
|
+
]);
|
|
82
|
+
};
|
|
83
|
+
const makeSignature = async (value, secret)=>{
|
|
84
|
+
const key = await getCryptoKey(secret);
|
|
85
|
+
const signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value));
|
|
86
|
+
// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs
|
|
87
|
+
return btoa(String.fromCharCode(...new Uint8Array(signature)));
|
|
88
|
+
};
|
|
89
|
+
export const signCookieValue = async (value, secret)=>{
|
|
90
|
+
const signature = await makeSignature(value, secret);
|
|
91
|
+
value = `${value}.${signature}`;
|
|
92
|
+
value = encodeURIComponent(value);
|
|
93
|
+
value = decodeURIComponent(value);
|
|
94
|
+
return value;
|
|
95
|
+
};
|
|
96
|
+
export const serializeCookie = (key, value, opt)=>{
|
|
97
|
+
value = encodeURIComponent(value);
|
|
98
|
+
return _serialize(key, value, opt);
|
|
99
|
+
};
|
|
100
|
+
export const serializeSignedCookie = async (key, value, secret, opt)=>{
|
|
101
|
+
value = await signCookieValue(value, secret);
|
|
102
|
+
return _serialize(key, value, opt);
|
|
103
|
+
};
|
|
104
|
+
export const getCookieKey = (key, prefix)=>{
|
|
105
|
+
let finalKey = key;
|
|
106
|
+
if (prefix) {
|
|
107
|
+
if (prefix === 'secure') {
|
|
108
|
+
finalKey = '__Secure-' + key;
|
|
109
|
+
} else if (prefix === 'host') {
|
|
110
|
+
finalKey = '__Host-' + key;
|
|
111
|
+
} else {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return finalKey;
|
|
116
|
+
};
|
|
117
|
+
export function tryDecode(str) {
|
|
118
|
+
try {
|
|
119
|
+
return str.includes('%') ? decodeURIComponent(str) : str;
|
|
120
|
+
} catch {
|
|
121
|
+
return str;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
126
|
+
* name-value pairs.
|
|
127
|
+
*
|
|
128
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
129
|
+
*
|
|
130
|
+
* @param str the string representing a `Cookie` header value
|
|
131
|
+
*/ export function parseCookies(str) {
|
|
132
|
+
if (typeof str !== 'string') {
|
|
133
|
+
throw new TypeError('argument str must be a string');
|
|
134
|
+
}
|
|
135
|
+
const cookies = new Map();
|
|
136
|
+
let index = 0;
|
|
137
|
+
while(index < str.length){
|
|
138
|
+
const eqIdx = str.indexOf('=', index);
|
|
139
|
+
if (eqIdx === -1) {
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
let endIdx = str.indexOf(';', index);
|
|
143
|
+
if (endIdx === -1) {
|
|
144
|
+
endIdx = str.length;
|
|
145
|
+
} else if (endIdx < eqIdx) {
|
|
146
|
+
index = str.lastIndexOf(';', eqIdx - 1) + 1;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const key = str.slice(index, eqIdx).trim();
|
|
150
|
+
if (!cookies.has(key)) {
|
|
151
|
+
let val = str.slice(eqIdx + 1, endIdx).trim();
|
|
152
|
+
if (val.codePointAt(0) === 0x22) {
|
|
153
|
+
val = val.slice(1, -1);
|
|
154
|
+
}
|
|
155
|
+
cookies.set(key, tryDecode(val));
|
|
156
|
+
}
|
|
157
|
+
index = endIdx + 1;
|
|
158
|
+
}
|
|
159
|
+
return cookies;
|
|
160
|
+
}
|
|
161
|
+
export const getSignedCookie = async (key, secret, headers, prefix)=>{
|
|
162
|
+
const finalKey = getCookieKey(key, prefix);
|
|
163
|
+
if (!finalKey) {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
const cookieHeader = headers.get('cookie');
|
|
167
|
+
const parsedCookies = cookieHeader ? parseCookies(cookieHeader) : undefined;
|
|
168
|
+
const value = parsedCookies?.get(finalKey);
|
|
169
|
+
if (!value) {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
const signatureStartPos = value.lastIndexOf('.');
|
|
173
|
+
if (signatureStartPos < 1) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
const signedValue = value.substring(0, signatureStartPos);
|
|
177
|
+
const signature = value.substring(signatureStartPos + 1);
|
|
178
|
+
if (signature.length !== 44 || !signature.endsWith('=')) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
const secretKey = await getCryptoKey(secret);
|
|
182
|
+
const isVerified = await verifySignature(signature, signedValue, secretKey);
|
|
183
|
+
return isVerified ? signedValue : false;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
//# sourceMappingURL=serialize-cookie.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/plugin/helpers/serialize-cookie.ts"],"sourcesContent":["import { subtle } from 'uncrypto'\n\ntype CookiePrefixOptions = 'host' | 'secure'\n\ntype CookieOptions = {\n /**\n * Domain of the cookie\n *\n * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n * available on the specified server and its subdomains. If the it is not\n * specified, the cookies are available on the server that sets it but not on\n * its subdomains.\n *\n * @example\n * `domain: \"example.com\"`\n */\n domain?: string\n /**\n * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n * Expires attribute:\n *\n * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n * takes precedence when both are set. The rationale behind this is that when you set an\n * Expires date and time, they're relative to the client the cookie is being set on. If the\n * server is set to a different time, this could cause errors\n */\n expires?: Date\n /**\n * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n * property. Note that a cookie that has been created with HttpOnly will still be sent with\n * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n * This mitigates attacks against cross-site scripting\n */\n httpOnly?: boolean\n /**\n * Indicates the number of seconds until the cookie expires. A zero or negative number will\n * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n *\n * @example 604800 - 7 days\n */\n maxAge?: number\n /**\n * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n * header.\n *\n * @example\n * \"/docs\"\n * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n */\n path?: string\n /**\n * Indicates that the cookie is sent to the server only when a request is made with the https:\n * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n */\n secure?: boolean\n /**\n * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n * against cross-site request forgery attacks (CSRF).\n *\n * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n * requests originating from the same site that set the cookie. If a request originates from a\n * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n * attribute are sent.\n *\n * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n * images or frames, but is sent when a user is navigating to the origin site from an external\n * site (for example, when following a link). This is the default behavior if the SameSite\n * attribute is not specified.\n *\n * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n * The Secure attribute must also be set when setting this value.\n */\n sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none'\n /**\n * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n * set, the Secure directive must also be set.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n */\n partitioned?: boolean\n /**\n * Cooke Prefix\n *\n * - secure: `__Secure-` -> `__Secure-cookie-name`\n * - host: `__Host-` -> `__Host-cookie-name`\n *\n * `secure` must be set to true to use prefixes\n */\n prefix?: CookiePrefixOptions\n}\n\nexport const verifySignature = async (\n base64Signature: string,\n value: string,\n secret: CryptoKey,\n): Promise<boolean> => {\n try {\n const signatureBinStr = atob(base64Signature)\n const signature = new Uint8Array(signatureBinStr.length)\n for (let i = 0, len = signatureBinStr.length; i < len; i++) {\n signature[i] = signatureBinStr.charCodeAt(i)\n }\n return await subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value))\n } catch (e) {\n return false\n }\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n let cookie: string\n\n if (opt?.prefix === 'secure') {\n cookie = `${`__Secure-${key}`}=${value}`\n } else if (opt?.prefix === 'host') {\n cookie = `${`__Host-${key}`}=${value}`\n } else {\n cookie = `${key}=${value}`\n }\n\n if (key.startsWith('__Secure-') && !opt.secure) {\n opt.secure = true\n }\n\n if (key.startsWith('__Host-')) {\n if (!opt.secure) {\n opt.secure = true\n }\n\n if (opt.path !== '/') {\n opt.path = '/'\n }\n\n if (opt.domain) {\n opt.domain = undefined\n }\n }\n\n if (opt && typeof opt.maxAge === 'number' && opt.maxAge >= 0) {\n if (opt.maxAge > 34560000) {\n throw new Error(\n 'Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.',\n )\n }\n cookie += `; Max-Age=${Math.floor(opt.maxAge)}`\n }\n\n if (opt.domain && opt.prefix !== 'host') {\n cookie += `; Domain=${opt.domain}`\n }\n\n if (opt.path) {\n cookie += `; Path=${opt.path}`\n }\n\n if (opt.expires) {\n if (opt.expires.getTime() - Date.now() > 34560000_000) {\n throw new Error(\n 'Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.',\n )\n }\n cookie += `; Expires=${opt.expires.toUTCString()}`\n }\n\n if (opt.httpOnly) {\n cookie += '; HttpOnly'\n }\n\n if (opt.secure) {\n cookie += '; Secure'\n }\n\n if (opt.sameSite) {\n cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`\n }\n\n if (opt.partitioned) {\n if (!opt.secure) {\n opt.secure = true\n }\n cookie += '; Partitioned'\n }\n\n return cookie\n}\n\nconst algorithm = { name: 'HMAC', hash: 'SHA-256' }\n\nconst getCryptoKey = async (secret: string | BufferSource) => {\n const secretBuf = typeof secret === 'string' ? new TextEncoder().encode(secret) : secret\n return await subtle.importKey('raw', secretBuf, algorithm, false, ['sign', 'verify'])\n}\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n const key = await getCryptoKey(secret)\n const signature = await subtle.sign(algorithm.name, key, new TextEncoder().encode(value))\n // the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n return btoa(String.fromCharCode(...new Uint8Array(signature)))\n}\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n const signature = await makeSignature(value, secret)\n value = `${value}.${signature}`\n value = encodeURIComponent(value)\n value = decodeURIComponent(value)\n return value\n}\n\nexport const serializeCookie = (key: string, value: string, opt?: CookieOptions) => {\n value = encodeURIComponent(value)\n return _serialize(key, value, opt)\n}\n\nexport const serializeSignedCookie = async (\n key: string,\n value: string,\n secret: string,\n opt?: CookieOptions,\n) => {\n value = await signCookieValue(value, secret)\n return _serialize(key, value, opt)\n}\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n let finalKey = key\n if (prefix) {\n if (prefix === 'secure') {\n finalKey = '__Secure-' + key\n } else if (prefix === 'host') {\n finalKey = '__Host-' + key\n } else {\n return undefined\n }\n }\n return finalKey\n}\n\nexport function tryDecode(str: string) {\n try {\n return str.includes('%') ? decodeURIComponent(str) : str\n } catch {\n return str\n }\n}\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string')\n }\n\n const cookies: Map<string, string> = new Map()\n\n let index = 0\n while (index < str.length) {\n const eqIdx = str.indexOf('=', index)\n\n if (eqIdx === -1) {\n break\n }\n\n let endIdx = str.indexOf(';', index)\n\n if (endIdx === -1) {\n endIdx = str.length\n } else if (endIdx < eqIdx) {\n index = str.lastIndexOf(';', eqIdx - 1) + 1\n continue\n }\n\n const key = str.slice(index, eqIdx).trim()\n if (!cookies.has(key)) {\n let val = str.slice(eqIdx + 1, endIdx).trim()\n if (val.codePointAt(0) === 0x22) {\n val = val.slice(1, -1)\n }\n cookies.set(key, tryDecode(val))\n }\n\n index = endIdx + 1\n }\n\n return cookies\n}\n\nexport const getSignedCookie = async (\n key: string,\n secret: string,\n headers: Headers,\n prefix?: CookiePrefixOptions,\n) => {\n const finalKey = getCookieKey(key, prefix)\n if (!finalKey) {\n return null\n }\n const cookieHeader = headers.get('cookie')\n const parsedCookies = cookieHeader ? parseCookies(cookieHeader) : undefined\n const value = parsedCookies?.get(finalKey)\n if (!value) {\n return null\n }\n const signatureStartPos = value.lastIndexOf('.')\n if (signatureStartPos < 1) {\n return null\n }\n const signedValue = value.substring(0, signatureStartPos)\n const signature = value.substring(signatureStartPos + 1)\n if (signature.length !== 44 || !signature.endsWith('=')) {\n return null\n }\n const secretKey = await getCryptoKey(secret)\n const isVerified = await verifySignature(signature, signedValue, secretKey)\n return isVerified ? signedValue : false\n}\n"],"names":["subtle","verifySignature","base64Signature","value","secret","signatureBinStr","atob","signature","Uint8Array","length","i","len","charCodeAt","verify","algorithm","TextEncoder","encode","e","_serialize","key","opt","cookie","prefix","startsWith","secure","path","domain","undefined","maxAge","Error","Math","floor","expires","getTime","Date","now","toUTCString","httpOnly","sameSite","charAt","toUpperCase","slice","partitioned","name","hash","getCryptoKey","secretBuf","importKey","makeSignature","sign","btoa","String","fromCharCode","signCookieValue","encodeURIComponent","decodeURIComponent","serializeCookie","serializeSignedCookie","getCookieKey","finalKey","tryDecode","str","includes","parseCookies","TypeError","cookies","Map","index","eqIdx","indexOf","endIdx","lastIndexOf","trim","has","val","codePointAt","set","getSignedCookie","headers","cookieHeader","get","parsedCookies","signatureStartPos","signedValue","substring","endsWith","secretKey","isVerified"],"mappings":"AAAA,SAASA,MAAM,QAAQ,WAAU;A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AAoB;IACtD,IAAI3E,UAAUE,MAAM,KAAK,MAAM,CAACF,UAAU8E,QAAQ,CAAC,MAAM;QACvD,OAAO;IACT;IACA,MAAMC,YAAY,MAAMzC,aAAazC;IACrC,MAAMmF,aAAa,MAAMtF,gBAAgBM,WAAW4E,aAAaG;IACjE,OAAOC,aAAaJ,cAAc;AACpC,EAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Config } from 'payload';
|
|
2
|
+
import type { PayloadBetterAuthPluginOptions } from './types';
|
|
3
|
+
export * from './types';
|
|
4
|
+
export * from './helpers';
|
|
5
|
+
export { sanitizeBetterAuthOptions } from './lib/sanitize-auth-options';
|
|
6
|
+
export { getPayloadAuth } from './lib/get-payload-auth';
|
|
7
|
+
export declare function payloadBetterAuth(pluginOptions: PayloadBetterAuthPluginOptions): (config: Config) => Config;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { sanitizeBetterAuthOptions } from './lib/sanitize-auth-options';
|
|
2
|
+
import { getRequiredCollectionSlugs } from './lib/get-required-collection-slugs';
|
|
3
|
+
import { buildCollectionConfigs } from './lib/build-collection-configs';
|
|
4
|
+
import { respectSaveToJwtFieldsMiddleware } from './lib/respect-save-to-jwt-fields-middleware';
|
|
5
|
+
import { initBetterAuth } from './lib/init-better-auth';
|
|
6
|
+
export * from './types';
|
|
7
|
+
export * from './helpers';
|
|
8
|
+
export { sanitizeBetterAuthOptions } from './lib/sanitize-auth-options';
|
|
9
|
+
export { getPayloadAuth } from './lib/get-payload-auth';
|
|
10
|
+
export function payloadBetterAuth(pluginOptions) {
|
|
11
|
+
return (config)=>{
|
|
12
|
+
if (pluginOptions.disabled) {
|
|
13
|
+
return config;
|
|
14
|
+
}
|
|
15
|
+
config.custom = {
|
|
16
|
+
...config.custom,
|
|
17
|
+
hasBetterAuthPlugin: true
|
|
18
|
+
};
|
|
19
|
+
if (!config.collections) {
|
|
20
|
+
config.collections = [];
|
|
21
|
+
}
|
|
22
|
+
let sanitzedBetterAuthOptions = sanitizeBetterAuthOptions(pluginOptions);
|
|
23
|
+
// Determine which collections to add based on the options and plugins
|
|
24
|
+
const requiredCollectionSlugs = getRequiredCollectionSlugs({
|
|
25
|
+
logTables: pluginOptions.logTables ?? false,
|
|
26
|
+
pluginOptions,
|
|
27
|
+
sanitizedBAOptions: sanitzedBetterAuthOptions
|
|
28
|
+
});
|
|
29
|
+
// Update with the required collections + existing collections
|
|
30
|
+
config.collections = buildCollectionConfigs({
|
|
31
|
+
incomingCollections: config.collections ?? [],
|
|
32
|
+
requiredCollectionSlugs,
|
|
33
|
+
pluginOptions,
|
|
34
|
+
sanitizedBAOptions: sanitzedBetterAuthOptions
|
|
35
|
+
});
|
|
36
|
+
respectSaveToJwtFieldsMiddleware({
|
|
37
|
+
sanitizedOptions: sanitzedBetterAuthOptions,
|
|
38
|
+
payloadConfig: config,
|
|
39
|
+
pluginOptions
|
|
40
|
+
});
|
|
41
|
+
const incomingOnInit = config.onInit;
|
|
42
|
+
config.onInit = async (payload)=>{
|
|
43
|
+
// Ensure we are executing any existing onInit functions before running our own.
|
|
44
|
+
if (incomingOnInit) {
|
|
45
|
+
await incomingOnInit(payload);
|
|
46
|
+
}
|
|
47
|
+
// Initialize and set the betterAuth instance
|
|
48
|
+
const auth = initBetterAuth({
|
|
49
|
+
payload,
|
|
50
|
+
options: {
|
|
51
|
+
...sanitzedBetterAuthOptions,
|
|
52
|
+
enableDebugLogs: pluginOptions.enableDebugLogs,
|
|
53
|
+
plugins: [
|
|
54
|
+
...sanitzedBetterAuthOptions.plugins ?? []
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
payload.betterAuth = auth;
|
|
59
|
+
};
|
|
60
|
+
return config;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type { BasePayload, Config } from 'payload'\nimport type { PayloadBetterAuthPluginOptions } from './types'\nimport { sanitizeBetterAuthOptions } from './lib/sanitize-auth-options'\nimport { getRequiredCollectionSlugs } from './lib/get-required-collection-slugs'\nimport { buildCollectionConfigs } from './lib/build-collection-configs'\nimport { respectSaveToJwtFieldsMiddleware } from './lib/respect-save-to-jwt-fields-middleware'\nimport { initBetterAuth } from './lib/init-better-auth'\n\nexport * from './types'\nexport * from './helpers'\nexport { sanitizeBetterAuthOptions } from './lib/sanitize-auth-options'\nexport { getPayloadAuth } from './lib/get-payload-auth'\n\nexport function payloadBetterAuth(pluginOptions: PayloadBetterAuthPluginOptions) {\n return (config: Config): Config => {\n if (pluginOptions.disabled) {\n return config\n }\n config.custom = {\n ...config.custom,\n hasBetterAuthPlugin: true,\n }\n\n if (!config.collections) {\n config.collections = []\n }\n\n let sanitzedBetterAuthOptions = sanitizeBetterAuthOptions(pluginOptions)\n\n // Determine which collections to add based on the options and plugins\n const requiredCollectionSlugs = getRequiredCollectionSlugs({\n logTables: pluginOptions.logTables ?? false,\n pluginOptions,\n sanitizedBAOptions: sanitzedBetterAuthOptions,\n })\n\n // Update with the required collections + existing collections\n config.collections = buildCollectionConfigs({\n incomingCollections: config.collections ?? [],\n requiredCollectionSlugs,\n pluginOptions,\n sanitizedBAOptions: sanitzedBetterAuthOptions,\n })\n\n respectSaveToJwtFieldsMiddleware({\n sanitizedOptions: sanitzedBetterAuthOptions,\n payloadConfig: config,\n pluginOptions,\n })\n\n const incomingOnInit = config.onInit\n\n config.onInit = async (payload) => {\n // Ensure we are executing any existing onInit functions before running our own.\n if (incomingOnInit) {\n await incomingOnInit(payload)\n }\n\n // Initialize and set the betterAuth instance\n const auth = initBetterAuth<NonNullable<typeof sanitzedBetterAuthOptions.plugins>>({\n payload,\n options: {\n ...sanitzedBetterAuthOptions,\n enableDebugLogs: pluginOptions.enableDebugLogs,\n plugins: [...(sanitzedBetterAuthOptions.plugins ?? [])],\n },\n })\n ;(payload as BasePayload & { betterAuth: typeof auth }).betterAuth = auth\n }\n return config\n }\n}\n"],"names":["sanitizeBetterAuthOptions","getRequiredCollectionSlugs","buildCollectionConfigs","respectSaveToJwtFieldsMiddleware","initBetterAuth","getPayloadAuth","payloadBetterAuth","pluginOptions","config","disabled","custom","hasBetterAuthPlugin","collections","sanitzedBetterAuthOptions","requiredCollectionSlugs","logTables","sanitizedBAOptions","incomingCollections","sanitizedOptions","payloadConfig","incomingOnInit","onInit","payload","auth","options","enableDebugLogs","plugins","betterAuth"],"mappings":"AAEA,SAASA,yBAAyB,QAAQ,8BAA6B;AACvE,SAASC,0BAA0B,QAAQ,sCAAqC;AAChF,SAASC,sBAAsB,QAAQ,iCAAgC;AACvE,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,cAAc,QAAQ,yBAAwB;AAEvD,cAAc,UAAS;AACvB,cAAc,YAAW;AACzB,SAASJ,yBAAyB,QAAQ,8BAA6B;AACvE,SAASK,cAAc,QAAQ,yBAAwB;AAEvD,OAAO,SAASC,kBAAkBC,aAA6C;IAC7E,OAAO,CAACC;QACN,IAAID,cAAcE,QAAQ,EAAE;YAC1B,OAAOD;QACT;QACAA,OAAOE,MAAM,GAAG;YACd,GAAGF,OAAOE,MAAM;YAChBC,qBAAqB;QACvB;QAEA,IAAI,CAACH,OAAOI,WAAW,EAAE;YACvBJ,OAAOI,WAAW,GAAG,EAAE;QACzB;QAEA,IAAIC,4BAA4Bb,0BAA0BO;QAE1D,sEAAsE;QACtE,MAAMO,0BAA0Bb,2BAA2B;YACzDc,WAAWR,cAAcQ,SAAS,IAAI;YACtCR;YACAS,oBAAoBH;QACtB;QAEA,8DAA8D;QAC9DL,OAAOI,WAAW,GAAGV,uBAAuB;YAC1Ce,qBAAqBT,OAAOI,WAAW,IAAI,EAAE;YAC7CE;YACAP;YACAS,oBAAoBH;QACtB;QAEAV,iCAAiC;YAC/Be,kBAAkBL;YAClBM,eAAeX;YACfD;QACF;QAEA,MAAMa,iBAAiBZ,OAAOa,MAAM;QAEpCb,OAAOa,MAAM,GAAG,OAAOC;YACrB,gFAAgF;YAChF,IAAIF,gBAAgB;gBAClB,MAAMA,eAAeE;YACvB;YAEA,6CAA6C;YAC7C,MAAMC,OAAOnB,eAAsE;gBACjFkB;gBACAE,SAAS;oBACP,GAAGX,yBAAyB;oBAC5BY,iBAAiBlB,cAAckB,eAAe;oBAC9CC,SAAS;2BAAKb,0BAA0Ba,OAAO,IAAI,EAAE;qBAAE;gBACzD;YACF;YACEJ,QAAsDK,UAAU,GAAGJ;QACvE;QACA,OAAOf;IACT;AACF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AuthStrategy } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Auth strategy for BetterAuth
|
|
4
|
+
* @param adminRoles - Admin roles
|
|
5
|
+
* @param userSlug - User collection slug
|
|
6
|
+
* @returns Auth strategy
|
|
7
|
+
*/
|
|
8
|
+
export declare function betterAuthStrategy(adminRoles?: string[], userSlug?: string): AuthStrategy;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { getPayloadAuth } from './get-payload-auth';
|
|
2
|
+
/**
|
|
3
|
+
* Auth strategy for BetterAuth
|
|
4
|
+
* @param adminRoles - Admin roles
|
|
5
|
+
* @param userSlug - User collection slug
|
|
6
|
+
* @returns Auth strategy
|
|
7
|
+
*/ export function betterAuthStrategy(adminRoles, userSlug) {
|
|
8
|
+
return {
|
|
9
|
+
name: 'better-auth',
|
|
10
|
+
authenticate: async ({ payload, headers })=>{
|
|
11
|
+
const payloadAuth = await getPayloadAuth(payload.config);
|
|
12
|
+
const session = await payloadAuth.betterAuth.api.getSession({
|
|
13
|
+
headers
|
|
14
|
+
});
|
|
15
|
+
const sessionUserIdField = payloadAuth.betterAuth.options.session?.fields?.userId ?? 'userId';
|
|
16
|
+
const userId = session?.session?.[sessionUserIdField] ?? session?.user?.id;
|
|
17
|
+
if (!session || !userId) {
|
|
18
|
+
return {
|
|
19
|
+
user: null
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const user = await payloadAuth.findByID({
|
|
24
|
+
collection: userSlug ?? 'users',
|
|
25
|
+
id: userId
|
|
26
|
+
});
|
|
27
|
+
if (!user) {
|
|
28
|
+
return {
|
|
29
|
+
user: null
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
user: {
|
|
34
|
+
...user,
|
|
35
|
+
collection: userSlug ?? 'users',
|
|
36
|
+
_strategy: 'better-auth'
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
} catch {
|
|
40
|
+
return {
|
|
41
|
+
user: null
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=auth-strategy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/plugin/lib/auth-strategy.ts"],"sourcesContent":["import type { AuthStrategy } from 'payload'\nimport { getPayloadAuth } from './get-payload-auth'\nimport type { TPlugins } from '..'\n\n/**\n * Auth strategy for BetterAuth\n * @param adminRoles - Admin roles\n * @param userSlug - User collection slug\n * @returns Auth strategy\n */\nexport function betterAuthStrategy(adminRoles?: string[], userSlug?: string): AuthStrategy {\n return {\n name: 'better-auth',\n authenticate: async ({ payload, headers }) => {\n const payloadAuth = await getPayloadAuth<NonNullable<TPlugins>>(payload.config)\n const session = await payloadAuth.betterAuth.api.getSession({ headers })\n const sessionUserIdField = payloadAuth.betterAuth.options.session?.fields?.userId ?? 'userId'\n const userId = (session?.session as any)?.[sessionUserIdField] ?? session?.user?.id\n\n if (!session || !userId) {\n return { user: null }\n }\n try {\n const user = await payloadAuth.findByID({\n collection: userSlug ?? 'users',\n id: userId,\n })\n\n if (!user) {\n return { user: null }\n }\n\n return {\n user: {\n ...user,\n collection: userSlug ?? 'users',\n _strategy: 'better-auth',\n },\n }\n } catch {\n return { user: null }\n }\n },\n }\n}\n"],"names":["getPayloadAuth","betterAuthStrategy","adminRoles","userSlug","name","authenticate","payload","headers","payloadAuth","config","session","betterAuth","api","getSession","sessionUserIdField","options","fields","userId","user","id","findByID","collection","_strategy"],"mappings":"AACA,SAASA,cAAc,QAAQ,qBAAoB;AAGnD;;;;;CAKC,GACD,OAAO,SAASC,mBAAmBC,UAAqB,EAAEC,QAAiB;IACzE,OAAO;QACLC,MAAM;QACNC,cAAc,OAAO,EAAEC,OAAO,EAAEC,OAAO,EAAE;YACvC,MAAMC,cAAc,MAAMR,eAAsCM,QAAQG,MAAM;YAC9E,MAAMC,UAAU,MAAMF,YAAYG,UAAU,CAACC,GAAG,CAACC,UAAU,CAAC;gBAAEN;YAAQ;YACtE,MAAMO,qBAAqBN,YAAYG,UAAU,CAACI,OAAO,CAACL,OAAO,EAAEM,QAAQC,UAAU;YACrF,MAAMA,SAAS,AAACP,SAASA,SAAiB,CAACI,mBAAmB,IAAIJ,SAASQ,MAAMC;YAEjF,IAAI,CAACT,WAAW,CAACO,QAAQ;gBACvB,OAAO;oBAAEC,MAAM;gBAAK;YACtB;YACA,IAAI;gBACF,MAAMA,OAAO,MAAMV,YAAYY,QAAQ,CAAC;oBACtCC,YAAYlB,YAAY;oBACxBgB,IAAIF;gBACN;gBAEA,IAAI,CAACC,MAAM;oBACT,OAAO;wBAAEA,MAAM;oBAAK;gBACtB;gBAEA,OAAO;oBACLA,MAAM;wBACJ,GAAGA,IAAI;wBACPG,YAAYlB,YAAY;wBACxBmB,WAAW;oBACb;gBACF;YACF,EAAE,OAAM;gBACN,OAAO;oBAAEJ,MAAM;gBAAK;YACtB;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { PayloadBetterAuthPluginOptions, SanitizedBetterAuthOptions } from '..';
|
|
2
|
+
import { CollectionConfig } from 'payload';
|
|
3
|
+
/**
|
|
4
|
+
* Builds the required collections based on the BetterAuth options and plugins
|
|
5
|
+
*/
|
|
6
|
+
export declare function buildCollectionConfigs({ incomingCollections, requiredCollectionSlugs, pluginOptions, sanitizedBAOptions, }: {
|
|
7
|
+
incomingCollections: CollectionConfig[];
|
|
8
|
+
requiredCollectionSlugs: Set<string>;
|
|
9
|
+
pluginOptions: PayloadBetterAuthPluginOptions;
|
|
10
|
+
sanitizedBAOptions: SanitizedBetterAuthOptions;
|
|
11
|
+
}): CollectionConfig[];
|