peta-auth 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -4
- 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 +24 -31
- package/dist/elysia.mjs +17 -8
- package/dist/errors-DxJ-WUJL.mjs +17 -0
- package/dist/hono.d.mts +23 -1
- package/dist/hono.mjs +14 -4
- 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 -2
- package/dist/nuxt.mjs +19 -7
- 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
|
@@ -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 };
|
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "peta-auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Encrypted cookie sessions for Bun — Hono, ElysiaJS & Nuxt adapters",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/zfadhli/peta-stack.git"
|
|
9
|
+
},
|
|
5
10
|
"type": "module",
|
|
6
11
|
"module": "./dist/index.mjs",
|
|
7
12
|
"types": "./dist/index.d.mts",
|
|
@@ -51,9 +56,9 @@
|
|
|
51
56
|
"typecheck": "tsc --noEmit"
|
|
52
57
|
},
|
|
53
58
|
"dependencies": {
|
|
54
|
-
"
|
|
55
|
-
"cookie": "^1.
|
|
56
|
-
"iron-webcrypto": "^
|
|
59
|
+
"@node-rs/argon2": "^2.0.2",
|
|
60
|
+
"cookie": "^1.1.1",
|
|
61
|
+
"iron-webcrypto": "^2.0.0",
|
|
57
62
|
"jose": "^6.2.3"
|
|
58
63
|
},
|
|
59
64
|
"peerDependencies": {
|
|
@@ -74,9 +79,8 @@
|
|
|
74
79
|
}
|
|
75
80
|
},
|
|
76
81
|
"devDependencies": {
|
|
77
|
-
"@biomejs/biome": "^2.
|
|
78
|
-
"@types/
|
|
79
|
-
"@types/bun": "latest",
|
|
82
|
+
"@biomejs/biome": "^2.5.0",
|
|
83
|
+
"@types/bun": "^1.3.14",
|
|
80
84
|
"elysia": "latest",
|
|
81
85
|
"h3": "latest",
|
|
82
86
|
"hono": "latest",
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
//#region src/crypto.d.ts
|
|
2
|
-
type PasswordsMap = Record<string, string>;
|
|
3
|
-
type Password = PasswordsMap | string;
|
|
4
|
-
declare const sealData: (data: unknown, {
|
|
5
|
-
password,
|
|
6
|
-
ttl
|
|
7
|
-
}: {
|
|
8
|
-
password: Password;
|
|
9
|
-
ttl?: number;
|
|
10
|
-
}) => Promise<string>;
|
|
11
|
-
declare const unsealData: <T>(seal: string, {
|
|
12
|
-
password,
|
|
13
|
-
ttl
|
|
14
|
-
}: {
|
|
15
|
-
password: Password;
|
|
16
|
-
ttl?: number;
|
|
17
|
-
}) => Promise<T>;
|
|
18
|
-
//#endregion
|
|
19
|
-
export { sealData as n, unsealData as r, Password as t };
|
package/dist/oauth/index.d.mts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
//#region src/oauth/index.d.ts
|
|
2
|
-
declare function getOAuthRedirectURL(request: Request): string;
|
|
3
|
-
declare function handlePKCE(request: Request): Promise<{
|
|
4
|
-
codeChallenge?: string;
|
|
5
|
-
codeChallengeMethod?: string;
|
|
6
|
-
codeVerifier?: string;
|
|
7
|
-
setCookie?: string;
|
|
8
|
-
}>;
|
|
9
|
-
declare function handleState(request: Request): {
|
|
10
|
-
state?: string;
|
|
11
|
-
expectedState?: string;
|
|
12
|
-
setCookie?: string;
|
|
13
|
-
};
|
|
14
|
-
interface RequestAccessTokenOptions {
|
|
15
|
-
body?: Record<string, string | undefined>;
|
|
16
|
-
params?: Record<string, string | undefined>;
|
|
17
|
-
headers?: Record<string, string>;
|
|
18
|
-
}
|
|
19
|
-
declare function requestAccessToken<T = unknown>(url: string, options: RequestAccessTokenOptions): Promise<T>;
|
|
20
|
-
declare function redirect(url: string, cookie?: string): Response;
|
|
21
|
-
declare function handleMissingConfiguration(provider: string, missingKeys: string[], onError?: (err: Error) => Response | Promise<Response>): Response | Promise<Response>;
|
|
22
|
-
declare function handleAccessTokenError(provider: string, errorData: Record<string, string>, onError?: (err: Error) => Response | Promise<Response>): Response | Promise<Response>;
|
|
23
|
-
declare function handleInvalidState(provider: string, onError?: (err: Error) => Response | Promise<Response>): Response | Promise<Response>;
|
|
24
|
-
//#endregion
|
|
25
|
-
export { RequestAccessTokenOptions, getOAuthRedirectURL, handleAccessTokenError, handleInvalidState, handleMissingConfiguration, handlePKCE, handleState, redirect, requestAccessToken };
|
package/dist/oauth/index.mjs
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import { parse, serialize } from "cookie";
|
|
2
|
-
//#region src/oauth/index.ts
|
|
3
|
-
const isDevelopment = process.env.NODE_ENV === "development";
|
|
4
|
-
const OAUTH_COOKIE_MAX_AGE = 600;
|
|
5
|
-
function encodeBase64Url(input) {
|
|
6
|
-
return btoa(String.fromCharCode(...input)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
7
|
-
}
|
|
8
|
-
function getRandomBytes(size = 32) {
|
|
9
|
-
return crypto.getRandomValues(new Uint8Array(size));
|
|
10
|
-
}
|
|
11
|
-
function oauthCookieOptions(maxAge) {
|
|
12
|
-
return {
|
|
13
|
-
path: "/",
|
|
14
|
-
httpOnly: true,
|
|
15
|
-
sameSite: "lax",
|
|
16
|
-
secure: !isDevelopment,
|
|
17
|
-
maxAge
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
function getOAuthRedirectURL(request) {
|
|
21
|
-
const url = new URL(request.url);
|
|
22
|
-
return `${url.protocol}//${url.host}${url.pathname}`;
|
|
23
|
-
}
|
|
24
|
-
async function handlePKCE(request) {
|
|
25
|
-
const code = new URL(request.url).searchParams.get("code");
|
|
26
|
-
const cookies = parse(request.headers.get("cookie") ?? "");
|
|
27
|
-
if (code) return { codeVerifier: cookies["peta-auth-pkce"] };
|
|
28
|
-
const verifier = encodeBase64Url(getRandomBytes(32));
|
|
29
|
-
const encoder = new TextEncoder();
|
|
30
|
-
return {
|
|
31
|
-
codeChallenge: encodeBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier)))),
|
|
32
|
-
codeChallengeMethod: "S256",
|
|
33
|
-
setCookie: serialize("peta-auth-pkce", verifier, oauthCookieOptions(OAUTH_COOKIE_MAX_AGE))
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
function handleState(request) {
|
|
37
|
-
const queryState = new URL(request.url).searchParams.get("state");
|
|
38
|
-
const cookies = parse(request.headers.get("cookie") ?? "");
|
|
39
|
-
if (queryState) return {
|
|
40
|
-
state: queryState,
|
|
41
|
-
expectedState: cookies["peta-auth-state"]
|
|
42
|
-
};
|
|
43
|
-
const state = encodeBase64Url(getRandomBytes(8));
|
|
44
|
-
return {
|
|
45
|
-
state,
|
|
46
|
-
setCookie: serialize("peta-auth-state", state, oauthCookieOptions(OAUTH_COOKIE_MAX_AGE))
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
async function requestAccessToken(url, options) {
|
|
50
|
-
const headers = {
|
|
51
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
52
|
-
...options.headers
|
|
53
|
-
};
|
|
54
|
-
const bodyParams = options.body ?? options.params ?? {};
|
|
55
|
-
const body = new URLSearchParams();
|
|
56
|
-
for (const [key, value] of Object.entries(bodyParams)) if (value !== void 0) body.append(key, value);
|
|
57
|
-
const response = await fetch(url, {
|
|
58
|
-
method: "POST",
|
|
59
|
-
headers,
|
|
60
|
-
body: body.toString()
|
|
61
|
-
});
|
|
62
|
-
if (!response.ok) {
|
|
63
|
-
if (response.status === 401) return response.json();
|
|
64
|
-
throw new Error(`OAuth token request failed: ${response.status} ${response.statusText}`);
|
|
65
|
-
}
|
|
66
|
-
return response.json();
|
|
67
|
-
}
|
|
68
|
-
function redirect(url, cookie) {
|
|
69
|
-
const headers = new Headers({ Location: url });
|
|
70
|
-
if (cookie) headers.append("Set-Cookie", cookie);
|
|
71
|
-
return new Response(null, {
|
|
72
|
-
status: 302,
|
|
73
|
-
headers
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
function handleMissingConfiguration(provider, missingKeys, onError) {
|
|
77
|
-
const envVars = missingKeys.map((k) => `PETA_OAUTH_${provider.toUpperCase()}_${k.replace(/([A-Z])/g, "_$1").toUpperCase()}`);
|
|
78
|
-
const err = /* @__PURE__ */ new Error(`Missing ${envVars.join(" or ")} env ${missingKeys.length > 1 ? "variables" : "variable"}.`);
|
|
79
|
-
if (onError) return onError(err);
|
|
80
|
-
return new Response(JSON.stringify({ error: err.message }), {
|
|
81
|
-
status: 500,
|
|
82
|
-
headers: { "Content-Type": "application/json" }
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
function handleAccessTokenError(provider, errorData, onError) {
|
|
86
|
-
const message = `${provider} login failed: ${errorData.error_description || errorData.error || "Unknown error"}`;
|
|
87
|
-
const err = new Error(message);
|
|
88
|
-
if (onError) return onError(err);
|
|
89
|
-
return new Response(JSON.stringify({ error: err.message }), {
|
|
90
|
-
status: 401,
|
|
91
|
-
headers: { "Content-Type": "application/json" }
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
function handleInvalidState(provider, onError) {
|
|
95
|
-
const err = /* @__PURE__ */ new Error(`${provider} login failed: state mismatch`);
|
|
96
|
-
if (onError) return onError(err);
|
|
97
|
-
return new Response(JSON.stringify({ error: err.message }), {
|
|
98
|
-
status: 500,
|
|
99
|
-
headers: { "Content-Type": "application/json" }
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
//#endregion
|
|
103
|
-
export { getOAuthRedirectURL, handleAccessTokenError, handleInvalidState, handleMissingConfiguration, handlePKCE, handleState, redirect, requestAccessToken };
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
import { defaults, seal, unseal } from "iron-webcrypto";
|
|
2
|
-
import { serialize } from "cookie";
|
|
3
|
-
//#region src/crypto.ts
|
|
4
|
-
const fourteenDays = 336 * 3600;
|
|
5
|
-
const currentMajorVersion = 2;
|
|
6
|
-
const versionDelimiter = "~";
|
|
7
|
-
function normalizePassword(password) {
|
|
8
|
-
return typeof password === "string" ? { 1: password } : password;
|
|
9
|
-
}
|
|
10
|
-
function parseSeal(seal) {
|
|
11
|
-
const idx = seal.lastIndexOf(versionDelimiter);
|
|
12
|
-
if (idx === -1) return {
|
|
13
|
-
sealWithoutVersion: seal,
|
|
14
|
-
tokenVersion: null
|
|
15
|
-
};
|
|
16
|
-
return {
|
|
17
|
-
sealWithoutVersion: seal.slice(0, idx),
|
|
18
|
-
tokenVersion: parseInt(seal.slice(idx + 1), 10) || null
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
function createSealData(webcrypto) {
|
|
22
|
-
return async function sealData(data, { password, ttl = fourteenDays }) {
|
|
23
|
-
const map = normalizePassword(password);
|
|
24
|
-
const id = Math.max(...Object.keys(map).map(Number)).toString();
|
|
25
|
-
const pw = map[id];
|
|
26
|
-
return `${await seal(webcrypto, data, {
|
|
27
|
-
id,
|
|
28
|
-
secret: pw
|
|
29
|
-
}, {
|
|
30
|
-
...defaults,
|
|
31
|
-
ttl: ttl * 1e3
|
|
32
|
-
})}${versionDelimiter}${currentMajorVersion}`;
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
function createUnsealData(webcrypto) {
|
|
36
|
-
return async function unsealData(seal, { password, ttl = fourteenDays }) {
|
|
37
|
-
const map = normalizePassword(password);
|
|
38
|
-
const { sealWithoutVersion, tokenVersion } = parseSeal(seal);
|
|
39
|
-
try {
|
|
40
|
-
const data = await unseal(webcrypto, sealWithoutVersion, map, {
|
|
41
|
-
...defaults,
|
|
42
|
-
ttl: ttl * 1e3
|
|
43
|
-
}) ?? {};
|
|
44
|
-
if (tokenVersion === 2) return data;
|
|
45
|
-
const d = data;
|
|
46
|
-
return { ...d.persistent ? d.persistent : {} };
|
|
47
|
-
} catch (err) {
|
|
48
|
-
if (err instanceof Error && /^(Expired seal|Bad hmac value|Cannot find password|Incorrect number of sealed components)/.test(err.message)) return {};
|
|
49
|
-
throw err;
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
function getCrypto() {
|
|
54
|
-
return globalThis.crypto;
|
|
55
|
-
}
|
|
56
|
-
const sealData = createSealData(getCrypto());
|
|
57
|
-
const unsealData = createUnsealData(getCrypto());
|
|
58
|
-
//#endregion
|
|
59
|
-
//#region src/session.ts
|
|
60
|
-
const timestampSkewSec = 60;
|
|
61
|
-
const defaults$1 = {
|
|
62
|
-
ttl: 336 * 3600,
|
|
63
|
-
cookieOptions: {
|
|
64
|
-
httpOnly: true,
|
|
65
|
-
secure: true,
|
|
66
|
-
sameSite: "lax",
|
|
67
|
-
path: "/"
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
function computeMaxAge(ttl) {
|
|
71
|
-
if (ttl === 0) return 2147483647;
|
|
72
|
-
return ttl - timestampSkewSec;
|
|
73
|
-
}
|
|
74
|
-
function resolveConfig(opts) {
|
|
75
|
-
const ttl = opts.ttl ?? defaults$1.ttl;
|
|
76
|
-
const cookieOptions = {
|
|
77
|
-
...defaults$1.cookieOptions,
|
|
78
|
-
...opts.cookieOptions
|
|
79
|
-
};
|
|
80
|
-
if (!("maxAge" in (opts.cookieOptions ?? {}))) cookieOptions.maxAge = computeMaxAge(ttl);
|
|
81
|
-
const passwordsMap = typeof opts.password === "string" ? { 1: opts.password } : opts.password;
|
|
82
|
-
for (const pw of Object.values(passwordsMap)) if (pw.length < 32) throw new Error("peta-auth: password must be at least 32 characters");
|
|
83
|
-
return {
|
|
84
|
-
ttl,
|
|
85
|
-
cookieName: opts.cookieName,
|
|
86
|
-
password: opts.password,
|
|
87
|
-
cookieOptions
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
async function createSessionFromAdapter(adapter, options) {
|
|
91
|
-
let config = resolveConfig(options);
|
|
92
|
-
const seal = adapter.getCookie(config.cookieName);
|
|
93
|
-
const session = seal ? await unsealData(seal, {
|
|
94
|
-
password: config.password,
|
|
95
|
-
ttl: config.ttl
|
|
96
|
-
}) : {};
|
|
97
|
-
session.save = async () => {
|
|
98
|
-
const s = await sealData(session, {
|
|
99
|
-
password: config.password,
|
|
100
|
-
ttl: config.ttl
|
|
101
|
-
});
|
|
102
|
-
const cookieValue = serialize(config.cookieName, s, config.cookieOptions);
|
|
103
|
-
if (cookieValue.length > 4096) throw new Error(`peta-auth: cookie too large (${cookieValue.length} bytes)`);
|
|
104
|
-
adapter.setCookie(cookieValue);
|
|
105
|
-
};
|
|
106
|
-
session.destroy = () => {
|
|
107
|
-
for (const key of Object.keys(session)) if (key !== "save" && key !== "destroy" && key !== "updateConfig") delete session[key];
|
|
108
|
-
adapter.setCookie(serialize(config.cookieName, "", {
|
|
109
|
-
...config.cookieOptions,
|
|
110
|
-
maxAge: 0
|
|
111
|
-
}));
|
|
112
|
-
};
|
|
113
|
-
session.updateConfig = (opts) => {
|
|
114
|
-
config = resolveConfig(opts);
|
|
115
|
-
};
|
|
116
|
-
return session;
|
|
117
|
-
}
|
|
118
|
-
//#endregion
|
|
119
|
-
export { sealData as n, unsealData as r, createSessionFromAdapter as t };
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { t as Password } from "./crypto-Ln_Mj_zp.mjs";
|
|
2
|
-
import { SerializeOptions } from "cookie";
|
|
3
|
-
|
|
4
|
-
//#region src/session.d.ts
|
|
5
|
-
interface SessionOptions {
|
|
6
|
-
password: Password;
|
|
7
|
-
cookieName: string;
|
|
8
|
-
ttl?: number;
|
|
9
|
-
cookieOptions?: Omit<SerializeOptions, 'encode'>;
|
|
10
|
-
}
|
|
11
|
-
interface IronSession {
|
|
12
|
-
save(): Promise<void>;
|
|
13
|
-
destroy(): void;
|
|
14
|
-
updateConfig(options: SessionOptions): void;
|
|
15
|
-
[key: string]: unknown;
|
|
16
|
-
}
|
|
17
|
-
interface SessionAdapter {
|
|
18
|
-
getCookie(name: string): string | undefined;
|
|
19
|
-
setCookie(cookie: string): void;
|
|
20
|
-
}
|
|
21
|
-
declare function createSessionFromAdapter<T extends Record<string, unknown> = Record<string, unknown>>(adapter: SessionAdapter, options: SessionOptions): Promise<T & IronSession>;
|
|
22
|
-
//#endregion
|
|
23
|
-
export { createSessionFromAdapter as i, SessionAdapter as n, SessionOptions as r, IronSession as t };
|