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/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "peta-auth",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
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 };
|