peta-auth 0.1.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 +21 -0
- package/README.md +256 -0
- package/dist/elysia.d.mts +38 -0
- package/dist/elysia.mjs +17 -0
- package/dist/hono.d.mts +12 -0
- package/dist/hono.mjs +15 -0
- package/dist/index.d.mts +10 -0
- package/dist/index.mjs +11 -0
- package/dist/nuxt.d.mts +7 -0
- package/dist/nuxt.mjs +18 -0
- package/dist/oauth/github.d.mts +37 -0
- package/dist/oauth/github.mjs +92 -0
- package/dist/oauth/google.d.mts +39 -0
- package/dist/oauth/google.mjs +84 -0
- package/dist/oauth/index.d.mts +25 -0
- package/dist/oauth/index.mjs +103 -0
- package/dist/session-DSwf3XPH.mjs +119 -0
- package/dist/session-DYH_m3lO.d.mts +40 -0
- package/package.json +76 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jason Miller
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
# peta-auth
|
|
2
|
+
|
|
3
|
+
Encrypted cookie sessions for Bun — with first-class adapters for **Hono**, **ElysiaJS**, and **Nuxt**.
|
|
4
|
+
|
|
5
|
+
Uses `iron-webcrypto` (AES-256-CBC + HMAC-SHA256) to seal session data into stateless, signed-and-encrypted cookies. No server-side storage needed.
|
|
6
|
+
|
|
7
|
+
Inspired by [iron-session](https://github.com/vvo/iron-session) and [nuxt-auth-utils](https://github.com/atinux/nuxt-auth-utils).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
bun add peta-auth
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Install only the framework adapters you need:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
bun add hono # for peta-auth/hono
|
|
17
|
+
bun add elysia # for peta-auth/elysia
|
|
18
|
+
# Nuxt already includes h3 — just add peta-auth
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
### Hono
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { Hono } from 'hono'
|
|
29
|
+
import { session } from 'peta-auth/hono'
|
|
30
|
+
|
|
31
|
+
const app = new Hono()
|
|
32
|
+
|
|
33
|
+
app.use('*', session({
|
|
34
|
+
password: process.env.SESSION_SECRET!,
|
|
35
|
+
cookieName: 'my-session',
|
|
36
|
+
}))
|
|
37
|
+
|
|
38
|
+
app.get('/profile', (c) => {
|
|
39
|
+
const s = c.var.session
|
|
40
|
+
if (!s.user) return c.json({ error: 'unauthorized' }, 401)
|
|
41
|
+
return c.json(s.user)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
app.post('/login', async (c) => {
|
|
45
|
+
const { name } = await c.req.json()
|
|
46
|
+
Object.assign(c.var.session, { user: { name }, loggedInAt: Date.now() })
|
|
47
|
+
await c.var.session.save()
|
|
48
|
+
return c.json({ ok: true })
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
app.post('/logout', (c) => {
|
|
52
|
+
c.var.session.destroy()
|
|
53
|
+
return c.json({ ok: true })
|
|
54
|
+
})
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Run with `bun run file.ts` — Bun auto-starts the server.
|
|
58
|
+
|
|
59
|
+
### ElysiaJS
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { Elysia } from 'elysia'
|
|
63
|
+
import { session } from 'peta-auth/elysia'
|
|
64
|
+
|
|
65
|
+
new Elysia()
|
|
66
|
+
.use(session({
|
|
67
|
+
password: process.env.SESSION_SECRET!,
|
|
68
|
+
cookieName: 'my-session',
|
|
69
|
+
}))
|
|
70
|
+
.get('/profile', ({ session: s }) =>
|
|
71
|
+
!s.user ? Response.json({ error: 'unauthorized' }, { status: 401 })
|
|
72
|
+
: Response.json(s.user))
|
|
73
|
+
.post('/login', async ({ session: s, body }: any) => {
|
|
74
|
+
s.user = { name: body.name }
|
|
75
|
+
await s.save()
|
|
76
|
+
return Response.json({ ok: true })
|
|
77
|
+
})
|
|
78
|
+
.post('/logout', ({ session: s }) => {
|
|
79
|
+
s.destroy()
|
|
80
|
+
return Response.json({ ok: true })
|
|
81
|
+
})
|
|
82
|
+
.listen(3000)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Nuxt
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
// server/api/profile.get.ts
|
|
89
|
+
import { useSession } from 'peta-auth/nuxt'
|
|
90
|
+
|
|
91
|
+
export default defineEventHandler(async (event) => {
|
|
92
|
+
const session = await useSession(event, {
|
|
93
|
+
password: process.env.NUXT_SESSION_PASSWORD!,
|
|
94
|
+
cookieName: 'nuxt-session',
|
|
95
|
+
})
|
|
96
|
+
if (!session.user) throw createError({ statusCode: 401 })
|
|
97
|
+
return session.user
|
|
98
|
+
})
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
// server/api/login.post.ts
|
|
103
|
+
import { useSession } from 'peta-auth/nuxt'
|
|
104
|
+
|
|
105
|
+
export default defineEventHandler(async (event) => {
|
|
106
|
+
const session = await useSession(event, {
|
|
107
|
+
password: process.env.NUXT_SESSION_PASSWORD!,
|
|
108
|
+
cookieName: 'nuxt-session',
|
|
109
|
+
})
|
|
110
|
+
const body = await readBody(event)
|
|
111
|
+
Object.assign(session, { user: body, loggedInAt: Date.now() })
|
|
112
|
+
await session.save()
|
|
113
|
+
return { ok: true }
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Set `NUXT_SESSION_PASSWORD` in your `.env`.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## API
|
|
122
|
+
|
|
123
|
+
### `session` middleware (framework adapters)
|
|
124
|
+
|
|
125
|
+
Each adapter exports a `session(options)` function that reads the session from the incoming cookie and attaches it to the framework's context.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
session({
|
|
129
|
+
password: process.env.SESSION_SECRET!, // required, at least 32 chars
|
|
130
|
+
cookieName: 'my-session', // required
|
|
131
|
+
ttl: 60 * 60 * 24 * 14, // optional, default 14 days
|
|
132
|
+
cookieOptions: { httpOnly: true, secure: true, sameSite: 'lax', path: '/' },
|
|
133
|
+
})
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Password rotation is supported via object syntax:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
session({ password: { 1: 'old-pw', 2: 'new-pw' }, cookieName: 'my-session' })
|
|
140
|
+
// new cookies use key 2, old cookies still decrypt with key 1
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Session object
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
interface IronSession {
|
|
147
|
+
save(): Promise<void> // seal & write the cookie
|
|
148
|
+
destroy(): void // clear data & expire the cookie
|
|
149
|
+
updateConfig(opts): void // change options for this request
|
|
150
|
+
[key: string]: unknown // your data
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Low-level
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { createSessionFromAdapter, sealData, unsealData } from 'peta-auth'
|
|
158
|
+
import { hashPassword, verifyPassword } from 'peta-auth'
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- **`createSessionFromAdapter(adapter, options)`** — takes a `SessionAdapter` (`{ getCookie, setCookie }`). Used internally by all framework adapters.
|
|
162
|
+
- **`sealData(data, { password, ttl? })` / `unsealData<T>(seal, { password, ttl? })`** — encrypt/decrypt arbitrary data.
|
|
163
|
+
- **`hashPassword(password, { cost? })` / `verifyPassword(hash, password)`** — bcrypt hashing via `bcryptjs`. Default cost: 10.
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## OAuth
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import { defineOAuthGitHubEventHandler } from 'peta-auth/oauth/github'
|
|
171
|
+
import { defineOAuthGoogleEventHandler } from 'peta-auth/oauth/google'
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Each returns a `(request: Request) => Promise<Response>` handler — framework-agnostic.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
import { defineOAuthGitHubEventHandler } from 'peta-auth/oauth/github'
|
|
178
|
+
import { session } from 'peta-auth/hono'
|
|
179
|
+
|
|
180
|
+
const app = new Hono()
|
|
181
|
+
app.use('*', session({ password: process.env.SESSION_SECRET!, cookieName: 'my-session' }))
|
|
182
|
+
|
|
183
|
+
const githubHandler = defineOAuthGitHubEventHandler({
|
|
184
|
+
config: {
|
|
185
|
+
clientId: process.env.GITHUB_CLIENT_ID!,
|
|
186
|
+
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
187
|
+
},
|
|
188
|
+
async onSuccess({ user, tokens }) {
|
|
189
|
+
// The user is authenticated — redirect back to your app.
|
|
190
|
+
// To create a session, use the `request` parameter:
|
|
191
|
+
// onSuccess({ user, tokens, request })
|
|
192
|
+
return new Response(null, { status: 302, headers: { Location: '/' } })
|
|
193
|
+
},
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
app.get('/auth/github', async (c) => githubHandler(c.req.raw))
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Requires env vars: `PETA_OAUTH_GITHUB_CLIENT_ID`, `PETA_OAUTH_GITHUB_CLIENT_SECRET` (or `PETA_OAUTH_GOOGLE_*`).
|
|
200
|
+
|
|
201
|
+
The `onSuccess` callback receives `request: Request` — create a session from the raw request inside the handler:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import { createSessionFromAdapter } from 'peta-auth'
|
|
205
|
+
import { parse } from 'cookie'
|
|
206
|
+
|
|
207
|
+
async onSuccess({ user, tokens, request }) {
|
|
208
|
+
const res = new Response(null, { status: 302, headers: { Location: '/' } })
|
|
209
|
+
const session = await createSessionFromAdapter({
|
|
210
|
+
getCookie: (name) => parse(request.headers.get('cookie') ?? '')[name],
|
|
211
|
+
setCookie: (v) => res.headers.append('Set-Cookie', v),
|
|
212
|
+
}, { password: process.env.SESSION_SECRET!, cookieName: 'my-session' })
|
|
213
|
+
session.user = { id: user.id, login: user.login }
|
|
214
|
+
await session.save()
|
|
215
|
+
return res
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
## Examples
|
|
222
|
+
|
|
223
|
+
Full runnable examples in [`examples/`](./examples). All work with zero config (demo password fallback built in):
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
bun run examples/hono-basic.ts # Hono — session CRUD, views counter
|
|
227
|
+
bun run examples/elysia-basic.ts # Elysia — session CRUD, views counter
|
|
228
|
+
bun run examples/password-auth.ts # Hono — signup + login with bcrypt
|
|
229
|
+
bun run examples/oauth-github.ts # Hono — GitHub OAuth
|
|
230
|
+
bun run examples/oauth-google.ts # Hono — Google OAuth (PKCE)
|
|
231
|
+
bun run examples/elysia-password.ts # Elysia — signup + login with bcrypt
|
|
232
|
+
bun run examples/elysia-oauth-github.ts # Elysia — GitHub OAuth
|
|
233
|
+
bun run examples/elysia-oauth-google.ts # Elysia — Google OAuth (PKCE)
|
|
234
|
+
cd examples/nuxt # Nuxt — server routes with useSession
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## How it works
|
|
240
|
+
|
|
241
|
+
Session data is serialized, encrypted with AES-256-CBC, integrity-protected with HMAC-SHA256, and stored in a single cookie. The session is **stateless** — no database, no Redis, no server-side storage.
|
|
242
|
+
|
|
243
|
+
- `session.save()` — seals the current data into the cookie
|
|
244
|
+
- `session.destroy()` — clears data and expires the cookie
|
|
245
|
+
- Multiple mutations can be made before `save()` — only one seal operation
|
|
246
|
+
- Cookie size limit of 4096 bytes applies (throws if exceeded)
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## Scripts
|
|
251
|
+
|
|
252
|
+
```bash
|
|
253
|
+
bun test # 43 tests across 9 files
|
|
254
|
+
bun run build # tsdown → dist/ (16 files, 24 kB)
|
|
255
|
+
bun run prepublish # build + publish
|
|
256
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { r as SessionOptions, t as IronSession } from "./session-DYH_m3lO.mjs";
|
|
2
|
+
import { Elysia } from "elysia";
|
|
3
|
+
|
|
4
|
+
//#region src/elysia.d.ts
|
|
5
|
+
declare function session(options: SessionOptions): Elysia<"", {
|
|
6
|
+
decorator: {};
|
|
7
|
+
store: {};
|
|
8
|
+
derive: {};
|
|
9
|
+
resolve: {};
|
|
10
|
+
}, {
|
|
11
|
+
typebox: {};
|
|
12
|
+
error: {};
|
|
13
|
+
}, {
|
|
14
|
+
schema: {};
|
|
15
|
+
standaloneSchema: {};
|
|
16
|
+
macro: {};
|
|
17
|
+
macroFn: {};
|
|
18
|
+
parser: {};
|
|
19
|
+
response: {};
|
|
20
|
+
}, {}, {
|
|
21
|
+
derive: {
|
|
22
|
+
readonly session: Record<string, unknown> & IronSession;
|
|
23
|
+
};
|
|
24
|
+
resolve: {};
|
|
25
|
+
schema: {};
|
|
26
|
+
standaloneSchema: {};
|
|
27
|
+
response: import("elysia").ExtractErrorFromHandle<{
|
|
28
|
+
readonly session: Record<string, unknown> & IronSession;
|
|
29
|
+
}>;
|
|
30
|
+
}, {
|
|
31
|
+
derive: {};
|
|
32
|
+
resolve: {};
|
|
33
|
+
schema: {};
|
|
34
|
+
standaloneSchema: {};
|
|
35
|
+
response: {};
|
|
36
|
+
}>;
|
|
37
|
+
//#endregion
|
|
38
|
+
export { session };
|
package/dist/elysia.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { t as createSessionFromAdapter } from "./session-DSwf3XPH.mjs";
|
|
2
|
+
import { parse } from "cookie";
|
|
3
|
+
import { Elysia } from "elysia";
|
|
4
|
+
//#region src/elysia.ts
|
|
5
|
+
function session(options) {
|
|
6
|
+
return new Elysia({ name: "peta-auth" }).derive({ as: "scoped" }, async ({ headers: reqHeaders, set }) => {
|
|
7
|
+
const cookieStr = reqHeaders instanceof Headers ? reqHeaders.get("cookie") ?? "" : reqHeaders.cookie ?? "";
|
|
8
|
+
return { session: await createSessionFromAdapter({
|
|
9
|
+
getCookie: (name) => parse(cookieStr)[name],
|
|
10
|
+
setCookie: (v) => {
|
|
11
|
+
set.headers["Set-Cookie"] = v;
|
|
12
|
+
}
|
|
13
|
+
}, options) };
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { session };
|
package/dist/hono.d.mts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { r as SessionOptions, t as IronSession } from "./session-DYH_m3lO.mjs";
|
|
2
|
+
import { MiddlewareHandler } from "hono";
|
|
3
|
+
|
|
4
|
+
//#region src/hono.d.ts
|
|
5
|
+
declare module 'hono' {
|
|
6
|
+
interface ContextVariableMap {
|
|
7
|
+
session: IronSession;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
declare function session(options: SessionOptions): MiddlewareHandler;
|
|
11
|
+
//#endregion
|
|
12
|
+
export { session };
|
package/dist/hono.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { t as createSessionFromAdapter } from "./session-DSwf3XPH.mjs";
|
|
2
|
+
import { parse } from "cookie";
|
|
3
|
+
import { createMiddleware } from "hono/factory";
|
|
4
|
+
//#region src/hono.ts
|
|
5
|
+
function session(options) {
|
|
6
|
+
return createMiddleware(async (c, next) => {
|
|
7
|
+
c.set("session", await createSessionFromAdapter({
|
|
8
|
+
getCookie: (name) => parse(c.req.header("cookie") ?? "")[name],
|
|
9
|
+
setCookie: (v) => c.res.headers.append("Set-Cookie", v)
|
|
10
|
+
}, options));
|
|
11
|
+
await next();
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { session };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { a as Password, i as createSessionFromAdapter, n as SessionAdapter, o as sealData, r as SessionOptions, s as unsealData, t as IronSession } from "./session-DYH_m3lO.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/password.d.ts
|
|
4
|
+
interface HashOptions {
|
|
5
|
+
cost?: number;
|
|
6
|
+
}
|
|
7
|
+
declare function hashPassword(password: string, options?: HashOptions): Promise<string>;
|
|
8
|
+
declare function verifyPassword(hash: string, password: string): Promise<boolean>;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { type IronSession, type Password, type SessionAdapter, type SessionOptions, createSessionFromAdapter, hashPassword, sealData, unsealData, verifyPassword };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { n as sealData, r as unsealData, t as createSessionFromAdapter } from "./session-DSwf3XPH.mjs";
|
|
2
|
+
import { compareSync, genSaltSync, hashSync } from "bcryptjs";
|
|
3
|
+
//#region src/password.ts
|
|
4
|
+
async function hashPassword(password, options = {}) {
|
|
5
|
+
return hashSync(password, genSaltSync(options.cost ?? 10));
|
|
6
|
+
}
|
|
7
|
+
async function verifyPassword(hash, password) {
|
|
8
|
+
return compareSync(password, hash);
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
export { createSessionFromAdapter, hashPassword, sealData, unsealData, verifyPassword };
|
package/dist/nuxt.d.mts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { r as SessionOptions, t as IronSession } from "./session-DYH_m3lO.mjs";
|
|
2
|
+
import { H3Event } from "h3";
|
|
3
|
+
|
|
4
|
+
//#region src/nuxt.d.ts
|
|
5
|
+
declare function useSession(event: H3Event, options: SessionOptions): Promise<IronSession>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { useSession };
|
package/dist/nuxt.mjs
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { t as createSessionFromAdapter } from "./session-DSwf3XPH.mjs";
|
|
2
|
+
import { appendHeader, getCookie } from "h3";
|
|
3
|
+
//#region src/nuxt.ts
|
|
4
|
+
function useSession(event, options) {
|
|
5
|
+
const password = options.password ?? process.env.NUXT_SESSION_PASSWORD;
|
|
6
|
+
if (!password) throw new Error("peta-auth/nuxt: NUXT_SESSION_PASSWORD is required");
|
|
7
|
+
return createSessionFromAdapter({
|
|
8
|
+
getCookie: (name) => getCookie(event, name),
|
|
9
|
+
setCookie: (value) => appendHeader(event, "Set-Cookie", value)
|
|
10
|
+
}, {
|
|
11
|
+
password,
|
|
12
|
+
cookieName: options?.cookieName ?? "nuxt-session",
|
|
13
|
+
ttl: options?.ttl,
|
|
14
|
+
cookieOptions: options?.cookieOptions
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { useSession };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/oauth/github.d.ts
|
|
2
|
+
interface OAuthGitHubConfig {
|
|
3
|
+
clientId?: string;
|
|
4
|
+
clientSecret?: string;
|
|
5
|
+
scope?: string[];
|
|
6
|
+
emailRequired?: boolean;
|
|
7
|
+
authorizationURL?: string;
|
|
8
|
+
tokenURL?: string;
|
|
9
|
+
apiURL?: string;
|
|
10
|
+
authorizationParams?: Record<string, string>;
|
|
11
|
+
redirectURL?: string;
|
|
12
|
+
}
|
|
13
|
+
interface GitHubUser {
|
|
14
|
+
login: string;
|
|
15
|
+
id: number;
|
|
16
|
+
node_id: string;
|
|
17
|
+
avatar_url: string;
|
|
18
|
+
name: string;
|
|
19
|
+
email: string | null;
|
|
20
|
+
email_verified?: boolean;
|
|
21
|
+
}
|
|
22
|
+
interface GitHubTokens {
|
|
23
|
+
access_token: string;
|
|
24
|
+
scope: string;
|
|
25
|
+
token_type: string;
|
|
26
|
+
}
|
|
27
|
+
declare function defineOAuthGitHubEventHandler(options: {
|
|
28
|
+
config?: OAuthGitHubConfig;
|
|
29
|
+
onSuccess: (event: {
|
|
30
|
+
user: GitHubUser;
|
|
31
|
+
tokens: GitHubTokens;
|
|
32
|
+
request: Request;
|
|
33
|
+
}) => Response | Promise<Response>;
|
|
34
|
+
onError?: (error: Error) => Response | Promise<Response>;
|
|
35
|
+
}): (request: Request) => Promise<Response>;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { OAuthGitHubConfig, defineOAuthGitHubEventHandler };
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { getOAuthRedirectURL, handleAccessTokenError, handleInvalidState, handleMissingConfiguration, handleState, redirect, requestAccessToken } from "./index.mjs";
|
|
2
|
+
//#region src/oauth/github.ts
|
|
3
|
+
function resolveGitHubConfig(config) {
|
|
4
|
+
return {
|
|
5
|
+
authorizationURL: config.authorizationURL ?? "https://github.com/login/oauth/authorize",
|
|
6
|
+
tokenURL: config.tokenURL ?? "https://github.com/login/oauth/access_token",
|
|
7
|
+
apiURL: config.apiURL ?? "https://api.github.com",
|
|
8
|
+
clientId: config.clientId ?? process.env.PETA_OAUTH_GITHUB_CLIENT_ID ?? "",
|
|
9
|
+
clientSecret: config.clientSecret ?? process.env.PETA_OAUTH_GITHUB_CLIENT_SECRET ?? "",
|
|
10
|
+
scope: config.scope ?? [],
|
|
11
|
+
emailRequired: config.emailRequired ?? false,
|
|
12
|
+
authorizationParams: config.authorizationParams ?? {},
|
|
13
|
+
redirectURL: config.redirectURL
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function defineOAuthGitHubEventHandler(options) {
|
|
17
|
+
const { config: userConfig = {}, onSuccess, onError } = options;
|
|
18
|
+
return async (request) => {
|
|
19
|
+
const config = resolveGitHubConfig(userConfig);
|
|
20
|
+
const url = new URL(request.url);
|
|
21
|
+
const queryCode = url.searchParams.get("code");
|
|
22
|
+
const queryError = url.searchParams.get("error");
|
|
23
|
+
const queryState = url.searchParams.get("state");
|
|
24
|
+
if (queryError) {
|
|
25
|
+
const err = /* @__PURE__ */ new Error(`GitHub login failed: ${queryError}`);
|
|
26
|
+
if (onError) return onError(err);
|
|
27
|
+
return new Response(JSON.stringify({ error: err.message }), {
|
|
28
|
+
status: 401,
|
|
29
|
+
headers: { "Content-Type": "application/json" }
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
if (!config.clientId || !config.clientSecret) {
|
|
33
|
+
const missing = [];
|
|
34
|
+
if (!config.clientId) missing.push("clientId");
|
|
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: {
|
|
52
|
+
grant_type: "authorization_code",
|
|
53
|
+
client_id: config.clientId,
|
|
54
|
+
client_secret: config.clientSecret,
|
|
55
|
+
redirect_uri: redirectURL,
|
|
56
|
+
code: queryCode
|
|
57
|
+
} });
|
|
58
|
+
const tokensRecord = tokens;
|
|
59
|
+
if (tokensRecord.error) return handleAccessTokenError("github", tokensRecord, onError);
|
|
60
|
+
const accessToken = tokens.access_token;
|
|
61
|
+
const userResponse = await fetch(`${config.apiURL}/user`, { headers: {
|
|
62
|
+
"User-Agent": `GitHub-OAuth-${config.clientId}`,
|
|
63
|
+
Authorization: `token ${accessToken}`
|
|
64
|
+
} });
|
|
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
|
+
}
|
|
70
|
+
const user = await userResponse.json();
|
|
71
|
+
if (!user.email && config.emailRequired) {
|
|
72
|
+
const emailsResponse = await fetch(`${config.apiURL}/user/emails`, { headers: {
|
|
73
|
+
"User-Agent": `GitHub-OAuth-${config.clientId}`,
|
|
74
|
+
Authorization: `token ${accessToken}`
|
|
75
|
+
} });
|
|
76
|
+
if (emailsResponse.ok) {
|
|
77
|
+
const primaryEmail = (await emailsResponse.json()).find((e) => e.primary);
|
|
78
|
+
if (primaryEmail) {
|
|
79
|
+
user.email = primaryEmail.email;
|
|
80
|
+
user.email_verified = primaryEmail.verified;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return onSuccess({
|
|
85
|
+
user,
|
|
86
|
+
tokens,
|
|
87
|
+
request
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
export { defineOAuthGitHubEventHandler };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
//#region src/oauth/google.d.ts
|
|
2
|
+
interface OAuthGoogleConfig {
|
|
3
|
+
clientId?: string;
|
|
4
|
+
clientSecret?: string;
|
|
5
|
+
scope?: string[];
|
|
6
|
+
authorizationURL?: string;
|
|
7
|
+
tokenURL?: string;
|
|
8
|
+
userInfoURL?: string;
|
|
9
|
+
authorizationParams?: Record<string, string>;
|
|
10
|
+
redirectURL?: string;
|
|
11
|
+
}
|
|
12
|
+
interface GoogleUser {
|
|
13
|
+
sub: string;
|
|
14
|
+
name: string;
|
|
15
|
+
given_name: string;
|
|
16
|
+
family_name: string;
|
|
17
|
+
picture: string;
|
|
18
|
+
email: string;
|
|
19
|
+
email_verified: boolean;
|
|
20
|
+
locale: string;
|
|
21
|
+
}
|
|
22
|
+
interface GoogleTokens {
|
|
23
|
+
access_token: string;
|
|
24
|
+
id_token: string;
|
|
25
|
+
scope: string;
|
|
26
|
+
token_type: string;
|
|
27
|
+
expires_in: number;
|
|
28
|
+
}
|
|
29
|
+
declare function defineOAuthGoogleEventHandler(options: {
|
|
30
|
+
config?: OAuthGoogleConfig;
|
|
31
|
+
onSuccess: (event: {
|
|
32
|
+
user: GoogleUser;
|
|
33
|
+
tokens: GoogleTokens;
|
|
34
|
+
request: Request;
|
|
35
|
+
}) => Response | Promise<Response>;
|
|
36
|
+
onError?: (error: Error) => Response | Promise<Response>;
|
|
37
|
+
}): (request: Request) => Promise<Response>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { OAuthGoogleConfig, defineOAuthGoogleEventHandler };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { getOAuthRedirectURL, handleAccessTokenError, handleInvalidState, handleMissingConfiguration, handlePKCE, handleState, redirect, requestAccessToken } from "./index.mjs";
|
|
2
|
+
//#region src/oauth/google.ts
|
|
3
|
+
function resolveGoogleConfig(config) {
|
|
4
|
+
return {
|
|
5
|
+
authorizationURL: config.authorizationURL ?? "https://accounts.google.com/o/oauth2/v2/auth",
|
|
6
|
+
tokenURL: config.tokenURL ?? "https://oauth2.googleapis.com/token",
|
|
7
|
+
userInfoURL: config.userInfoURL ?? "https://www.googleapis.com/oauth2/v3/userinfo",
|
|
8
|
+
clientId: config.clientId ?? process.env.PETA_OAUTH_GOOGLE_CLIENT_ID ?? "",
|
|
9
|
+
clientSecret: config.clientSecret ?? process.env.PETA_OAUTH_GOOGLE_CLIENT_SECRET ?? "",
|
|
10
|
+
scope: config.scope ?? [
|
|
11
|
+
"openid",
|
|
12
|
+
"email",
|
|
13
|
+
"profile"
|
|
14
|
+
],
|
|
15
|
+
authorizationParams: config.authorizationParams ?? {},
|
|
16
|
+
redirectURL: config.redirectURL
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function defineOAuthGoogleEventHandler(options) {
|
|
20
|
+
const { config: userConfig = {}, onSuccess, onError } = options;
|
|
21
|
+
return async (request) => {
|
|
22
|
+
const config = resolveGoogleConfig(userConfig);
|
|
23
|
+
const url = new URL(request.url);
|
|
24
|
+
const queryCode = url.searchParams.get("code");
|
|
25
|
+
const queryError = url.searchParams.get("error");
|
|
26
|
+
const queryState = url.searchParams.get("state");
|
|
27
|
+
if (queryError) {
|
|
28
|
+
const err = /* @__PURE__ */ new Error(`Google login failed: ${queryError}`);
|
|
29
|
+
if (onError) return onError(err);
|
|
30
|
+
return new Response(JSON.stringify({ error: err.message }), {
|
|
31
|
+
status: 401,
|
|
32
|
+
headers: { "Content-Type": "application/json" }
|
|
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);
|
|
40
|
+
}
|
|
41
|
+
const redirectURL = config.redirectURL || getOAuthRedirectURL(request);
|
|
42
|
+
const state = handleState(request);
|
|
43
|
+
const pkce = await handlePKCE(request);
|
|
44
|
+
if (!queryCode) {
|
|
45
|
+
const authUrl = new URL(config.authorizationURL);
|
|
46
|
+
authUrl.searchParams.set("client_id", config.clientId);
|
|
47
|
+
authUrl.searchParams.set("redirect_uri", redirectURL);
|
|
48
|
+
authUrl.searchParams.set("scope", config.scope.join(" "));
|
|
49
|
+
authUrl.searchParams.set("response_type", "code");
|
|
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: {
|
|
61
|
+
grant_type: "authorization_code",
|
|
62
|
+
client_id: config.clientId,
|
|
63
|
+
client_secret: config.clientSecret,
|
|
64
|
+
redirect_uri: redirectURL,
|
|
65
|
+
code: queryCode,
|
|
66
|
+
code_verifier: pkce.codeVerifier
|
|
67
|
+
} });
|
|
68
|
+
const tokensRecord = tokens;
|
|
69
|
+
if (tokensRecord.error) return handleAccessTokenError("google", tokensRecord, onError);
|
|
70
|
+
const userResponse = await fetch(config.userInfoURL, { headers: { Authorization: `Bearer ${tokens.access_token}` } });
|
|
71
|
+
if (!userResponse.ok) {
|
|
72
|
+
const err = /* @__PURE__ */ new Error(`Google user fetch failed: ${userResponse.status}`);
|
|
73
|
+
if (onError) return onError(err);
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
return onSuccess({
|
|
77
|
+
user: await userResponse.json(),
|
|
78
|
+
tokens,
|
|
79
|
+
request
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { defineOAuthGoogleEventHandler };
|
|
@@ -0,0 +1,25 @@
|
|
|
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 };
|
|
@@ -0,0 +1,103 @@
|
|
|
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 };
|
|
@@ -0,0 +1,119 @@
|
|
|
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 };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { SerializeOptions } from "cookie";
|
|
2
|
+
|
|
3
|
+
//#region src/crypto.d.ts
|
|
4
|
+
type PasswordsMap = Record<string, string>;
|
|
5
|
+
type Password = PasswordsMap | string;
|
|
6
|
+
declare const sealData: (data: unknown, {
|
|
7
|
+
password,
|
|
8
|
+
ttl
|
|
9
|
+
}: {
|
|
10
|
+
password: Password;
|
|
11
|
+
ttl?: number;
|
|
12
|
+
}) => Promise<string>;
|
|
13
|
+
declare const unsealData: <T>(seal: string, {
|
|
14
|
+
password,
|
|
15
|
+
ttl
|
|
16
|
+
}: {
|
|
17
|
+
password: Password;
|
|
18
|
+
ttl?: number;
|
|
19
|
+
}) => Promise<T>;
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/session.d.ts
|
|
22
|
+
interface SessionOptions {
|
|
23
|
+
password: Password;
|
|
24
|
+
cookieName: string;
|
|
25
|
+
ttl?: number;
|
|
26
|
+
cookieOptions?: Omit<SerializeOptions, 'encode'>;
|
|
27
|
+
}
|
|
28
|
+
interface IronSession {
|
|
29
|
+
save(): Promise<void>;
|
|
30
|
+
destroy(): void;
|
|
31
|
+
updateConfig(options: SessionOptions): void;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
interface SessionAdapter {
|
|
35
|
+
getCookie(name: string): string | undefined;
|
|
36
|
+
setCookie(cookie: string): void;
|
|
37
|
+
}
|
|
38
|
+
declare function createSessionFromAdapter<T extends Record<string, unknown> = Record<string, unknown>>(adapter: SessionAdapter, options: SessionOptions): Promise<T & IronSession>;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { Password as a, createSessionFromAdapter as i, SessionAdapter as n, sealData as o, SessionOptions as r, unsealData as s, IronSession as t };
|
package/package.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "peta-auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Encrypted cookie sessions for Bun — Hono, ElysiaJS & Nuxt adapters",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.mts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.mts",
|
|
11
|
+
"import": "./dist/index.mjs"
|
|
12
|
+
},
|
|
13
|
+
"./hono": {
|
|
14
|
+
"types": "./dist/hono.d.mts",
|
|
15
|
+
"import": "./dist/hono.mjs"
|
|
16
|
+
},
|
|
17
|
+
"./elysia": {
|
|
18
|
+
"types": "./dist/elysia.d.mts",
|
|
19
|
+
"import": "./dist/elysia.mjs"
|
|
20
|
+
},
|
|
21
|
+
"./nuxt": {
|
|
22
|
+
"types": "./dist/nuxt.d.mts",
|
|
23
|
+
"import": "./dist/nuxt.mjs"
|
|
24
|
+
},
|
|
25
|
+
"./oauth/github": {
|
|
26
|
+
"types": "./dist/oauth/github.d.mts",
|
|
27
|
+
"import": "./dist/oauth/github.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./oauth/google": {
|
|
30
|
+
"types": "./dist/oauth/google.d.mts",
|
|
31
|
+
"import": "./dist/oauth/google.mjs"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist"
|
|
36
|
+
],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsdown",
|
|
39
|
+
"lint": "biome check --write .",
|
|
40
|
+
"lint:ci": "biome ci .",
|
|
41
|
+
"prepublish": "bun run build",
|
|
42
|
+
"test": "bun test"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"bcryptjs": "^3.0.3",
|
|
46
|
+
"cookie": "^1.0.2",
|
|
47
|
+
"iron-webcrypto": "^1.2.1"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"elysia": ">=1.0.0",
|
|
51
|
+
"h3": ">=1.15.0",
|
|
52
|
+
"hono": ">=4.0.0",
|
|
53
|
+
"typescript": "^5.0.0"
|
|
54
|
+
},
|
|
55
|
+
"peerDependenciesMeta": {
|
|
56
|
+
"elysia": {
|
|
57
|
+
"optional": true
|
|
58
|
+
},
|
|
59
|
+
"h3": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"hono": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@biomejs/biome": "^2.4.16",
|
|
68
|
+
"@types/bcryptjs": "^3.0.0",
|
|
69
|
+
"@types/bun": "latest",
|
|
70
|
+
"elysia": "latest",
|
|
71
|
+
"h3": "latest",
|
|
72
|
+
"hono": "latest",
|
|
73
|
+
"tsdown": "latest",
|
|
74
|
+
"typescript": "^5.0.0"
|
|
75
|
+
}
|
|
76
|
+
}
|