@ropean/sso-client 0.0.2

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.
Files changed (99) hide show
  1. package/dist/config.d.ts +12 -0
  2. package/dist/config.d.ts.map +1 -0
  3. package/dist/config.js +75 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/idp.d.ts +25 -0
  6. package/dist/idp.d.ts.map +1 -0
  7. package/dist/idp.js +64 -0
  8. package/dist/idp.js.map +1 -0
  9. package/dist/index.d.ts +73 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +63 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/jwks/verifier.d.ts +18 -0
  14. package/dist/jwks/verifier.d.ts.map +1 -0
  15. package/dist/jwks/verifier.js +62 -0
  16. package/dist/jwks/verifier.js.map +1 -0
  17. package/dist/middleware/authenticate.d.ts +25 -0
  18. package/dist/middleware/authenticate.d.ts.map +1 -0
  19. package/dist/middleware/authenticate.js +173 -0
  20. package/dist/middleware/authenticate.js.map +1 -0
  21. package/dist/middleware/cookie.d.ts +13 -0
  22. package/dist/middleware/cookie.d.ts.map +1 -0
  23. package/dist/middleware/cookie.js +71 -0
  24. package/dist/middleware/cookie.js.map +1 -0
  25. package/dist/routes/backchannel.d.ts +12 -0
  26. package/dist/routes/backchannel.d.ts.map +1 -0
  27. package/dist/routes/backchannel.js +58 -0
  28. package/dist/routes/backchannel.js.map +1 -0
  29. package/dist/routes/callback.d.ts +12 -0
  30. package/dist/routes/callback.d.ts.map +1 -0
  31. package/dist/routes/callback.js +80 -0
  32. package/dist/routes/callback.js.map +1 -0
  33. package/dist/routes/login.d.ts +10 -0
  34. package/dist/routes/login.d.ts.map +1 -0
  35. package/dist/routes/login.js +60 -0
  36. package/dist/routes/login.js.map +1 -0
  37. package/dist/routes/logout.d.ts +10 -0
  38. package/dist/routes/logout.d.ts.map +1 -0
  39. package/dist/routes/logout.js +40 -0
  40. package/dist/routes/logout.js.map +1 -0
  41. package/dist/routes/me.d.ts +4 -0
  42. package/dist/routes/me.d.ts.map +1 -0
  43. package/dist/routes/me.js +27 -0
  44. package/dist/routes/me.js.map +1 -0
  45. package/dist/routes/refresh.d.ts +8 -0
  46. package/dist/routes/refresh.d.ts.map +1 -0
  47. package/dist/routes/refresh.js +30 -0
  48. package/dist/routes/refresh.js.map +1 -0
  49. package/dist/store/crypto.d.ts +5 -0
  50. package/dist/store/crypto.d.ts.map +1 -0
  51. package/dist/store/crypto.js +38 -0
  52. package/dist/store/crypto.js.map +1 -0
  53. package/dist/store/interface.d.ts +22 -0
  54. package/dist/store/interface.d.ts.map +1 -0
  55. package/dist/store/interface.js +2 -0
  56. package/dist/store/interface.js.map +1 -0
  57. package/dist/store/kv.d.ts +32 -0
  58. package/dist/store/kv.d.ts.map +1 -0
  59. package/dist/store/kv.js +117 -0
  60. package/dist/store/kv.js.map +1 -0
  61. package/dist/store/memory.d.ts +23 -0
  62. package/dist/store/memory.d.ts.map +1 -0
  63. package/dist/store/memory.js +102 -0
  64. package/dist/store/memory.js.map +1 -0
  65. package/dist/store/sqlite.d.ts +19 -0
  66. package/dist/store/sqlite.d.ts.map +1 -0
  67. package/dist/store/sqlite.js +144 -0
  68. package/dist/store/sqlite.js.map +1 -0
  69. package/dist/types.d.ts +66 -0
  70. package/dist/types.d.ts.map +1 -0
  71. package/dist/types.js +4 -0
  72. package/dist/types.js.map +1 -0
  73. package/dist/utils.d.ts +6 -0
  74. package/dist/utils.d.ts.map +1 -0
  75. package/dist/utils.js +28 -0
  76. package/dist/utils.js.map +1 -0
  77. package/package.json +91 -0
  78. package/src/config.ts +93 -0
  79. package/src/idp.ts +83 -0
  80. package/src/index.ts +120 -0
  81. package/src/jwks/verifier.ts +69 -0
  82. package/src/middleware/authenticate.ts +197 -0
  83. package/src/middleware/cookie.test.ts +29 -0
  84. package/src/middleware/cookie.ts +87 -0
  85. package/src/routes/backchannel.ts +67 -0
  86. package/src/routes/callback.ts +99 -0
  87. package/src/routes/login.ts +72 -0
  88. package/src/routes/logout.ts +50 -0
  89. package/src/routes/me.ts +26 -0
  90. package/src/routes/refresh.ts +35 -0
  91. package/src/store/crypto.test.ts +23 -0
  92. package/src/store/crypto.ts +51 -0
  93. package/src/store/interface.ts +28 -0
  94. package/src/store/kv.ts +137 -0
  95. package/src/store/memory.ts +110 -0
  96. package/src/store/sqlite.test.ts +111 -0
  97. package/src/store/sqlite.ts +201 -0
  98. package/src/types.ts +80 -0
  99. package/src/utils.ts +30 -0
