@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.
- package/dist/config.d.ts +12 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +75 -0
- package/dist/config.js.map +1 -0
- package/dist/idp.d.ts +25 -0
- package/dist/idp.d.ts.map +1 -0
- package/dist/idp.js +64 -0
- package/dist/idp.js.map +1 -0
- package/dist/index.d.ts +73 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +63 -0
- package/dist/index.js.map +1 -0
- package/dist/jwks/verifier.d.ts +18 -0
- package/dist/jwks/verifier.d.ts.map +1 -0
- package/dist/jwks/verifier.js +62 -0
- package/dist/jwks/verifier.js.map +1 -0
- package/dist/middleware/authenticate.d.ts +25 -0
- package/dist/middleware/authenticate.d.ts.map +1 -0
- package/dist/middleware/authenticate.js +173 -0
- package/dist/middleware/authenticate.js.map +1 -0
- package/dist/middleware/cookie.d.ts +13 -0
- package/dist/middleware/cookie.d.ts.map +1 -0
- package/dist/middleware/cookie.js +71 -0
- package/dist/middleware/cookie.js.map +1 -0
- package/dist/routes/backchannel.d.ts +12 -0
- package/dist/routes/backchannel.d.ts.map +1 -0
- package/dist/routes/backchannel.js +58 -0
- package/dist/routes/backchannel.js.map +1 -0
- package/dist/routes/callback.d.ts +12 -0
- package/dist/routes/callback.d.ts.map +1 -0
- package/dist/routes/callback.js +80 -0
- package/dist/routes/callback.js.map +1 -0
- package/dist/routes/login.d.ts +10 -0
- package/dist/routes/login.d.ts.map +1 -0
- package/dist/routes/login.js +60 -0
- package/dist/routes/login.js.map +1 -0
- package/dist/routes/logout.d.ts +10 -0
- package/dist/routes/logout.d.ts.map +1 -0
- package/dist/routes/logout.js +40 -0
- package/dist/routes/logout.js.map +1 -0
- package/dist/routes/me.d.ts +4 -0
- package/dist/routes/me.d.ts.map +1 -0
- package/dist/routes/me.js +27 -0
- package/dist/routes/me.js.map +1 -0
- package/dist/routes/refresh.d.ts +8 -0
- package/dist/routes/refresh.d.ts.map +1 -0
- package/dist/routes/refresh.js +30 -0
- package/dist/routes/refresh.js.map +1 -0
- package/dist/store/crypto.d.ts +5 -0
- package/dist/store/crypto.d.ts.map +1 -0
- package/dist/store/crypto.js +38 -0
- package/dist/store/crypto.js.map +1 -0
- package/dist/store/interface.d.ts +22 -0
- package/dist/store/interface.d.ts.map +1 -0
- package/dist/store/interface.js +2 -0
- package/dist/store/interface.js.map +1 -0
- package/dist/store/kv.d.ts +32 -0
- package/dist/store/kv.d.ts.map +1 -0
- package/dist/store/kv.js +117 -0
- package/dist/store/kv.js.map +1 -0
- package/dist/store/memory.d.ts +23 -0
- package/dist/store/memory.d.ts.map +1 -0
- package/dist/store/memory.js +102 -0
- package/dist/store/memory.js.map +1 -0
- package/dist/store/sqlite.d.ts +19 -0
- package/dist/store/sqlite.d.ts.map +1 -0
- package/dist/store/sqlite.js +144 -0
- package/dist/store/sqlite.js.map +1 -0
- package/dist/types.d.ts +66 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +4 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +6 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +28 -0
- package/dist/utils.js.map +1 -0
- package/package.json +91 -0
- package/src/config.ts +93 -0
- package/src/idp.ts +83 -0
- package/src/index.ts +120 -0
- package/src/jwks/verifier.ts +69 -0
- package/src/middleware/authenticate.ts +197 -0
- package/src/middleware/cookie.test.ts +29 -0
- package/src/middleware/cookie.ts +87 -0
- package/src/routes/backchannel.ts +67 -0
- package/src/routes/callback.ts +99 -0
- package/src/routes/login.ts +72 -0
- package/src/routes/logout.ts +50 -0
- package/src/routes/me.ts +26 -0
- package/src/routes/refresh.ts +35 -0
- package/src/store/crypto.test.ts +23 -0
- package/src/store/crypto.ts +51 -0
- package/src/store/interface.ts +28 -0
- package/src/store/kv.ts +137 -0
- package/src/store/memory.ts +110 -0
- package/src/store/sqlite.test.ts +111 -0
- package/src/store/sqlite.ts +201 -0
- package/src/types.ts +80 -0
- package/src/utils.ts +30 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// In-memory SessionStore for testing and stateless edge environments.
|
|
2
|
+
|
|
3
|
+
import type { PkceRecord, SessionRecord } from '../types.js';
|
|
4
|
+
import type { SessionStore } from './interface.js';
|
|
5
|
+
|
|
6
|
+
export class MemoryStore implements SessionStore {
|
|
7
|
+
private pkce = new Map<string, PkceRecord>();
|
|
8
|
+
private sessions = new Map<string, SessionRecord>();
|
|
9
|
+
private bySub = new Map<string, Set<string>>();
|
|
10
|
+
private revoked = new Map<string, number>();
|
|
11
|
+
|
|
12
|
+
async createPkce(state: string, rec: PkceRecord): Promise<void> {
|
|
13
|
+
this.pkce.set(state, rec);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async consumePkce(state: string): Promise<PkceRecord | null> {
|
|
17
|
+
const rec = this.pkce.get(state);
|
|
18
|
+
if (!rec) return null;
|
|
19
|
+
this.pkce.delete(state);
|
|
20
|
+
if (rec.expiresAt < Date.now()) return null;
|
|
21
|
+
return rec;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async createSession(rec: SessionRecord): Promise<void> {
|
|
25
|
+
this.sessions.set(rec.sid, rec);
|
|
26
|
+
const sids = this.bySub.get(rec.sub) ?? new Set();
|
|
27
|
+
sids.add(rec.sid);
|
|
28
|
+
this.bySub.set(rec.sub, sids);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async getSession(sid: string): Promise<SessionRecord | null> {
|
|
32
|
+
const s = this.sessions.get(sid);
|
|
33
|
+
if (!s) return null;
|
|
34
|
+
if (s.refreshExpiresAt < Date.now()) {
|
|
35
|
+
await this.deleteSession(sid);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
return s;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async rotateSession(
|
|
42
|
+
sid: string,
|
|
43
|
+
patch: Partial<Omit<SessionRecord, 'sid' | 'sub' | 'createdAt'>>,
|
|
44
|
+
): Promise<SessionRecord | null> {
|
|
45
|
+
const cur = this.sessions.get(sid);
|
|
46
|
+
if (!cur) return null;
|
|
47
|
+
const next: SessionRecord = { ...cur, ...patch, sid: cur.sid, sub: cur.sub, createdAt: cur.createdAt };
|
|
48
|
+
this.sessions.set(sid, next);
|
|
49
|
+
return next;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async deleteSession(sid: string): Promise<void> {
|
|
53
|
+
const s = this.sessions.get(sid);
|
|
54
|
+
if (s) {
|
|
55
|
+
const sids = this.bySub.get(s.sub);
|
|
56
|
+
sids?.delete(sid);
|
|
57
|
+
if (sids?.size === 0) this.bySub.delete(s.sub);
|
|
58
|
+
}
|
|
59
|
+
this.sessions.delete(sid);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async revokeBySub(sub: string): Promise<number> {
|
|
63
|
+
const sids = this.bySub.get(sub);
|
|
64
|
+
if (!sids) return 0;
|
|
65
|
+
const count = sids.size;
|
|
66
|
+
for (const sid of sids) this.sessions.delete(sid);
|
|
67
|
+
this.bySub.delete(sub);
|
|
68
|
+
return count;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async revokeBySid(sid: string): Promise<void> {
|
|
72
|
+
await this.deleteSession(sid);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async markSidRevoked(sid: string, expiresAt: number): Promise<void> {
|
|
76
|
+
this.revoked.set(sid, expiresAt);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async isSidRevoked(sid: string): Promise<boolean> {
|
|
80
|
+
const exp = this.revoked.get(sid);
|
|
81
|
+
if (!exp) return false;
|
|
82
|
+
if (exp < Date.now()) {
|
|
83
|
+
this.revoked.delete(sid);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async purgeExpired(now: number): Promise<void> {
|
|
90
|
+
for (const [state, rec] of this.pkce) if (rec.expiresAt < now) this.pkce.delete(state);
|
|
91
|
+
for (const [sid, rec] of this.sessions) {
|
|
92
|
+
if (rec.refreshExpiresAt < now) {
|
|
93
|
+
const sids = this.bySub.get(rec.sub);
|
|
94
|
+
sids?.delete(sid);
|
|
95
|
+
this.sessions.delete(sid);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const [sid, exp] of this.revoked) if (exp < now) this.revoked.delete(sid);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
close(): void {}
|
|
102
|
+
|
|
103
|
+
_get(sid: string): SessionRecord | undefined {
|
|
104
|
+
return this.sessions.get(sid);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
_size(): number {
|
|
108
|
+
return this.sessions.size;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { mkdtempSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
5
|
+
import { SqliteSessionStore } from './sqlite.js';
|
|
6
|
+
import { encryptSecret } from './crypto.js';
|
|
7
|
+
|
|
8
|
+
describe('SqliteSessionStore', () => {
|
|
9
|
+
let store: SqliteSessionStore;
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
const dir = mkdtempSync(join(tmpdir(), 'sso-test-'));
|
|
13
|
+
store = new SqliteSessionStore(join(dir, 'sso.db'));
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
afterEach(() => {
|
|
17
|
+
store.close();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('consumes PKCE state exactly once', async () => {
|
|
21
|
+
await store.createPkce('state-1', {
|
|
22
|
+
codeVerifier: 'cv',
|
|
23
|
+
nonce: 'n',
|
|
24
|
+
returnTo: '/',
|
|
25
|
+
expiresAt: Date.now() + 60_000,
|
|
26
|
+
});
|
|
27
|
+
const first = await store.consumePkce('state-1');
|
|
28
|
+
expect(first?.codeVerifier).toBe('cv');
|
|
29
|
+
expect(await store.consumePkce('state-1')).toBeNull();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('expired PKCE returns null', async () => {
|
|
33
|
+
await store.createPkce('state-2', { codeVerifier: 'cv', nonce: 'n', returnTo: '/', expiresAt: Date.now() - 10 });
|
|
34
|
+
expect(await store.consumePkce('state-2')).toBeNull();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('round-trips a session', async () => {
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
await store.createSession({
|
|
40
|
+
sid: 'sid-1',
|
|
41
|
+
sub: 'user-1',
|
|
42
|
+
accessToken: 'at',
|
|
43
|
+
refreshTokenEnc: await encryptSecret('rt', 'x'.repeat(48)),
|
|
44
|
+
idToken: 'idt',
|
|
45
|
+
accessExpiresAt: now + 900_000,
|
|
46
|
+
refreshExpiresAt: now + 30 * 86_400_000,
|
|
47
|
+
createdAt: now,
|
|
48
|
+
rotatedAt: now,
|
|
49
|
+
userAgent: 'ua',
|
|
50
|
+
ip: '127.0.0.1',
|
|
51
|
+
});
|
|
52
|
+
const s = await store.getSession('sid-1');
|
|
53
|
+
expect(s?.sub).toBe('user-1');
|
|
54
|
+
expect(s?.accessToken).toBe('at');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('rotateSession updates fields and preserves sub/createdAt', async () => {
|
|
58
|
+
const now = Date.now();
|
|
59
|
+
await store.createSession({
|
|
60
|
+
sid: 'sid-2',
|
|
61
|
+
sub: 'u',
|
|
62
|
+
accessToken: 'old',
|
|
63
|
+
refreshTokenEnc: await encryptSecret('rt', 'x'.repeat(48)),
|
|
64
|
+
idToken: null,
|
|
65
|
+
accessExpiresAt: now,
|
|
66
|
+
refreshExpiresAt: now + 86_400_000,
|
|
67
|
+
createdAt: now,
|
|
68
|
+
rotatedAt: now,
|
|
69
|
+
userAgent: null,
|
|
70
|
+
ip: null,
|
|
71
|
+
});
|
|
72
|
+
const rotated = await store.rotateSession('sid-2', {
|
|
73
|
+
accessToken: 'new',
|
|
74
|
+
accessExpiresAt: now + 900_000,
|
|
75
|
+
rotatedAt: now + 1000,
|
|
76
|
+
});
|
|
77
|
+
expect(rotated?.accessToken).toBe('new');
|
|
78
|
+
expect(rotated?.sub).toBe('u');
|
|
79
|
+
expect(rotated?.createdAt).toBe(now);
|
|
80
|
+
expect(rotated?.rotatedAt).toBe(now + 1000);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('revokeBySub deletes all sessions for the user', async () => {
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
const enc = await encryptSecret('rt', 'x'.repeat(48));
|
|
86
|
+
for (const sid of ['a', 'b', 'c']) {
|
|
87
|
+
await store.createSession({
|
|
88
|
+
sid,
|
|
89
|
+
sub: 'shared',
|
|
90
|
+
accessToken: 'at',
|
|
91
|
+
refreshTokenEnc: enc,
|
|
92
|
+
idToken: null,
|
|
93
|
+
accessExpiresAt: now,
|
|
94
|
+
refreshExpiresAt: now + 1000,
|
|
95
|
+
createdAt: now,
|
|
96
|
+
rotatedAt: now,
|
|
97
|
+
userAgent: null,
|
|
98
|
+
ip: null,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
expect(await store.revokeBySub('shared')).toBe(3);
|
|
102
|
+
expect(await store.getSession('a')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('markSidRevoked + isSidRevoked observes TTL', async () => {
|
|
106
|
+
await store.markSidRevoked('rs-1', Date.now() + 60_000);
|
|
107
|
+
expect(await store.isSidRevoked('rs-1')).toBe(true);
|
|
108
|
+
await store.markSidRevoked('rs-2', Date.now() - 10);
|
|
109
|
+
expect(await store.isSidRevoked('rs-2')).toBe(false);
|
|
110
|
+
});
|
|
111
|
+
});
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import Database from 'better-sqlite3';
|
|
4
|
+
import type { Database as DB } from 'better-sqlite3';
|
|
5
|
+
import type { PkceRecord, SessionRecord } from '../types.js';
|
|
6
|
+
import type { SessionStore } from './interface.js';
|
|
7
|
+
|
|
8
|
+
const SCHEMA = `
|
|
9
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
10
|
+
sid TEXT PRIMARY KEY,
|
|
11
|
+
sub TEXT NOT NULL,
|
|
12
|
+
access_token TEXT NOT NULL,
|
|
13
|
+
refresh_token_enc BLOB NOT NULL,
|
|
14
|
+
id_token TEXT,
|
|
15
|
+
access_expires_at INTEGER NOT NULL,
|
|
16
|
+
refresh_expires_at INTEGER NOT NULL,
|
|
17
|
+
created_at INTEGER NOT NULL,
|
|
18
|
+
rotated_at INTEGER NOT NULL,
|
|
19
|
+
user_agent TEXT,
|
|
20
|
+
ip TEXT
|
|
21
|
+
);
|
|
22
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_sub ON sessions(sub);
|
|
23
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_refresh_exp ON sessions(refresh_expires_at);
|
|
24
|
+
|
|
25
|
+
CREATE TABLE IF NOT EXISTS pkce_states (
|
|
26
|
+
state TEXT PRIMARY KEY,
|
|
27
|
+
code_verifier TEXT NOT NULL,
|
|
28
|
+
nonce TEXT NOT NULL,
|
|
29
|
+
return_to TEXT NOT NULL,
|
|
30
|
+
expires_at INTEGER NOT NULL
|
|
31
|
+
);
|
|
32
|
+
CREATE INDEX IF NOT EXISTS idx_pkce_exp ON pkce_states(expires_at);
|
|
33
|
+
|
|
34
|
+
CREATE TABLE IF NOT EXISTS revoked_sids (
|
|
35
|
+
sid TEXT PRIMARY KEY,
|
|
36
|
+
expires_at INTEGER NOT NULL
|
|
37
|
+
);
|
|
38
|
+
CREATE INDEX IF NOT EXISTS idx_revoked_exp ON revoked_sids(expires_at);
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
type SessionRow = {
|
|
42
|
+
sid: string;
|
|
43
|
+
sub: string;
|
|
44
|
+
access_token: string;
|
|
45
|
+
refresh_token_enc: Buffer;
|
|
46
|
+
id_token: string | null;
|
|
47
|
+
access_expires_at: number;
|
|
48
|
+
refresh_expires_at: number;
|
|
49
|
+
created_at: number;
|
|
50
|
+
rotated_at: number;
|
|
51
|
+
user_agent: string | null;
|
|
52
|
+
ip: string | null;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function rowToSession(r: SessionRow): SessionRecord {
|
|
56
|
+
return {
|
|
57
|
+
sid: r.sid,
|
|
58
|
+
sub: r.sub,
|
|
59
|
+
accessToken: r.access_token,
|
|
60
|
+
refreshTokenEnc: r.refresh_token_enc,
|
|
61
|
+
idToken: r.id_token,
|
|
62
|
+
accessExpiresAt: r.access_expires_at,
|
|
63
|
+
refreshExpiresAt: r.refresh_expires_at,
|
|
64
|
+
createdAt: r.created_at,
|
|
65
|
+
rotatedAt: r.rotated_at,
|
|
66
|
+
userAgent: r.user_agent,
|
|
67
|
+
ip: r.ip,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class SqliteSessionStore implements SessionStore {
|
|
72
|
+
private readonly db: DB;
|
|
73
|
+
|
|
74
|
+
constructor(dbPath: string) {
|
|
75
|
+
const dir = path.dirname(dbPath);
|
|
76
|
+
if (dir && dir !== '.' && !fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
77
|
+
this.db = new Database(dbPath);
|
|
78
|
+
this.db.pragma('journal_mode = WAL');
|
|
79
|
+
this.db.pragma('foreign_keys = ON');
|
|
80
|
+
this.db.exec(SCHEMA);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async createPkce(state: string, rec: PkceRecord): Promise<void> {
|
|
84
|
+
this.db
|
|
85
|
+
.prepare('INSERT INTO pkce_states (state, code_verifier, nonce, return_to, expires_at) VALUES (?, ?, ?, ?, ?)')
|
|
86
|
+
.run(state, rec.codeVerifier, rec.nonce, rec.returnTo, rec.expiresAt);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async consumePkce(state: string): Promise<PkceRecord | null> {
|
|
90
|
+
const tx = this.db.transaction((s: string): PkceRecord | null => {
|
|
91
|
+
const row = this.db
|
|
92
|
+
.prepare('SELECT code_verifier, nonce, return_to, expires_at FROM pkce_states WHERE state = ?')
|
|
93
|
+
.get(s) as { code_verifier: string; nonce: string; return_to: string; expires_at: number } | undefined;
|
|
94
|
+
if (!row) return null;
|
|
95
|
+
this.db.prepare('DELETE FROM pkce_states WHERE state = ?').run(s);
|
|
96
|
+
if (row.expires_at < Date.now()) return null;
|
|
97
|
+
return { codeVerifier: row.code_verifier, nonce: row.nonce, returnTo: row.return_to, expiresAt: row.expires_at };
|
|
98
|
+
});
|
|
99
|
+
return tx(state);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async createSession(rec: SessionRecord): Promise<void> {
|
|
103
|
+
this.db
|
|
104
|
+
.prepare(
|
|
105
|
+
`INSERT INTO sessions (sid, sub, access_token, refresh_token_enc, id_token, access_expires_at, refresh_expires_at, created_at, rotated_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
106
|
+
)
|
|
107
|
+
.run(
|
|
108
|
+
rec.sid,
|
|
109
|
+
rec.sub,
|
|
110
|
+
rec.accessToken,
|
|
111
|
+
rec.refreshTokenEnc,
|
|
112
|
+
rec.idToken,
|
|
113
|
+
rec.accessExpiresAt,
|
|
114
|
+
rec.refreshExpiresAt,
|
|
115
|
+
rec.createdAt,
|
|
116
|
+
rec.rotatedAt,
|
|
117
|
+
rec.userAgent,
|
|
118
|
+
rec.ip,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async getSession(sid: string): Promise<SessionRecord | null> {
|
|
123
|
+
const row = this.db.prepare('SELECT * FROM sessions WHERE sid = ?').get(sid) as SessionRow | undefined;
|
|
124
|
+
return row ? rowToSession(row) : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async rotateSession(
|
|
128
|
+
sid: string,
|
|
129
|
+
patch: Partial<Omit<SessionRecord, 'sid' | 'sub' | 'createdAt'>>,
|
|
130
|
+
): Promise<SessionRecord | null> {
|
|
131
|
+
const cur = (this.db.prepare('SELECT * FROM sessions WHERE sid = ?').get(sid) as SessionRow | undefined) ?? null;
|
|
132
|
+
if (!cur) return null;
|
|
133
|
+
const next: SessionRow = {
|
|
134
|
+
sid: cur.sid,
|
|
135
|
+
sub: cur.sub,
|
|
136
|
+
access_token: patch.accessToken ?? cur.access_token,
|
|
137
|
+
refresh_token_enc: (patch.refreshTokenEnc as Buffer | undefined) ?? cur.refresh_token_enc,
|
|
138
|
+
id_token: patch.idToken !== undefined ? patch.idToken : cur.id_token,
|
|
139
|
+
access_expires_at: patch.accessExpiresAt ?? cur.access_expires_at,
|
|
140
|
+
refresh_expires_at: patch.refreshExpiresAt ?? cur.refresh_expires_at,
|
|
141
|
+
created_at: cur.created_at,
|
|
142
|
+
rotated_at: patch.rotatedAt ?? Date.now(),
|
|
143
|
+
user_agent: patch.userAgent !== undefined ? patch.userAgent : cur.user_agent,
|
|
144
|
+
ip: patch.ip !== undefined ? patch.ip : cur.ip,
|
|
145
|
+
};
|
|
146
|
+
this.db
|
|
147
|
+
.prepare(
|
|
148
|
+
`UPDATE sessions SET access_token = ?, refresh_token_enc = ?, id_token = ?, access_expires_at = ?, refresh_expires_at = ?, rotated_at = ?, user_agent = ?, ip = ? WHERE sid = ?`,
|
|
149
|
+
)
|
|
150
|
+
.run(
|
|
151
|
+
next.access_token,
|
|
152
|
+
next.refresh_token_enc,
|
|
153
|
+
next.id_token,
|
|
154
|
+
next.access_expires_at,
|
|
155
|
+
next.refresh_expires_at,
|
|
156
|
+
next.rotated_at,
|
|
157
|
+
next.user_agent,
|
|
158
|
+
next.ip,
|
|
159
|
+
sid,
|
|
160
|
+
);
|
|
161
|
+
return rowToSession(next);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async deleteSession(sid: string): Promise<void> {
|
|
165
|
+
this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async revokeBySub(sub: string): Promise<number> {
|
|
169
|
+
const info = this.db.prepare('DELETE FROM sessions WHERE sub = ?').run(sub);
|
|
170
|
+
return info.changes;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async revokeBySid(sid: string): Promise<void> {
|
|
174
|
+
this.db.prepare('DELETE FROM sessions WHERE sid = ?').run(sid);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async markSidRevoked(sid: string, expiresAt: number): Promise<void> {
|
|
178
|
+
this.db.prepare('INSERT OR REPLACE INTO revoked_sids (sid, expires_at) VALUES (?, ?)').run(sid, expiresAt);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async isSidRevoked(sid: string): Promise<boolean> {
|
|
182
|
+
const row = this.db.prepare('SELECT expires_at FROM revoked_sids WHERE sid = ?').get(sid) as
|
|
183
|
+
{ expires_at: number } | undefined;
|
|
184
|
+
if (!row) return false;
|
|
185
|
+
if (row.expires_at < Date.now()) {
|
|
186
|
+
this.db.prepare('DELETE FROM revoked_sids WHERE sid = ?').run(sid);
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async purgeExpired(now: number): Promise<void> {
|
|
193
|
+
this.db.prepare('DELETE FROM pkce_states WHERE expires_at < ?').run(now);
|
|
194
|
+
this.db.prepare('DELETE FROM sessions WHERE refresh_expires_at < ?').run(now);
|
|
195
|
+
this.db.prepare('DELETE FROM revoked_sids WHERE expires_at < ?').run(now);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
close(): void {
|
|
199
|
+
this.db.close();
|
|
200
|
+
}
|
|
201
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Public types for @ropean/sso-client. Kept dependency-free so this file can be
|
|
2
|
+
// imported without pulling in hono/jose/sqlite.
|
|
3
|
+
|
|
4
|
+
export interface SsoConfig {
|
|
5
|
+
// IDP
|
|
6
|
+
issuer: string; // e.g. https://sso.ropean.org/oauth
|
|
7
|
+
clientId: string;
|
|
8
|
+
clientSecret: string;
|
|
9
|
+
redirectUri: string; // {clientUri}/auth/callback
|
|
10
|
+
scopes: string; // space-separated, default: "openid profile email offline_access"
|
|
11
|
+
audience?: string; // optional aud validation; defaults to clientId
|
|
12
|
+
|
|
13
|
+
// Logout
|
|
14
|
+
postLogoutRedirectUri?: string;
|
|
15
|
+
|
|
16
|
+
// Session / cookie
|
|
17
|
+
sessionSecret: string; // 32+ random bytes; used for HMAC + AES-256-GCM
|
|
18
|
+
cookieName: string; // default: "sso_sid"
|
|
19
|
+
cookieDomain?: string;
|
|
20
|
+
cookieSecure: boolean; // default: true (force HTTPS)
|
|
21
|
+
cookieSameSite: 'Lax' | 'Strict' | 'None';
|
|
22
|
+
cookieMaxAgeSec: number; // default: refresh-token lifetime (30 days)
|
|
23
|
+
|
|
24
|
+
// Storage
|
|
25
|
+
dbPath: string; // SQLite file path (default: "./sso.db")
|
|
26
|
+
|
|
27
|
+
// Behavior
|
|
28
|
+
refreshSkewMs: number; // renew when access_token < skew from exp (default 120_000)
|
|
29
|
+
isDebug: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PkceRecord {
|
|
33
|
+
codeVerifier: string;
|
|
34
|
+
nonce: string;
|
|
35
|
+
returnTo: string;
|
|
36
|
+
expiresAt: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface SessionRecord {
|
|
40
|
+
sid: string;
|
|
41
|
+
sub: string;
|
|
42
|
+
accessToken: string;
|
|
43
|
+
refreshTokenEnc: Uint8Array; // AES-256-GCM ciphertext (with IV + tag prefix)
|
|
44
|
+
idToken: string | null;
|
|
45
|
+
accessExpiresAt: number; // ms epoch
|
|
46
|
+
refreshExpiresAt: number; // ms epoch
|
|
47
|
+
createdAt: number;
|
|
48
|
+
rotatedAt: number;
|
|
49
|
+
userAgent: string | null;
|
|
50
|
+
ip: string | null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface UserClaims {
|
|
54
|
+
sub: string;
|
|
55
|
+
iss?: string;
|
|
56
|
+
aud?: string | string[];
|
|
57
|
+
exp?: number;
|
|
58
|
+
iat?: number;
|
|
59
|
+
jti?: string;
|
|
60
|
+
client_id?: string;
|
|
61
|
+
scope?: string;
|
|
62
|
+
role?: string;
|
|
63
|
+
org_id?: string | null;
|
|
64
|
+
sid?: string;
|
|
65
|
+
// OIDC profile (when carried)
|
|
66
|
+
preferred_username?: string;
|
|
67
|
+
username?: string;
|
|
68
|
+
name?: string;
|
|
69
|
+
email?: string;
|
|
70
|
+
email_verified?: boolean;
|
|
71
|
+
picture?: string;
|
|
72
|
+
// Allow passthrough custom claims
|
|
73
|
+
[key: string]: unknown;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface AuthContext {
|
|
77
|
+
user: UserClaims;
|
|
78
|
+
source: 'cookie' | 'bearer';
|
|
79
|
+
session?: { sid: string; sub: string };
|
|
80
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Cross-runtime base64url + random byte utilities (Web Crypto API only, no node:crypto)
|
|
2
|
+
|
|
3
|
+
export function bufToBase64url(buf: Uint8Array): string {
|
|
4
|
+
let binary = '';
|
|
5
|
+
for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i] as number);
|
|
6
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function base64urlToBuf(str: string): Uint8Array {
|
|
10
|
+
const b64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
|
11
|
+
const pad = (4 - (b64.length % 4)) % 4;
|
|
12
|
+
const binary = atob(b64 + '='.repeat(pad));
|
|
13
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function bufToBase64(buf: Uint8Array): string {
|
|
17
|
+
let binary = '';
|
|
18
|
+
for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i] as number);
|
|
19
|
+
return btoa(binary);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function base64ToBuf(str: string): Uint8Array {
|
|
23
|
+
const binary = atob(str);
|
|
24
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function randomHex(byteLen: number): string {
|
|
28
|
+
const bytes = crypto.getRandomValues(new Uint8Array(byteLen));
|
|
29
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
30
|
+
}
|