peta-auth 0.1.3 → 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/README.md +93 -185
- package/dist/crypto-DR-ETdLZ.d.mts +35 -0
- package/dist/crypto-WcFV83Nz.mjs +84 -0
- package/dist/csrf.d.mts +31 -2
- package/dist/csrf.mjs +34 -2
- package/dist/elysia.d.mts +22 -1
- package/dist/elysia.mjs +16 -7
- package/dist/errors-DxJ-WUJL.mjs +17 -0
- package/dist/hono.d.mts +22 -1
- package/dist/hono.mjs +13 -3
- package/dist/index.d.mts +59 -5
- package/dist/index.mjs +56 -8
- package/dist/jwt.d.mts +23 -2
- package/dist/jwt.mjs +29 -9
- package/dist/nuxt.d.mts +26 -3
- package/dist/nuxt.mjs +18 -6
- package/dist/oauth/github.d.mts +18 -5
- package/dist/oauth/github.mjs +62 -71
- package/dist/oauth/google.d.mts +20 -7
- package/dist/oauth/google.mjs +65 -75
- package/dist/session-0bF8_7Ui.d.mts +53 -0
- package/dist/session-BGCQ1Z1Q.mjs +87 -0
- package/dist/utils-CKT3C1Lq.mjs +174 -0
- package/package.json +11 -7
- package/dist/crypto-Ln_Mj_zp.d.mts +0 -19
- package/dist/oauth/index.d.mts +0 -25
- package/dist/oauth/index.mjs +0 -103
- package/dist/session-DSwf3XPH.mjs +0 -119
- package/dist/session-z20gaFVT.d.mts +0 -23
package/dist/oauth/github.mjs
CHANGED
|
@@ -1,92 +1,83 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as defineOAuthHandler } from "../utils-CKT3C1Lq.mjs";
|
|
2
2
|
//#region src/oauth/github.ts
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if (!config.clientSecret) missing.push("clientSecret");
|
|
36
|
-
return handleMissingConfiguration("github", missing, onError);
|
|
37
|
-
}
|
|
38
|
-
const redirectURL = config.redirectURL || getOAuthRedirectURL(request);
|
|
39
|
-
const state = handleState(request);
|
|
40
|
-
if (!queryCode) {
|
|
41
|
-
if (config.emailRequired && !config.scope.includes("user:email")) config.scope.push("user:email");
|
|
42
|
-
const authUrl = new URL(config.authorizationURL);
|
|
43
|
-
authUrl.searchParams.set("client_id", config.clientId);
|
|
44
|
-
authUrl.searchParams.set("redirect_uri", redirectURL);
|
|
45
|
-
authUrl.searchParams.set("scope", config.scope.join(" "));
|
|
46
|
-
authUrl.searchParams.set("state", state.state ?? "");
|
|
47
|
-
for (const [k, v] of Object.entries(config.authorizationParams)) authUrl.searchParams.set(k, v);
|
|
48
|
-
return redirect(authUrl.toString(), state.setCookie);
|
|
49
|
-
}
|
|
50
|
-
if (!queryState || queryState !== state.expectedState) return handleInvalidState("github", onError);
|
|
51
|
-
const tokens = await requestAccessToken(config.tokenURL, { body: {
|
|
3
|
+
const githubProvider = {
|
|
4
|
+
name: "github",
|
|
5
|
+
resolveConfig(config) {
|
|
6
|
+
const c = config;
|
|
7
|
+
return {
|
|
8
|
+
authorizationURL: c.authorizationURL ?? "https://github.com/login/oauth/authorize",
|
|
9
|
+
tokenURL: c.tokenURL ?? "https://github.com/login/oauth/access_token",
|
|
10
|
+
apiURL: c.apiURL ?? "https://api.github.com",
|
|
11
|
+
clientId: c.clientId ?? process.env.PETA_OAUTH_GITHUB_CLIENT_ID ?? "",
|
|
12
|
+
clientSecret: c.clientSecret ?? process.env.PETA_OAUTH_GITHUB_CLIENT_SECRET ?? "",
|
|
13
|
+
scope: c.scope ?? [],
|
|
14
|
+
emailRequired: c.emailRequired ?? false,
|
|
15
|
+
authorizationParams: c.authorizationParams ?? {},
|
|
16
|
+
redirectURL: c.redirectURL
|
|
17
|
+
};
|
|
18
|
+
},
|
|
19
|
+
buildAuthUrl(config, redirectURL, state, _pkce) {
|
|
20
|
+
const c = config;
|
|
21
|
+
if (c.emailRequired && !c.scope.includes("user:email")) c.scope.push("user:email");
|
|
22
|
+
const authUrl = new URL(c.authorizationURL);
|
|
23
|
+
authUrl.searchParams.set("client_id", c.clientId);
|
|
24
|
+
authUrl.searchParams.set("redirect_uri", redirectURL);
|
|
25
|
+
authUrl.searchParams.set("scope", c.scope.join(" "));
|
|
26
|
+
authUrl.searchParams.set("state", state.state ?? "");
|
|
27
|
+
for (const [key, value] of Object.entries(c.authorizationParams)) authUrl.searchParams.set(key, value);
|
|
28
|
+
return {
|
|
29
|
+
url: authUrl.toString(),
|
|
30
|
+
cookies: state.setCookie
|
|
31
|
+
};
|
|
32
|
+
},
|
|
33
|
+
requestTokenBody(config, redirectURL, code, _pkce) {
|
|
34
|
+
return {
|
|
52
35
|
grant_type: "authorization_code",
|
|
53
36
|
client_id: config.clientId,
|
|
54
37
|
client_secret: config.clientSecret,
|
|
55
38
|
redirect_uri: redirectURL,
|
|
56
|
-
code
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
39
|
+
code
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
async fetchUser(config, tokens, _request) {
|
|
43
|
+
const c = config;
|
|
60
44
|
const accessToken = tokens.access_token;
|
|
61
|
-
const userResponse = await fetch(`${
|
|
62
|
-
"User-Agent": `GitHub-OAuth-${
|
|
45
|
+
const userResponse = await fetch(`${c.apiURL}/user`, { headers: {
|
|
46
|
+
"User-Agent": `GitHub-OAuth-${c.clientId}`,
|
|
63
47
|
Authorization: `token ${accessToken}`
|
|
64
48
|
} });
|
|
65
|
-
if (!userResponse.ok) {
|
|
66
|
-
const err = /* @__PURE__ */ new Error(`GitHub user fetch failed: ${userResponse.status}`);
|
|
67
|
-
if (onError) return onError(err);
|
|
68
|
-
throw err;
|
|
69
|
-
}
|
|
49
|
+
if (!userResponse.ok) throw new Error(`GitHub user fetch failed: ${userResponse.status}`);
|
|
70
50
|
const user = await userResponse.json();
|
|
71
|
-
if (!user.email &&
|
|
72
|
-
const emailsResponse = await fetch(`${
|
|
73
|
-
"User-Agent": `GitHub-OAuth-${
|
|
51
|
+
if (!user.email && c.emailRequired) {
|
|
52
|
+
const emailsResponse = await fetch(`${c.apiURL}/user/emails`, { headers: {
|
|
53
|
+
"User-Agent": `GitHub-OAuth-${c.clientId}`,
|
|
74
54
|
Authorization: `token ${accessToken}`
|
|
75
55
|
} });
|
|
76
56
|
if (emailsResponse.ok) {
|
|
77
|
-
const primaryEmail = (await emailsResponse.json()).find((
|
|
57
|
+
const primaryEmail = (await emailsResponse.json()).find((entry) => entry.primary);
|
|
78
58
|
if (primaryEmail) {
|
|
79
59
|
user.email = primaryEmail.email;
|
|
80
60
|
user.email_verified = primaryEmail.verified;
|
|
81
61
|
}
|
|
82
62
|
}
|
|
83
63
|
}
|
|
84
|
-
return
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
64
|
+
return user;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Define a GitHub OAuth event handler.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const handle = defineOAuthGitHubEventHandler({
|
|
73
|
+
* onSuccess: async ({ user, tokens }) =>
|
|
74
|
+
* new Response(`Welcome ${user.login}!`),
|
|
75
|
+
* })
|
|
76
|
+
* serve(handle)
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
function defineOAuthGitHubEventHandler(options) {
|
|
80
|
+
return defineOAuthHandler(githubProvider, options);
|
|
90
81
|
}
|
|
91
82
|
//#endregion
|
|
92
83
|
export { defineOAuthGitHubEventHandler };
|
package/dist/oauth/google.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
//#region src/oauth/google.d.ts
|
|
2
|
+
/** Configuration for Google OAuth. */
|
|
2
3
|
interface OAuthGoogleConfig {
|
|
3
4
|
clientId?: string;
|
|
4
5
|
clientSecret?: string;
|
|
@@ -9,6 +10,13 @@ interface OAuthGoogleConfig {
|
|
|
9
10
|
authorizationParams?: Record<string, string>;
|
|
10
11
|
redirectURL?: string;
|
|
11
12
|
}
|
|
13
|
+
interface GoogleTokens {
|
|
14
|
+
access_token: string;
|
|
15
|
+
id_token: string;
|
|
16
|
+
scope: string;
|
|
17
|
+
token_type: string;
|
|
18
|
+
expires_in: number;
|
|
19
|
+
}
|
|
12
20
|
interface GoogleUser {
|
|
13
21
|
sub: string;
|
|
14
22
|
name: string;
|
|
@@ -19,13 +27,18 @@ interface GoogleUser {
|
|
|
19
27
|
email_verified: boolean;
|
|
20
28
|
locale: string;
|
|
21
29
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
30
|
+
/**
|
|
31
|
+
* Define a Google OAuth event handler.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* const handle = defineOAuthGoogleEventHandler({
|
|
36
|
+
* onSuccess: async ({ user }) =>
|
|
37
|
+
* new Response(`Welcome ${user.name}!`),
|
|
38
|
+
* })
|
|
39
|
+
* serve(handle)
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
29
42
|
declare function defineOAuthGoogleEventHandler(options: {
|
|
30
43
|
config?: OAuthGoogleConfig;
|
|
31
44
|
onSuccess: (event: {
|
package/dist/oauth/google.mjs
CHANGED
|
@@ -1,84 +1,74 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as defineOAuthHandler } from "../utils-CKT3C1Lq.mjs";
|
|
2
2
|
//#region src/oauth/google.ts
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
if (!config.clientId || !config.clientSecret) {
|
|
36
|
-
const missing = [];
|
|
37
|
-
if (!config.clientId) missing.push("clientId");
|
|
38
|
-
if (!config.clientSecret) missing.push("clientSecret");
|
|
39
|
-
return handleMissingConfiguration("google", missing, onError);
|
|
3
|
+
const googleProvider = {
|
|
4
|
+
name: "google",
|
|
5
|
+
resolveConfig(config) {
|
|
6
|
+
const c = config;
|
|
7
|
+
return {
|
|
8
|
+
authorizationURL: c.authorizationURL ?? "https://accounts.google.com/o/oauth2/v2/auth",
|
|
9
|
+
tokenURL: c.tokenURL ?? "https://oauth2.googleapis.com/token",
|
|
10
|
+
userInfoURL: c.userInfoURL ?? "https://www.googleapis.com/oauth2/v3/userinfo",
|
|
11
|
+
clientId: c.clientId ?? process.env.PETA_OAUTH_GOOGLE_CLIENT_ID ?? "",
|
|
12
|
+
clientSecret: c.clientSecret ?? process.env.PETA_OAUTH_GOOGLE_CLIENT_SECRET ?? "",
|
|
13
|
+
scope: c.scope ?? [
|
|
14
|
+
"openid",
|
|
15
|
+
"email",
|
|
16
|
+
"profile"
|
|
17
|
+
],
|
|
18
|
+
authorizationParams: c.authorizationParams ?? {},
|
|
19
|
+
redirectURL: c.redirectURL
|
|
20
|
+
};
|
|
21
|
+
},
|
|
22
|
+
buildAuthUrl(config, redirectURL, state, pkce) {
|
|
23
|
+
const c = config;
|
|
24
|
+
const authUrl = new URL(c.authorizationURL);
|
|
25
|
+
authUrl.searchParams.set("client_id", c.clientId);
|
|
26
|
+
authUrl.searchParams.set("redirect_uri", redirectURL);
|
|
27
|
+
authUrl.searchParams.set("scope", c.scope.join(" "));
|
|
28
|
+
authUrl.searchParams.set("response_type", "code");
|
|
29
|
+
authUrl.searchParams.set("state", state.state ?? "");
|
|
30
|
+
if (pkce.codeChallenge) {
|
|
31
|
+
authUrl.searchParams.set("code_challenge", pkce.codeChallenge);
|
|
32
|
+
authUrl.searchParams.set("code_challenge_method", pkce.codeChallengeMethod ?? "S256");
|
|
40
33
|
}
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
authUrl.searchParams.set("state", state.state ?? "");
|
|
51
|
-
if (pkce.codeChallenge) {
|
|
52
|
-
authUrl.searchParams.set("code_challenge", pkce.codeChallenge);
|
|
53
|
-
authUrl.searchParams.set("code_challenge_method", pkce.codeChallengeMethod ?? "S256");
|
|
54
|
-
}
|
|
55
|
-
for (const [k, v] of Object.entries(config.authorizationParams)) authUrl.searchParams.set(k, v);
|
|
56
|
-
const cookies = [state.setCookie, pkce.setCookie].filter(Boolean).join("; ");
|
|
57
|
-
return redirect(authUrl.toString(), cookies || void 0);
|
|
58
|
-
}
|
|
59
|
-
if (!queryState || queryState !== state.expectedState) return handleInvalidState("google", onError);
|
|
60
|
-
const tokens = await requestAccessToken(config.tokenURL, { body: {
|
|
34
|
+
for (const [key, value] of Object.entries(c.authorizationParams)) authUrl.searchParams.set(key, value);
|
|
35
|
+
const cookies = [state.setCookie, pkce.setCookie].filter(Boolean).join("; ");
|
|
36
|
+
return {
|
|
37
|
+
url: authUrl.toString(),
|
|
38
|
+
cookies: cookies || void 0
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
requestTokenBody(config, redirectURL, code, pkce) {
|
|
42
|
+
return {
|
|
61
43
|
grant_type: "authorization_code",
|
|
62
44
|
client_id: config.clientId,
|
|
63
45
|
client_secret: config.clientSecret,
|
|
64
46
|
redirect_uri: redirectURL,
|
|
65
|
-
code
|
|
66
|
-
code_verifier: pkce.codeVerifier
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
47
|
+
code,
|
|
48
|
+
code_verifier: pkce.codeVerifier ?? ""
|
|
49
|
+
};
|
|
50
|
+
},
|
|
51
|
+
async fetchUser(config, tokens, _request) {
|
|
52
|
+
const userURL = config.userInfoURL ?? "https://www.googleapis.com/oauth2/v3/userinfo";
|
|
53
|
+
const userResponse = await fetch(userURL, { headers: { Authorization: `Bearer ${tokens.access_token}` } });
|
|
54
|
+
if (!userResponse.ok) throw new Error(`Google user fetch failed: ${userResponse.status}`);
|
|
55
|
+
return userResponse.json();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Define a Google OAuth event handler.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* const handle = defineOAuthGoogleEventHandler({
|
|
64
|
+
* onSuccess: async ({ user }) =>
|
|
65
|
+
* new Response(`Welcome ${user.name}!`),
|
|
66
|
+
* })
|
|
67
|
+
* serve(handle)
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
function defineOAuthGoogleEventHandler(options) {
|
|
71
|
+
return defineOAuthHandler(googleProvider, options);
|
|
82
72
|
}
|
|
83
73
|
//#endregion
|
|
84
74
|
export { defineOAuthGoogleEventHandler };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { t as Password } from "./crypto-DR-ETdLZ.mjs";
|
|
2
|
+
import { SerializeOptions } from "cookie";
|
|
3
|
+
|
|
4
|
+
//#region src/session.d.ts
|
|
5
|
+
/** Options for creating a cookie session. */
|
|
6
|
+
interface SessionOptions {
|
|
7
|
+
/** Password(s) used to encrypt the session cookie. */
|
|
8
|
+
password: Password;
|
|
9
|
+
/** Name of the cookie. */
|
|
10
|
+
cookieName: string;
|
|
11
|
+
/** Session lifetime in seconds (default 14 days). */
|
|
12
|
+
timeToLive?: number;
|
|
13
|
+
/** Extra cookie serialization options. */
|
|
14
|
+
cookieOptions?: Omit<SerializeOptions, "encode">;
|
|
15
|
+
}
|
|
16
|
+
/** A session instance returned by {@link createSessionFromAdapter}. */
|
|
17
|
+
interface IronSession {
|
|
18
|
+
/** Persist the session to the response cookie. */
|
|
19
|
+
save(): Promise<void>;
|
|
20
|
+
/** Clear the session cookie. */
|
|
21
|
+
destroy(): void;
|
|
22
|
+
/** Update session config at runtime. */
|
|
23
|
+
updateConfig(options: SessionOptions): void;
|
|
24
|
+
/** Arbitrary session data keys. */
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** An adapter between the framework and the session cookie store. */
|
|
28
|
+
interface SessionAdapter {
|
|
29
|
+
/** Read a cookie by name from the incoming request. */
|
|
30
|
+
getCookie(name: string): string | undefined;
|
|
31
|
+
/** Set a cookie on the outgoing response. */
|
|
32
|
+
setCookie(cookie: string): void;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Create a session from a framework adapter.
|
|
36
|
+
*
|
|
37
|
+
* Reads the session cookie (if present), hydrates the data, and
|
|
38
|
+
* returns a session object with {@link IronSession.save},
|
|
39
|
+
* {@link IronSession.destroy}, and {@link IronSession.updateConfig}.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* const session = await createSessionFromAdapter(adapter, {
|
|
44
|
+
* password: "my-32-char-password...",
|
|
45
|
+
* cookieName: "my-session",
|
|
46
|
+
* })
|
|
47
|
+
* session.userId = 42
|
|
48
|
+
* await session.save()
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function createSessionFromAdapter<T extends Record<string, unknown> = Record<string, unknown>>(adapter: SessionAdapter, options: SessionOptions): Promise<T & IronSession>;
|
|
52
|
+
//#endregion
|
|
53
|
+
export { createSessionFromAdapter as i, SessionAdapter as n, SessionOptions as r, IronSession as t };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { n as sealData, r as unsealData, t as normalizePassword } from "./crypto-WcFV83Nz.mjs";
|
|
2
|
+
import { t as PetaAuthError } from "./errors-DxJ-WUJL.mjs";
|
|
3
|
+
import { serialize } from "cookie";
|
|
4
|
+
//#region src/session.ts
|
|
5
|
+
const TIMESTAMP_SKEW_SECONDS = 60;
|
|
6
|
+
const DEFAULTS = {
|
|
7
|
+
timeToLive: 336 * 3600,
|
|
8
|
+
cookieOptions: {
|
|
9
|
+
httpOnly: true,
|
|
10
|
+
sameSite: "lax",
|
|
11
|
+
path: "/"
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
function computeMaxAge(timeToLive) {
|
|
15
|
+
if (timeToLive === 0) return 2147483647;
|
|
16
|
+
return timeToLive - TIMESTAMP_SKEW_SECONDS;
|
|
17
|
+
}
|
|
18
|
+
/** Check whether a session has any user data keys beyond the built-in methods. */
|
|
19
|
+
function sessionHasData(session, key) {
|
|
20
|
+
if (key) return !!session[key];
|
|
21
|
+
return Object.keys(session).some((k) => k !== "save" && k !== "destroy" && k !== "updateConfig");
|
|
22
|
+
}
|
|
23
|
+
/** @internal */
|
|
24
|
+
function resolveConfig(options) {
|
|
25
|
+
const timeToLive = options.timeToLive ?? DEFAULTS.timeToLive;
|
|
26
|
+
const cookieOptions = {
|
|
27
|
+
...DEFAULTS.cookieOptions,
|
|
28
|
+
secure: process.env.NODE_ENV !== "development",
|
|
29
|
+
...options.cookieOptions
|
|
30
|
+
};
|
|
31
|
+
if (!("maxAge" in (options.cookieOptions ?? {}))) cookieOptions.maxAge = computeMaxAge(timeToLive);
|
|
32
|
+
const passwordsMap = normalizePassword(options.password);
|
|
33
|
+
for (const secret of Object.values(passwordsMap)) if (secret.length < 32) throw new PetaAuthError("PASSWORD_TOO_SHORT", "peta-auth: password must be at least 32 characters");
|
|
34
|
+
return {
|
|
35
|
+
timeToLive,
|
|
36
|
+
cookieName: options.cookieName,
|
|
37
|
+
password: options.password,
|
|
38
|
+
cookieOptions
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a session from a framework adapter.
|
|
43
|
+
*
|
|
44
|
+
* Reads the session cookie (if present), hydrates the data, and
|
|
45
|
+
* returns a session object with {@link IronSession.save},
|
|
46
|
+
* {@link IronSession.destroy}, and {@link IronSession.updateConfig}.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const session = await createSessionFromAdapter(adapter, {
|
|
51
|
+
* password: "my-32-char-password...",
|
|
52
|
+
* cookieName: "my-session",
|
|
53
|
+
* })
|
|
54
|
+
* session.userId = 42
|
|
55
|
+
* await session.save()
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
async function createSessionFromAdapter(adapter, options) {
|
|
59
|
+
let config = resolveConfig(options);
|
|
60
|
+
const seal = adapter.getCookie(config.cookieName);
|
|
61
|
+
const session = seal ? await unsealData(seal, {
|
|
62
|
+
password: config.password,
|
|
63
|
+
ttl: config.timeToLive
|
|
64
|
+
}) : {};
|
|
65
|
+
session.save = async () => {
|
|
66
|
+
const s = await sealData(session, {
|
|
67
|
+
password: config.password,
|
|
68
|
+
ttl: config.timeToLive
|
|
69
|
+
});
|
|
70
|
+
const cookieValue = serialize(config.cookieName, s, config.cookieOptions);
|
|
71
|
+
if (cookieValue.length > 4096) throw new PetaAuthError("COOKIE_TOO_LARGE", `peta-auth: cookie too large (${cookieValue.length} bytes)`);
|
|
72
|
+
adapter.setCookie(cookieValue);
|
|
73
|
+
};
|
|
74
|
+
session.destroy = () => {
|
|
75
|
+
for (const key of Object.keys(session)) if (key !== "save" && key !== "destroy" && key !== "updateConfig") delete session[key];
|
|
76
|
+
adapter.setCookie(serialize(config.cookieName, "", {
|
|
77
|
+
...config.cookieOptions,
|
|
78
|
+
maxAge: 0
|
|
79
|
+
}));
|
|
80
|
+
};
|
|
81
|
+
session.updateConfig = (updatedOptions) => {
|
|
82
|
+
config = resolveConfig(updatedOptions);
|
|
83
|
+
};
|
|
84
|
+
return session;
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { sessionHasData as n, createSessionFromAdapter as t };
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { constantTimeEqual } from "./csrf.mjs";
|
|
2
|
+
import { t as PetaAuthError } from "./errors-DxJ-WUJL.mjs";
|
|
3
|
+
import { parse, serialize } from "cookie";
|
|
4
|
+
//#region src/oauth/utils.ts
|
|
5
|
+
const IS_DEVELOPMENT = process.env.NODE_ENV === "development";
|
|
6
|
+
const OAUTH_COOKIE_MAX_AGE = 600;
|
|
7
|
+
function encodeBase64Url(input) {
|
|
8
|
+
return btoa(String.fromCharCode(...input)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
9
|
+
}
|
|
10
|
+
function getRandomBytes(size = 32) {
|
|
11
|
+
return crypto.getRandomValues(new Uint8Array(size));
|
|
12
|
+
}
|
|
13
|
+
function oauthCookieOptions(maxAge) {
|
|
14
|
+
return {
|
|
15
|
+
path: "/",
|
|
16
|
+
httpOnly: true,
|
|
17
|
+
sameSite: "lax",
|
|
18
|
+
secure: !IS_DEVELOPMENT,
|
|
19
|
+
maxAge
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Extract the OAuth redirect URL from a request.
|
|
24
|
+
*/
|
|
25
|
+
function getOAuthRedirectURL(request) {
|
|
26
|
+
const url = new URL(request.url);
|
|
27
|
+
return `${url.protocol}//${url.host}${url.pathname}`;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Handle PKCE (Proof Key for Code Exchange) for OAuth flows.
|
|
31
|
+
*
|
|
32
|
+
* On the initial redirect leg it generates a code verifier + challenge.
|
|
33
|
+
* On the callback leg it extracts the stored verifier from the cookie.
|
|
34
|
+
*/
|
|
35
|
+
async function handlePKCE(request) {
|
|
36
|
+
const code = new URL(request.url).searchParams.get("code");
|
|
37
|
+
const cookies = parse(request.headers.get("cookie") ?? "");
|
|
38
|
+
if (code) return { codeVerifier: cookies["peta-auth-pkce"] };
|
|
39
|
+
const verifier = encodeBase64Url(getRandomBytes(32));
|
|
40
|
+
const encoder = new TextEncoder();
|
|
41
|
+
return {
|
|
42
|
+
codeChallenge: encodeBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier)))),
|
|
43
|
+
codeChallengeMethod: "S256",
|
|
44
|
+
setCookie: serialize("peta-auth-pkce", verifier, oauthCookieOptions(OAUTH_COOKIE_MAX_AGE))
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Handle OAuth state parameter for CSRF protection.
|
|
49
|
+
*/
|
|
50
|
+
function handleState(request) {
|
|
51
|
+
const queryState = new URL(request.url).searchParams.get("state");
|
|
52
|
+
const cookies = parse(request.headers.get("cookie") ?? "");
|
|
53
|
+
if (queryState) return {
|
|
54
|
+
state: queryState,
|
|
55
|
+
expectedState: cookies["peta-auth-state"]
|
|
56
|
+
};
|
|
57
|
+
const state = encodeBase64Url(getRandomBytes(8));
|
|
58
|
+
return {
|
|
59
|
+
state,
|
|
60
|
+
setCookie: serialize("peta-auth-state", state, oauthCookieOptions(OAUTH_COOKIE_MAX_AGE))
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Exchange an authorization code for an access token.
|
|
65
|
+
*/
|
|
66
|
+
async function requestAccessToken(url, options) {
|
|
67
|
+
const headers = {
|
|
68
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
69
|
+
...options.headers
|
|
70
|
+
};
|
|
71
|
+
const bodyParams = options.body ?? options.params ?? {};
|
|
72
|
+
const body = new URLSearchParams();
|
|
73
|
+
for (const [key, value] of Object.entries(bodyParams)) if (value !== void 0) body.append(key, value);
|
|
74
|
+
const response = await fetch(url, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers,
|
|
77
|
+
body: body.toString()
|
|
78
|
+
});
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
if (response.status === 401) return response.json();
|
|
81
|
+
throw new PetaAuthError("OAUTH_TOKEN_FAILED", `OAuth token request failed: ${response.status} ${response.statusText}`);
|
|
82
|
+
}
|
|
83
|
+
return response.json();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Create a 302 redirect response, optionally with a cookie.
|
|
87
|
+
*/
|
|
88
|
+
function redirect(url, cookie) {
|
|
89
|
+
const headers = new Headers({ Location: url });
|
|
90
|
+
if (cookie) headers.append("Set-Cookie", cookie);
|
|
91
|
+
return new Response(null, {
|
|
92
|
+
status: 302,
|
|
93
|
+
headers
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Create a JSON error response with the given status code.
|
|
98
|
+
*/
|
|
99
|
+
function jsonError(error, status) {
|
|
100
|
+
return new Response(JSON.stringify({ error: error.message }), {
|
|
101
|
+
status,
|
|
102
|
+
headers: { "Content-Type": "application/json" }
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Handle missing OAuth configuration.
|
|
107
|
+
*/
|
|
108
|
+
function handleMissingConfiguration(provider, missingKeys, onError) {
|
|
109
|
+
const envVars = missingKeys.map((key) => `PETA_OAUTH_${provider.toUpperCase()}_${key.replace(/([A-Z])/g, "_$1").toUpperCase()}`);
|
|
110
|
+
const error = /* @__PURE__ */ new Error(`Missing ${envVars.join(" or ")} env ${missingKeys.length > 1 ? "variables" : "variable"}.`);
|
|
111
|
+
if (onError) return onError(error);
|
|
112
|
+
return jsonError(error, 500);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Handle OAuth access token errors.
|
|
116
|
+
*/
|
|
117
|
+
function handleAccessTokenError(provider, errorData, onError) {
|
|
118
|
+
const message = `${provider} login failed: ${errorData.error_description || errorData.error || "Unknown error"}`;
|
|
119
|
+
const error = new Error(message);
|
|
120
|
+
if (onError) return onError(error);
|
|
121
|
+
return jsonError(error, 401);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Define an OAuth event handler using a provider-specific config.
|
|
125
|
+
*
|
|
126
|
+
* Handles the shared OAuth flow (redirect, callback, token exchange, user fetch)
|
|
127
|
+
* while delegating provider-specific behavior to the config callbacks.
|
|
128
|
+
*/
|
|
129
|
+
function defineOAuthHandler(provider, options) {
|
|
130
|
+
const { config: userConfig = {}, onSuccess, onError } = options;
|
|
131
|
+
return async (request) => {
|
|
132
|
+
const config = provider.resolveConfig(userConfig);
|
|
133
|
+
const url = new URL(request.url);
|
|
134
|
+
const queryCode = url.searchParams.get("code");
|
|
135
|
+
const queryError = url.searchParams.get("error");
|
|
136
|
+
const queryState = url.searchParams.get("state");
|
|
137
|
+
if (queryError) {
|
|
138
|
+
const error = /* @__PURE__ */ new Error(`${provider.name} login failed: ${queryError}`);
|
|
139
|
+
if (onError) return onError(error);
|
|
140
|
+
return jsonError(error, 401);
|
|
141
|
+
}
|
|
142
|
+
if (!config.clientId || !config.clientSecret) {
|
|
143
|
+
const missing = [];
|
|
144
|
+
if (!config.clientId) missing.push("clientId");
|
|
145
|
+
if (!config.clientSecret) missing.push("clientSecret");
|
|
146
|
+
return handleMissingConfiguration(provider.name, missing, onError);
|
|
147
|
+
}
|
|
148
|
+
const redirectURL = config.redirectURL || getOAuthRedirectURL(request);
|
|
149
|
+
const state = handleState(request);
|
|
150
|
+
const pkce = await handlePKCE(request);
|
|
151
|
+
if (!queryCode) {
|
|
152
|
+
const { url: authUrl, cookies } = provider.buildAuthUrl(config, redirectURL, state, pkce);
|
|
153
|
+
return redirect(authUrl, cookies);
|
|
154
|
+
}
|
|
155
|
+
if (!queryState || !state.expectedState || !constantTimeEqual(queryState, state.expectedState)) return handleInvalidState(provider.name, onError);
|
|
156
|
+
const tokens = await requestAccessToken(config.tokenURL, { body: provider.requestTokenBody(config, redirectURL, queryCode, pkce) });
|
|
157
|
+
if (tokens.error) return handleAccessTokenError(provider.name, tokens, onError);
|
|
158
|
+
return onSuccess({
|
|
159
|
+
user: await provider.fetchUser(config, tokens, request),
|
|
160
|
+
tokens,
|
|
161
|
+
request
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Handle OAuth state mismatch.
|
|
167
|
+
*/
|
|
168
|
+
function handleInvalidState(provider, onError) {
|
|
169
|
+
const error = /* @__PURE__ */ new Error(`${provider} login failed: state mismatch`);
|
|
170
|
+
if (onError) return onError(error);
|
|
171
|
+
return jsonError(error, 500);
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
export { defineOAuthHandler as t };
|