@@ -0,0 +1,87 @@
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
+ }
@@ -0,0 +1,67 @@
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
+ }
@@ -0,0 +1,99 @@
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
+ }
@@ -0,0 +1,72 @@
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
+ }
@@ -0,0 +1,50 @@
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
+ }
@@ -0,0 +1,26 @@
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
+ }
@@ -0,0 +1,35 @@
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
+ }
@@ -0,0 +1,23 @@
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
+ });
@@ -0,0 +1,51 @@
1
+ // AES-256-GCM encrypt/decrypt using Web Crypto API.
2
+ // Compatible with CF Workers, Vercel Edge, Node 18+.
3
+ // Wire format: [IV(12 bytes)][AuthTag(16 bytes)][Ciphertext]
4
+
5
+ import { bufToBase64, base64ToBuf } from '../utils.js';
6
+
7
+ async function deriveKey(secret: string): Promise<CryptoKey> {
8
+ const raw = new TextEncoder().encode(secret);
9
+ const hkdfKey = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
10
+ return crypto.subtle.deriveKey(
11
+ { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: new TextEncoder().encode('sso-rt') },
12
+ hkdfKey,
13
+ { name: 'AES-GCM', length: 256 },
14
+ false,
15
+ ['encrypt', 'decrypt'],
16
+ );
17
+ }
18
+
19
+ export async function encryptSecret(plaintext: string, secret: string): Promise<Uint8Array> {
20
+ const key = await deriveKey(secret);
21
+ const iv = crypto.getRandomValues(new Uint8Array(12));
22
+ const data = new TextEncoder().encode(plaintext);
23
+ const encBuf = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, data));
24
+ const ciphertext = encBuf.subarray(0, encBuf.length - 16);
25
+ const authTag = encBuf.subarray(encBuf.length - 16);
26
+ const result = new Uint8Array(12 + 16 + ciphertext.length);
27
+ result.set(iv, 0);
28
+ result.set(authTag, 12);
29
+ result.set(ciphertext, 28);
30
+ return result;
31
+ }
32
+
33
+ export async function decryptSecret(blob: Uint8Array, secret: string): Promise<string> {
34
+ if (blob.length < 28) throw new Error('ciphertext too short');
35
+ const key = await deriveKey(secret);
36
+ const iv = blob.subarray(0, 12);
37
+ const authTag = blob.subarray(12, 28);
38
+ const ciphertext = blob.subarray(28);
39
+ const combined = new Uint8Array(ciphertext.length + 16);
40
+ combined.set(ciphertext, 0);
41
+ combined.set(authTag, ciphertext.length);
42
+ const decrypted = await crypto.subtle.decrypt(
43
+ { name: 'AES-GCM', iv: iv as unknown as BufferSource },
44
+ key,
45
+ combined as unknown as BufferSource,
46
+ );
47
+ return new TextDecoder().decode(decrypted);
48
+ }
49
+
50
+ export const encBufToBase64 = (buf: Uint8Array): string => bufToBase64(buf);
51
+ export const base64ToEncBuf = (str: string): Uint8Array => base64ToBuf(str);
@@ -0,0 +1,28 @@
1
+ import type { PkceRecord, SessionRecord } from '../types.js';
2
+
3
+ export interface SessionStore {
4
+ createPkce(state: string, rec: PkceRecord): Promise<void>;
5
+ consumePkce(state: string): Promise<PkceRecord | null>;
6
+
7
+ createSession(rec: SessionRecord): Promise<void>;
8
+ getSession(sid: string): Promise<SessionRecord | null>;
9
+ rotateSession(
10
+ sid: string,
11
+ patch: Partial<Omit<SessionRecord, 'sid' | 'sub' | 'createdAt'>>,
12
+ ): Promise<SessionRecord | null>;
13
+ deleteSession(sid: string): Promise<void>;
14
+
15
+ revokeBySub(sub: string): Promise<number>;
16
+ revokeBySid(sid: string): Promise<void>;
17
+
18
+ markSidRevoked(sid: string, expiresAt: number): Promise<void>;
19
+ isSidRevoked(sid: string): Promise<boolean>;
20
+
21
+ purgeExpired(now: number): Promise<void>;
22
+
23
+ close(): void;
24
+
25
+ tryLockSession?(sid: string): Promise<{ acquired: boolean; token: string | null }>;
26
+ unlockSession?(sid: string, token: string | null): Promise<void>;
27
+ waitForSession?(sid: string, maxMs?: number): Promise<SessionRecord | null>;
28
+ }
@@ -0,0 +1,137 @@
1
+ // Cloudflare KV-backed SessionStore.
2
+ // Compatible with CF Workers, CF Pages Functions, and any runtime
3
+ // that exposes a KV namespace with get/put/delete methods.
4
+
5
+ import type { PkceRecord, SessionRecord } from '../types.js';
6
+ import type { SessionStore } from './interface.js';
7
+ import { bufToBase64, base64ToBuf, bufToBase64url } from '../utils.js';
8
+
9
+ export interface KVNamespace {
10
+ get(key: string): Promise<string | null>;
11
+ put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;
12
+ delete(key: string): Promise<void>;
13
+ }
14
+
15
+ type StoredSession = Omit<SessionRecord, 'refreshTokenEnc'> & { refreshTokenEnc: string };
16
+
17
+ function ttlSec(expiresAtMs: number): number {
18
+ return Math.max(Math.floor((expiresAtMs - Date.now()) / 1000), 60);
19
+ }
20
+
21
+ function serialize(rec: SessionRecord): StoredSession {
22
+ return { ...rec, refreshTokenEnc: bufToBase64(rec.refreshTokenEnc) };
23
+ }
24
+
25
+ function deserialize(stored: StoredSession): SessionRecord {
26
+ return { ...stored, refreshTokenEnc: base64ToBuf(stored.refreshTokenEnc) };
27
+ }
28
+
29
+ export class KvStore implements SessionStore {
30
+ constructor(private readonly kv: KVNamespace) {}
31
+
32
+ async createPkce(state: string, rec: PkceRecord): Promise<void> {
33
+ await this.kv.put(`pkce:${state}`, JSON.stringify(rec), { expirationTtl: ttlSec(rec.expiresAt) });
34
+ }
35
+
36
+ async consumePkce(state: string): Promise<PkceRecord | null> {
37
+ const raw = await this.kv.get(`pkce:${state}`);
38
+ if (!raw) return null;
39
+ await this.kv.delete(`pkce:${state}`);
40
+ const rec: PkceRecord = JSON.parse(raw);
41
+ if (rec.expiresAt < Date.now()) return null;
42
+ return rec;
43
+ }
44
+
45
+ async createSession(rec: SessionRecord): Promise<void> {
46
+ const ttl = ttlSec(rec.refreshExpiresAt);
47
+ await this.kv.put(`session:${rec.sid}`, JSON.stringify(serialize(rec)), { expirationTtl: ttl });
48
+ await this.kv.put(`sub:${rec.sub}`, rec.sid, { expirationTtl: ttl });
49
+ }
50
+
51
+ async getSession(sid: string): Promise<SessionRecord | null> {
52
+ const raw = await this.kv.get(`session:${sid}`);
53
+ if (!raw) return null;
54
+ return deserialize(JSON.parse(raw) as StoredSession);
55
+ }
56
+
57
+ async rotateSession(
58
+ sid: string,
59
+ patch: Partial<Omit<SessionRecord, 'sid' | 'sub' | 'createdAt'>>,
60
+ ): Promise<SessionRecord | null> {
61
+ const cur = await this.getSession(sid);
62
+ if (!cur) return null;
63
+ const next: SessionRecord = {
64
+ ...cur,
65
+ accessToken: patch.accessToken ?? cur.accessToken,
66
+ refreshTokenEnc: patch.refreshTokenEnc ?? cur.refreshTokenEnc,
67
+ idToken: patch.idToken !== undefined ? patch.idToken : cur.idToken,
68
+ accessExpiresAt: patch.accessExpiresAt ?? cur.accessExpiresAt,
69
+ refreshExpiresAt: patch.refreshExpiresAt ?? cur.refreshExpiresAt,
70
+ rotatedAt: patch.rotatedAt ?? Date.now(),
71
+ userAgent: patch.userAgent !== undefined ? patch.userAgent : cur.userAgent,
72
+ ip: patch.ip !== undefined ? patch.ip : cur.ip,
73
+ };
74
+ const ttl = ttlSec(next.refreshExpiresAt);
75
+ await this.kv.put(`session:${sid}`, JSON.stringify(serialize(next)), { expirationTtl: ttl });
76
+ return next;
77
+ }
78
+
79
+ async deleteSession(sid: string): Promise<void> {
80
+ const raw = await this.kv.get(`session:${sid}`);
81
+ if (raw) {
82
+ const stored = JSON.parse(raw) as StoredSession;
83
+ await this.kv.delete(`sub:${stored.sub}`);
84
+ }
85
+ await this.kv.delete(`session:${sid}`);
86
+ }
87
+
88
+ async revokeBySub(sub: string): Promise<number> {
89
+ const sid = await this.kv.get(`sub:${sub}`);
90
+ if (!sid) return 0;
91
+ await this.kv.delete(`session:${sid}`);
92
+ await this.kv.delete(`sub:${sub}`);
93
+ return 1;
94
+ }
95
+
96
+ async revokeBySid(sid: string): Promise<void> {
97
+ await this.deleteSession(sid);
98
+ }
99
+
100
+ async markSidRevoked(sid: string, expiresAt: number): Promise<void> {
101
+ await this.kv.put(`revoked:${sid}`, '1', { expirationTtl: ttlSec(expiresAt) });
102
+ }
103
+
104
+ async isSidRevoked(sid: string): Promise<boolean> {
105
+ return (await this.kv.get(`revoked:${sid}`)) === '1';
106
+ }
107
+
108
+ async purgeExpired(_now: number): Promise<void> {}
109
+
110
+ close(): void {}
111
+
112
+ async tryLockSession(sid: string): Promise<{ acquired: boolean; token: string | null }> {
113
+ const key = `refresh_lock:${sid}`;
114
+ const existing = await this.kv.get(key);
115
+ if (existing) return { acquired: false, token: null };
116
+ const token = bufToBase64url(crypto.getRandomValues(new Uint8Array(16)));
117
+ await this.kv.put(key, token, { expirationTtl: 60 });
118
+ return { acquired: true, token };
119
+ }
120
+
121
+ async unlockSession(sid: string, token: string | null): Promise<void> {
122
+ if (!token) return;
123
+ const key = `refresh_lock:${sid}`;
124
+ const current = await this.kv.get(key);
125
+ if (current === token) await this.kv.delete(key);
126
+ }
127
+
128
+ async waitForSession(sid: string, maxMs = 3000): Promise<SessionRecord | null> {
129
+ const end = Date.now() + maxMs;
130
+ while (Date.now() < end) {
131
+ await new Promise((r) => setTimeout(r, 200));
132
+ const s = await this.getSession(sid);
133
+ if (s) return s;
134
+ }
135
+ return null;
136
+ }
137
+ }