@ropean/sso-client 0.0.2 → 0.0.4
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/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +19 -3
- package/dist/config.js.map +1 -1
- package/dist/idp.d.ts +8 -1
- package/dist/idp.d.ts.map +1 -1
- package/dist/idp.js +10 -0
- package/dist/idp.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/jwks/verifier.d.ts +6 -2
- package/dist/jwks/verifier.d.ts.map +1 -1
- package/dist/jwks/verifier.js.map +1 -1
- package/dist/middleware/authenticate.d.ts +1 -0
- package/dist/middleware/authenticate.d.ts.map +1 -1
- package/dist/middleware/authenticate.js +8 -3
- package/dist/middleware/authenticate.js.map +1 -1
- package/dist/middleware/cookie.js.map +1 -1
- package/dist/routes/backchannel.js.map +1 -1
- package/dist/routes/callback.js.map +1 -1
- package/dist/routes/login.js.map +1 -1
- package/dist/routes/logout.js.map +1 -1
- package/dist/routes/me.js.map +1 -1
- package/dist/routes/refresh.js.map +1 -1
- package/dist/store/crypto.js.map +1 -1
- package/dist/store/interface.js.map +1 -1
- package/dist/store/kv.js.map +1 -1
- package/dist/store/memory.js.map +1 -1
- package/dist/store/sqlite.js.map +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils.js.map +1 -1
- package/package.json +1 -2
- package/src/config.ts +0 -93
- package/src/idp.ts +0 -83
- package/src/index.ts +0 -120
- package/src/jwks/verifier.ts +0 -69
- package/src/middleware/authenticate.ts +0 -197
- package/src/middleware/cookie.test.ts +0 -29
- package/src/middleware/cookie.ts +0 -87
- package/src/routes/backchannel.ts +0 -67
- package/src/routes/callback.ts +0 -99
- package/src/routes/login.ts +0 -72
- package/src/routes/logout.ts +0 -50
- package/src/routes/me.ts +0 -26
- package/src/routes/refresh.ts +0 -35
- package/src/store/crypto.test.ts +0 -23
- package/src/store/crypto.ts +0 -51
- package/src/store/interface.ts +0 -28
- package/src/store/kv.ts +0 -137
- package/src/store/memory.ts +0 -110
- package/src/store/sqlite.test.ts +0 -111
- package/src/store/sqlite.ts +0 -201
- package/src/types.ts +0 -80
- package/src/utils.ts +0 -30
|
@@ -1,197 +0,0 @@
|
|
|
1
|
-
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
-
import { decodeJwt } from 'jose';
|
|
3
|
-
import type { SessionStore } from '../store/interface.js';
|
|
4
|
-
import type { JwtVerifier } from '../jwks/verifier.js';
|
|
5
|
-
import type { AuthContext, SessionRecord, SsoConfig, UserClaims } from '../types.js';
|
|
6
|
-
import { IdpError, refreshAccessToken } from '../idp.js';
|
|
7
|
-
import { decryptSecret, encryptSecret } from '../store/crypto.js';
|
|
8
|
-
import { readSessionSidFromCookie, setSessionCookie, parseSidFromCookieHeader } from './cookie.js';
|
|
9
|
-
|
|
10
|
-
export interface AuthDeps {
|
|
11
|
-
config: SsoConfig;
|
|
12
|
-
store: SessionStore;
|
|
13
|
-
verifier: JwtVerifier;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export interface AuthOptions {
|
|
17
|
-
admin?: boolean;
|
|
18
|
-
optional?: boolean;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
declare module 'hono' {
|
|
22
|
-
interface ContextVariableMap {
|
|
23
|
-
user: UserClaims;
|
|
24
|
-
auth: AuthContext;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function isAdmin(user: UserClaims): boolean {
|
|
29
|
-
const role = typeof user.role === 'string' ? user.role.toLowerCase() : '';
|
|
30
|
-
return role.includes('admin');
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function tryCookieAuth(c: Context, deps: AuthDeps): Promise<AuthContext | null> {
|
|
34
|
-
const { config, store } = deps;
|
|
35
|
-
const sid = await readSessionSidFromCookie(c, config);
|
|
36
|
-
if (!sid) return null;
|
|
37
|
-
|
|
38
|
-
let session = await store.getSession(sid);
|
|
39
|
-
if (!session) return null;
|
|
40
|
-
|
|
41
|
-
const now = Date.now();
|
|
42
|
-
if (session.refreshExpiresAt < now) {
|
|
43
|
-
await store.deleteSession(sid);
|
|
44
|
-
await setSessionCookie(c, config, null, { clear: true });
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
if (session.accessExpiresAt - now < config.refreshSkewMs) {
|
|
49
|
-
const renewed = await renewSession(deps, session);
|
|
50
|
-
if (!renewed) {
|
|
51
|
-
await setSessionCookie(c, config, null, { clear: true });
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
session = renewed;
|
|
55
|
-
await setSessionCookie(c, config, sid);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (!session.idToken) return null;
|
|
59
|
-
try {
|
|
60
|
-
const user = decodeJwt(session.idToken) as UserClaims;
|
|
61
|
-
return { user, source: 'cookie', session: { sid: session.sid, sub: session.sub } };
|
|
62
|
-
} catch {
|
|
63
|
-
return null;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function renewSession(deps: AuthDeps, session: SessionRecord): Promise<SessionRecord | null> {
|
|
68
|
-
const { config, store } = deps;
|
|
69
|
-
|
|
70
|
-
let lockToken: string | null = null;
|
|
71
|
-
if (store.tryLockSession) {
|
|
72
|
-
const { acquired, token } = await store.tryLockSession(session.sid);
|
|
73
|
-
if (!acquired) {
|
|
74
|
-
const waited = await store.waitForSession?.(session.sid, 3000);
|
|
75
|
-
return waited ?? null;
|
|
76
|
-
}
|
|
77
|
-
lockToken = token;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
try {
|
|
81
|
-
let refreshToken: string;
|
|
82
|
-
try {
|
|
83
|
-
refreshToken = await decryptSecret(session.refreshTokenEnc, config.sessionSecret);
|
|
84
|
-
} catch {
|
|
85
|
-
await store.deleteSession(session.sid);
|
|
86
|
-
return null;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
try {
|
|
90
|
-
const tokens = await refreshAccessToken(config, refreshToken);
|
|
91
|
-
const now = Date.now();
|
|
92
|
-
const newRefresh = tokens.refresh_token ?? refreshToken;
|
|
93
|
-
return await store.rotateSession(session.sid, {
|
|
94
|
-
accessToken: tokens.access_token,
|
|
95
|
-
refreshTokenEnc: await encryptSecret(newRefresh, config.sessionSecret),
|
|
96
|
-
idToken: tokens.id_token ?? session.idToken,
|
|
97
|
-
accessExpiresAt: now + (tokens.expires_in ?? 900) * 1000,
|
|
98
|
-
refreshExpiresAt: now + config.cookieMaxAgeSec * 1000,
|
|
99
|
-
rotatedAt: now,
|
|
100
|
-
});
|
|
101
|
-
} catch (err) {
|
|
102
|
-
if (err instanceof IdpError && err.body.error === 'invalid_grant') {
|
|
103
|
-
for (let i = 1; i <= 3; i++) {
|
|
104
|
-
await new Promise((r) => setTimeout(r, 200 * i));
|
|
105
|
-
const s = await store.getSession(session.sid);
|
|
106
|
-
if (s && s.rotatedAt > session.rotatedAt) return s;
|
|
107
|
-
}
|
|
108
|
-
await store.deleteSession(session.sid);
|
|
109
|
-
}
|
|
110
|
-
return null;
|
|
111
|
-
}
|
|
112
|
-
} finally {
|
|
113
|
-
if (store.unlockSession) {
|
|
114
|
-
await store.unlockSession(session.sid, lockToken);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async function tryBearerAuth(c: Context, deps: AuthDeps): Promise<AuthContext | null> {
|
|
120
|
-
const { verifier, store } = deps;
|
|
121
|
-
const header = c.req.header('authorization');
|
|
122
|
-
if (!header || !header.startsWith('Bearer ')) return null;
|
|
123
|
-
const token = header.slice(7);
|
|
124
|
-
try {
|
|
125
|
-
const payload = await verifier.verifyAccessToken(token);
|
|
126
|
-
const user = payload as UserClaims;
|
|
127
|
-
if (typeof user.sid === 'string' && (await store.isSidRevoked(user.sid))) return null;
|
|
128
|
-
return { user, source: 'bearer' };
|
|
129
|
-
} catch {
|
|
130
|
-
return null;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
export function createAuthMiddleware(deps: AuthDeps) {
|
|
135
|
-
return (opts: AuthOptions = {}): MiddlewareHandler =>
|
|
136
|
-
async (c, next) => {
|
|
137
|
-
const auth = (await tryCookieAuth(c, deps)) ?? (await tryBearerAuth(c, deps));
|
|
138
|
-
if (!auth) {
|
|
139
|
-
if (opts.optional) {
|
|
140
|
-
await next();
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
return c.json({ message: 'Access Denied' }, 401);
|
|
144
|
-
}
|
|
145
|
-
if (opts.admin && !isAdmin(auth.user)) return c.json({ message: 'Admin access required' }, 403);
|
|
146
|
-
c.set('auth', auth);
|
|
147
|
-
c.set('user', auth.user);
|
|
148
|
-
await next();
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export async function resolveAuthFromRequest(
|
|
153
|
-
request: Request,
|
|
154
|
-
deps: AuthDeps,
|
|
155
|
-
): Promise<{ user: UserClaims; cookies: string[] } | null> {
|
|
156
|
-
const { config, store } = deps;
|
|
157
|
-
const cookieHeader = request.headers.get('cookie') ?? '';
|
|
158
|
-
const sid = await parseSidFromCookieHeader(cookieHeader, config);
|
|
159
|
-
if (!sid) return null;
|
|
160
|
-
|
|
161
|
-
let session = await store.getSession(sid);
|
|
162
|
-
if (!session) return null;
|
|
163
|
-
|
|
164
|
-
const now = Date.now();
|
|
165
|
-
if (session.refreshExpiresAt < now) {
|
|
166
|
-
await store.deleteSession(sid);
|
|
167
|
-
return null;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const cookies: string[] = [];
|
|
171
|
-
|
|
172
|
-
if (session.accessExpiresAt - now < config.refreshSkewMs) {
|
|
173
|
-
const renewed = await renewSession(deps, session);
|
|
174
|
-
if (!renewed) return null;
|
|
175
|
-
session = renewed;
|
|
176
|
-
const { encodeCookieValue } = await import('./cookie.js');
|
|
177
|
-
const cookieVal = await encodeCookieValue(sid, config.sessionSecret);
|
|
178
|
-
const parts = [
|
|
179
|
-
`${config.cookieName}=${cookieVal}`,
|
|
180
|
-
'Path=/',
|
|
181
|
-
'HttpOnly',
|
|
182
|
-
`SameSite=${config.cookieSameSite}`,
|
|
183
|
-
`Max-Age=${config.cookieMaxAgeSec}`,
|
|
184
|
-
];
|
|
185
|
-
if (config.cookieSecure) parts.push('Secure');
|
|
186
|
-
if (config.cookieDomain) parts.push(`Domain=${config.cookieDomain}`);
|
|
187
|
-
cookies.push(parts.join('; '));
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
if (!session.idToken) return null;
|
|
191
|
-
try {
|
|
192
|
-
const user = decodeJwt(session.idToken) as UserClaims;
|
|
193
|
-
return { user, cookies };
|
|
194
|
-
} catch {
|
|
195
|
-
return null;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { decodeCookieValue, encodeCookieValue, generateSid } from './cookie.js';
|
|
3
|
-
|
|
4
|
-
describe('cookie HMAC', () => {
|
|
5
|
-
const secret = 'x'.repeat(48);
|
|
6
|
-
|
|
7
|
-
it('round-trips a sid', async () => {
|
|
8
|
-
const sid = await generateSid();
|
|
9
|
-
const cookie = await encodeCookieValue(sid, secret);
|
|
10
|
-
expect(await decodeCookieValue(cookie, secret)).toBe(sid);
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it('rejects tampered sid', async () => {
|
|
14
|
-
const sid = await generateSid();
|
|
15
|
-
const cookie = await encodeCookieValue(sid, secret);
|
|
16
|
-
const broken = `${sid.slice(0, -1)}A.${cookie.split('.').pop()}`;
|
|
17
|
-
expect(await decodeCookieValue(broken, secret)).toBeNull();
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
it('rejects wrong secret', async () => {
|
|
21
|
-
const cookie = await encodeCookieValue(await generateSid(), secret);
|
|
22
|
-
expect(await decodeCookieValue(cookie, 'y'.repeat(48))).toBeNull();
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
it('rejects missing signature', async () => {
|
|
26
|
-
expect(await decodeCookieValue('abc', secret)).toBeNull();
|
|
27
|
-
expect(await decodeCookieValue('abc.', secret)).toBeNull();
|
|
28
|
-
});
|
|
29
|
-
});
|
package/src/middleware/cookie.ts
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
// Cookie signing with Web Crypto HMAC-SHA256.
|
|
2
|
-
// Compatible with CF Workers, Vercel Edge, Node 18+.
|
|
3
|
-
// Wire format: "<sid>.<base64url(hmac-sha256(sid, secret))>"
|
|
4
|
-
|
|
5
|
-
import type { Context } from 'hono';
|
|
6
|
-
import type { SsoConfig } from '../types.js';
|
|
7
|
-
import { bufToBase64url, base64urlToBuf } from '../utils.js';
|
|
8
|
-
|
|
9
|
-
export async function generateSid(): Promise<string> {
|
|
10
|
-
return bufToBase64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
async function importHmacKey(secret: string): Promise<CryptoKey> {
|
|
14
|
-
return crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
|
|
15
|
-
'sign',
|
|
16
|
-
'verify',
|
|
17
|
-
]);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export async function encodeCookieValue(sid: string, secret: string): Promise<string> {
|
|
21
|
-
const key = await importHmacKey(secret);
|
|
22
|
-
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(sid)));
|
|
23
|
-
return `${sid}.${bufToBase64url(sig)}`;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export async function decodeCookieValue(value: string, secret: string): Promise<string | null> {
|
|
27
|
-
const idx = value.lastIndexOf('.');
|
|
28
|
-
if (idx <= 0 || idx === value.length - 1) return null;
|
|
29
|
-
const sid = value.slice(0, idx);
|
|
30
|
-
const mac = value.slice(idx + 1);
|
|
31
|
-
const key = await importHmacKey(secret);
|
|
32
|
-
let sigBytes: Uint8Array;
|
|
33
|
-
try {
|
|
34
|
-
sigBytes = base64urlToBuf(mac);
|
|
35
|
-
} catch {
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
const valid = await crypto.subtle.verify(
|
|
39
|
-
'HMAC',
|
|
40
|
-
key,
|
|
41
|
-
sigBytes as unknown as BufferSource,
|
|
42
|
-
new TextEncoder().encode(sid),
|
|
43
|
-
);
|
|
44
|
-
return valid ? sid : null;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export async function parseSidFromCookieHeader(header: string, config: SsoConfig): Promise<string | null> {
|
|
48
|
-
for (const part of header.split(';')) {
|
|
49
|
-
const eq = part.indexOf('=');
|
|
50
|
-
if (eq < 0) continue;
|
|
51
|
-
const name = part.slice(0, eq).trim();
|
|
52
|
-
if (name !== config.cookieName) continue;
|
|
53
|
-
const value = part.slice(eq + 1).trim();
|
|
54
|
-
if (!value) return null;
|
|
55
|
-
return decodeCookieValue(value, config.sessionSecret);
|
|
56
|
-
}
|
|
57
|
-
return null;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface SetCookieOpts {
|
|
61
|
-
maxAgeSec?: number;
|
|
62
|
-
clear?: boolean;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export async function setSessionCookie(
|
|
66
|
-
c: Context,
|
|
67
|
-
config: SsoConfig,
|
|
68
|
-
sid: string | null,
|
|
69
|
-
opts: SetCookieOpts = {},
|
|
70
|
-
): Promise<void> {
|
|
71
|
-
const parts: string[] = [];
|
|
72
|
-
const value = sid && !opts.clear ? await encodeCookieValue(sid, config.sessionSecret) : '';
|
|
73
|
-
parts.push(`${config.cookieName}=${value}`);
|
|
74
|
-
parts.push('Path=/');
|
|
75
|
-
parts.push('HttpOnly');
|
|
76
|
-
parts.push(`SameSite=${config.cookieSameSite}`);
|
|
77
|
-
if (config.cookieSecure) parts.push('Secure');
|
|
78
|
-
if (config.cookieDomain) parts.push(`Domain=${config.cookieDomain}`);
|
|
79
|
-
parts.push(opts.clear ? 'Max-Age=0' : `Max-Age=${opts.maxAgeSec ?? config.cookieMaxAgeSec}`);
|
|
80
|
-
c.header('Set-Cookie', parts.join('; '), { append: true });
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export async function readSessionSidFromCookie(c: Context, config: SsoConfig): Promise<string | null> {
|
|
84
|
-
const header = c.req.header('cookie');
|
|
85
|
-
if (!header) return null;
|
|
86
|
-
return parseSidFromCookieHeader(header, config);
|
|
87
|
-
}
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import type { JwtVerifier } from '../jwks/verifier.js';
|
|
3
|
-
import type { SessionStore } from '../store/interface.js';
|
|
4
|
-
import type { SsoConfig } from '../types.js';
|
|
5
|
-
|
|
6
|
-
interface Deps {
|
|
7
|
-
config: SsoConfig;
|
|
8
|
-
store: SessionStore;
|
|
9
|
-
verifier: JwtVerifier;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function createBackchannelRoute(deps: Deps): Hono {
|
|
13
|
-
const { config, store, verifier } = deps;
|
|
14
|
-
const app = new Hono();
|
|
15
|
-
|
|
16
|
-
app.post('/backchannel-logout', async (c) => {
|
|
17
|
-
const ct = c.req.header('content-type') ?? '';
|
|
18
|
-
let logoutToken: string | undefined;
|
|
19
|
-
if (ct.includes('application/x-www-form-urlencoded')) {
|
|
20
|
-
const text = await c.req.text();
|
|
21
|
-
logoutToken = new URLSearchParams(text).get('logout_token') ?? undefined;
|
|
22
|
-
} else {
|
|
23
|
-
try {
|
|
24
|
-
const body = (await c.req.json()) as { logout_token?: string };
|
|
25
|
-
logoutToken = body.logout_token;
|
|
26
|
-
} catch {
|
|
27
|
-
// ignore
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
if (!logoutToken) {
|
|
32
|
-
if (config.isDebug) console.warn('[backchannel-logout] rejected: missing logout_token');
|
|
33
|
-
return c.body(null, 400);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
let payload;
|
|
37
|
-
try {
|
|
38
|
-
payload = await verifier.verifyBackchannelLogoutToken(logoutToken, { audience: config.clientId });
|
|
39
|
-
} catch (err) {
|
|
40
|
-
if (config.isDebug) console.warn('[backchannel-logout] rejected:', (err as Error).message);
|
|
41
|
-
return c.body(null, 400);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const sub = typeof payload.sub === 'string' ? payload.sub : null;
|
|
45
|
-
if (!sub) return c.body(null, 400);
|
|
46
|
-
const sid = typeof payload.sid === 'string' ? payload.sid : null;
|
|
47
|
-
|
|
48
|
-
const denylistTtl = 24 * 60 * 60 * 1000;
|
|
49
|
-
const expiresAt = Date.now() + denylistTtl;
|
|
50
|
-
|
|
51
|
-
if (sid) {
|
|
52
|
-
const session = await store.getSession(sid);
|
|
53
|
-
await store.revokeBySid(sid);
|
|
54
|
-
await store.markSidRevoked(sid, expiresAt);
|
|
55
|
-
if (config.isDebug) {
|
|
56
|
-
console.log(`[backchannel-logout] revoked sid=${sid} sub=${sub} hadSession=${!!session}`);
|
|
57
|
-
}
|
|
58
|
-
} else {
|
|
59
|
-
const deleted = await store.revokeBySub(sub);
|
|
60
|
-
if (config.isDebug) console.log(`[backchannel-logout] revoked all sessions for sub=${sub} (${deleted} rows)`);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return c.body(null, 204);
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
return app;
|
|
67
|
-
}
|
package/src/routes/callback.ts
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { exchangeAuthorizationCode } from '../idp.js';
|
|
3
|
-
import { encryptSecret } from '../store/crypto.js';
|
|
4
|
-
import { generateSid, setSessionCookie } from '../middleware/cookie.js';
|
|
5
|
-
import type { JwtVerifier } from '../jwks/verifier.js';
|
|
6
|
-
import type { SessionStore } from '../store/interface.js';
|
|
7
|
-
import type { SsoConfig } from '../types.js';
|
|
8
|
-
|
|
9
|
-
interface Deps {
|
|
10
|
-
config: SsoConfig;
|
|
11
|
-
store: SessionStore;
|
|
12
|
-
verifier: JwtVerifier;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function createCallbackRoute(deps: Deps): Hono {
|
|
16
|
-
const { config, store, verifier } = deps;
|
|
17
|
-
const app = new Hono();
|
|
18
|
-
|
|
19
|
-
app.get('/callback', async (c) => {
|
|
20
|
-
const code = c.req.query('code');
|
|
21
|
-
const state = c.req.query('state');
|
|
22
|
-
const error = c.req.query('error');
|
|
23
|
-
const errorDescription = c.req.query('error_description');
|
|
24
|
-
|
|
25
|
-
if (error) {
|
|
26
|
-
return c.json({ message: errorDescription || error }, 400);
|
|
27
|
-
}
|
|
28
|
-
if (!code || !state) {
|
|
29
|
-
return c.json({ message: 'Missing code or state' }, 400);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const pkce = await store.consumePkce(state);
|
|
33
|
-
if (!pkce) {
|
|
34
|
-
return c.json({ message: 'Invalid or expired state' }, 400);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
let tokens;
|
|
38
|
-
try {
|
|
39
|
-
tokens = await exchangeAuthorizationCode(config, { code, codeVerifier: pkce.codeVerifier });
|
|
40
|
-
} catch (err) {
|
|
41
|
-
const msg = err instanceof Error ? err.message : 'Token exchange failed';
|
|
42
|
-
return c.json({ message: 'Login failed', error: msg }, 400);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
let sub: string | null = null;
|
|
46
|
-
if (tokens.id_token) {
|
|
47
|
-
try {
|
|
48
|
-
const payload = await verifier.verifyIdToken(tokens.id_token, {
|
|
49
|
-
audience: config.clientId,
|
|
50
|
-
nonce: pkce.nonce,
|
|
51
|
-
});
|
|
52
|
-
sub = typeof payload.sub === 'string' ? payload.sub : null;
|
|
53
|
-
} catch (err) {
|
|
54
|
-
const msg = err instanceof Error ? err.message : 'id_token validation failed';
|
|
55
|
-
return c.json({ message: 'Login failed', error: msg }, 400);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (!sub) {
|
|
60
|
-
try {
|
|
61
|
-
const payload = await verifier.verifyAccessToken(tokens.access_token);
|
|
62
|
-
sub = typeof payload.sub === 'string' ? payload.sub : null;
|
|
63
|
-
} catch {
|
|
64
|
-
return c.json({ message: 'Login failed', error: 'access_token validation failed' }, 400);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
if (!sub) {
|
|
68
|
-
return c.json({ message: 'Login failed', error: 'missing sub claim' }, 400);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
if (!tokens.refresh_token) {
|
|
72
|
-
return c.json(
|
|
73
|
-
{ message: 'Login failed', error: 'no refresh_token returned — add offline_access to scopes' },
|
|
74
|
-
400,
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const sid = await generateSid();
|
|
79
|
-
const now = Date.now();
|
|
80
|
-
await store.createSession({
|
|
81
|
-
sid,
|
|
82
|
-
sub,
|
|
83
|
-
accessToken: tokens.access_token,
|
|
84
|
-
refreshTokenEnc: await encryptSecret(tokens.refresh_token, config.sessionSecret),
|
|
85
|
-
idToken: tokens.id_token ?? null,
|
|
86
|
-
accessExpiresAt: now + (tokens.expires_in ?? 900) * 1000,
|
|
87
|
-
refreshExpiresAt: now + config.cookieMaxAgeSec * 1000,
|
|
88
|
-
createdAt: now,
|
|
89
|
-
rotatedAt: now,
|
|
90
|
-
userAgent: c.req.header('user-agent') ?? null,
|
|
91
|
-
ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim() ?? null,
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
await setSessionCookie(c, config, sid);
|
|
95
|
-
return c.redirect(pkce.returnTo || '/');
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
return app;
|
|
99
|
-
}
|
package/src/routes/login.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { deriveEndpoints } from '../config.js';
|
|
3
|
-
import { bufToBase64url, randomHex } from '../utils.js';
|
|
4
|
-
import type { SessionStore } from '../store/interface.js';
|
|
5
|
-
import type { SsoConfig } from '../types.js';
|
|
6
|
-
|
|
7
|
-
const SAFE_RETURN_TO = /^\/[\w\-/.?=&%~+:#@!$'(),;*]*$/;
|
|
8
|
-
const PKCE_TTL_MS = 10 * 60 * 1000;
|
|
9
|
-
|
|
10
|
-
async function pkcePair(): Promise<{ verifier: string; challenge: string }> {
|
|
11
|
-
const verifier = bufToBase64url(crypto.getRandomValues(new Uint8Array(64)));
|
|
12
|
-
const hashBuf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
|
|
13
|
-
const challenge = bufToBase64url(new Uint8Array(hashBuf));
|
|
14
|
-
return { verifier, challenge };
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function safeReturnTo(input: unknown): string {
|
|
18
|
-
if (typeof input !== 'string') return '/';
|
|
19
|
-
return SAFE_RETURN_TO.test(input) ? input : '/';
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
interface Deps {
|
|
23
|
-
config: SsoConfig;
|
|
24
|
-
store: SessionStore;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function createLoginRoute(deps: Deps): Hono {
|
|
28
|
-
const { config, store } = deps;
|
|
29
|
-
const endpoints = deriveEndpoints(config.issuer);
|
|
30
|
-
const app = new Hono();
|
|
31
|
-
|
|
32
|
-
const start = async (returnTo: string, loginHint?: string | undefined) => {
|
|
33
|
-
const state = randomHex(16);
|
|
34
|
-
const nonce = randomHex(16);
|
|
35
|
-
const { verifier, challenge } = await pkcePair();
|
|
36
|
-
await store.createPkce(state, {
|
|
37
|
-
codeVerifier: verifier,
|
|
38
|
-
nonce,
|
|
39
|
-
returnTo,
|
|
40
|
-
expiresAt: Date.now() + PKCE_TTL_MS,
|
|
41
|
-
});
|
|
42
|
-
const params = new URLSearchParams({
|
|
43
|
-
response_type: 'code',
|
|
44
|
-
client_id: config.clientId,
|
|
45
|
-
redirect_uri: config.redirectUri,
|
|
46
|
-
scope: config.scopes,
|
|
47
|
-
state,
|
|
48
|
-
nonce,
|
|
49
|
-
code_challenge: challenge,
|
|
50
|
-
code_challenge_method: 'S256',
|
|
51
|
-
});
|
|
52
|
-
if (loginHint) params.set('login_hint', loginHint);
|
|
53
|
-
return `${endpoints.authorizeEndpoint}?${params.toString()}`;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
app.get('/login', async (c) => {
|
|
57
|
-
const returnTo = safeReturnTo(c.req.query('return_to'));
|
|
58
|
-
return c.redirect(await start(returnTo));
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
app.get('/initiate', async (c) => {
|
|
62
|
-
const iss = c.req.query('iss');
|
|
63
|
-
if (iss !== config.issuer) {
|
|
64
|
-
return c.json({ message: 'Unknown issuer' }, 400);
|
|
65
|
-
}
|
|
66
|
-
const returnTo = safeReturnTo(c.req.query('target_link_uri'));
|
|
67
|
-
const loginHint = c.req.query('login_hint') ?? undefined;
|
|
68
|
-
return c.redirect(await start(returnTo, loginHint));
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
return app;
|
|
72
|
-
}
|
package/src/routes/logout.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { deriveEndpoints } from '../config.js';
|
|
3
|
-
import { revokeRefreshToken } from '../idp.js';
|
|
4
|
-
import { decryptSecret } from '../store/crypto.js';
|
|
5
|
-
import { readSessionSidFromCookie, setSessionCookie } from '../middleware/cookie.js';
|
|
6
|
-
import { randomHex } from '../utils.js';
|
|
7
|
-
import type { SessionStore } from '../store/interface.js';
|
|
8
|
-
import type { SsoConfig } from '../types.js';
|
|
9
|
-
|
|
10
|
-
interface Deps {
|
|
11
|
-
config: SsoConfig;
|
|
12
|
-
store: SessionStore;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function createLogoutRoute(deps: Deps): Hono {
|
|
16
|
-
const { config, store } = deps;
|
|
17
|
-
const endpoints = deriveEndpoints(config.issuer);
|
|
18
|
-
const app = new Hono();
|
|
19
|
-
|
|
20
|
-
app.get('/logout', async (c) => {
|
|
21
|
-
const sid = await readSessionSidFromCookie(c, config);
|
|
22
|
-
let idTokenHint: string | null = null;
|
|
23
|
-
if (sid) {
|
|
24
|
-
const session = await store.getSession(sid);
|
|
25
|
-
if (session) {
|
|
26
|
-
idTokenHint = session.idToken;
|
|
27
|
-
try {
|
|
28
|
-
const refresh = await decryptSecret(session.refreshTokenEnc, config.sessionSecret);
|
|
29
|
-
await revokeRefreshToken(config, refresh);
|
|
30
|
-
} catch {
|
|
31
|
-
// best-effort
|
|
32
|
-
}
|
|
33
|
-
await store.deleteSession(sid);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
await setSessionCookie(c, config, null, { clear: true });
|
|
38
|
-
|
|
39
|
-
const params = new URLSearchParams({ state: randomHex(16) });
|
|
40
|
-
const postLogout = config.postLogoutRedirectUri || new URL('/', config.redirectUri).origin;
|
|
41
|
-
params.set('post_logout_redirect_uri', postLogout);
|
|
42
|
-
const hintFromQuery = c.req.query('id_token_hint');
|
|
43
|
-
if (idTokenHint || hintFromQuery) {
|
|
44
|
-
params.set('id_token_hint', idTokenHint ?? (hintFromQuery as string));
|
|
45
|
-
}
|
|
46
|
-
return c.redirect(`${endpoints.logoutEndpoint}?${params.toString()}`);
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
return app;
|
|
50
|
-
}
|
package/src/routes/me.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { createAuthMiddleware, type AuthDeps } from '../middleware/authenticate.js';
|
|
3
|
-
|
|
4
|
-
export function createMeRoute(deps: AuthDeps): Hono {
|
|
5
|
-
const auth = createAuthMiddleware(deps);
|
|
6
|
-
const app = new Hono();
|
|
7
|
-
app.get('/me', auth({ optional: true }), (c) => {
|
|
8
|
-
const ctx = c.get('auth');
|
|
9
|
-
if (!ctx) return c.json(null);
|
|
10
|
-
const claims = c.get('user');
|
|
11
|
-
const { sub, sid, username, preferred_username, name, email, email_verified, picture, role, org_id } = claims;
|
|
12
|
-
return c.json({
|
|
13
|
-
sub,
|
|
14
|
-
sid: sid ?? ctx.session?.sid,
|
|
15
|
-
username,
|
|
16
|
-
preferred_username,
|
|
17
|
-
name,
|
|
18
|
-
email,
|
|
19
|
-
email_verified,
|
|
20
|
-
picture,
|
|
21
|
-
role,
|
|
22
|
-
org_id,
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
return app;
|
|
26
|
-
}
|
package/src/routes/refresh.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { IdpError, refreshAccessToken } from '../idp.js';
|
|
3
|
-
import type { SsoConfig } from '../types.js';
|
|
4
|
-
|
|
5
|
-
interface Deps {
|
|
6
|
-
config: SsoConfig;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function createRefreshRoute(deps: Deps): Hono {
|
|
10
|
-
const { config } = deps;
|
|
11
|
-
const app = new Hono();
|
|
12
|
-
|
|
13
|
-
app.post('/refresh', async (c) => {
|
|
14
|
-
let body: { refresh_token?: string };
|
|
15
|
-
try {
|
|
16
|
-
body = await c.req.json();
|
|
17
|
-
} catch {
|
|
18
|
-
return c.json({ message: 'refresh_token required' }, 400);
|
|
19
|
-
}
|
|
20
|
-
if (!body.refresh_token) {
|
|
21
|
-
return c.json({ message: 'refresh_token required' }, 400);
|
|
22
|
-
}
|
|
23
|
-
try {
|
|
24
|
-
const tokens = await refreshAccessToken(config, body.refresh_token);
|
|
25
|
-
return c.json(tokens);
|
|
26
|
-
} catch (err) {
|
|
27
|
-
if (err instanceof IdpError) {
|
|
28
|
-
return c.json({ message: 'Token refresh failed', error: err.body.error_description ?? err.body.error }, 400);
|
|
29
|
-
}
|
|
30
|
-
return c.json({ message: 'Token refresh failed' }, 400);
|
|
31
|
-
}
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
return app;
|
|
35
|
-
}
|
package/src/store/crypto.test.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { decryptSecret, encryptSecret } from './crypto.js';
|
|
3
|
-
|
|
4
|
-
describe('crypto', () => {
|
|
5
|
-
const secret = 'a'.repeat(48);
|
|
6
|
-
|
|
7
|
-
it('round-trips a refresh token', async () => {
|
|
8
|
-
const plain = 'refresh-token-value-12345';
|
|
9
|
-
const enc = await encryptSecret(plain, secret);
|
|
10
|
-
expect(await decryptSecret(enc, secret)).toBe(plain);
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
it('rejects tampering', async () => {
|
|
14
|
-
const enc = await encryptSecret('a longer payload that gives the cipher some bytes to chew on', secret);
|
|
15
|
-
enc[enc.length - 1] = (enc[enc.length - 1] ?? 0) ^ 0x01;
|
|
16
|
-
await expect(decryptSecret(enc, secret)).rejects.toThrow();
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
it('rejects wrong key', async () => {
|
|
20
|
-
const enc = await encryptSecret('hello', secret);
|
|
21
|
-
await expect(decryptSecret(enc, 'b'.repeat(48))).rejects.toThrow();
|
|
22
|
-
});
|
|
23
|
-
});
|