@canicula/sirius-oidc-server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # @canicula/sirius-oidc-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client OpenID Connect pour coller **Sirius** dans le backend d’un outil interne.
4
+
5
+ L’utilisateur s’authentifie sur le CMS (2FA compris) et revient dans l’outil déjà
6
+ identifié. Vous n’avez pas à gérer les mots de passe.
7
+
8
+ À utiliser avec [`@canicula/sirius-oidc-client`](https://www.npmjs.com/package/@canicula/sirius-oidc-client)
9
+ pour les boutons de connexion / déconnexion.
10
+
11
+ ```bash
12
+ npm install @canicula/sirius-oidc-server
13
+ ```
14
+
15
+ Demandez à l’équipe Sirius un accès pour **votre instance** (Le Monde, l’Obs,
16
+ etc.) : un identifiant client, un secret, et l’URL de retour de votre outil
17
+ (en HTTPS).
18
+
19
+ ## Config
20
+
21
+ ```env
22
+ SIRIUS_OIDC_ISSUER=https://lemonde.sirius.press/oidc
23
+ SIRIUS_OIDC_CLIENT_ID= # fourni par Sirius
24
+ SIRIUS_OIDC_CLIENT_SECRET= # fourni par Sirius
25
+ SIRIUS_OIDC_REDIRECT_URI=https://votre-outil.lemonde.fr/auth/callback
26
+ SIRIUS_OIDC_COOKIE_SECRET= # une longue chaîne aléatoire, à vous
27
+ ```
28
+
29
+ `ISSUER` = l’instance Sirius visée.
30
+ `REDIRECT_URI` = la page de retour chez vous. Elle doit être **identique** à
31
+ celle déclarée par Sirius (schéma, hôte, chemin).
32
+ `COOKIE_SECRET` = pour verrouiller la session de **votre** outil, pas le secret
33
+ Sirius (32 caractères minimum).
34
+
35
+ ## Client SSO
36
+
37
+ Une fois, au démarrage du serveur :
38
+
39
+ ```ts
40
+ import { createSiriusAuthFromEnv } from "@canicula/sirius-oidc-server";
41
+
42
+ export const siriusAuth = createSiriusAuthFromEnv();
43
+ ```
44
+
45
+ ## Trois routes
46
+
47
+ ### `GET /login` — démarrer la connexion
48
+
49
+ ```ts
50
+ export const GET = siriusAuth.handleLogin;
51
+ ```
52
+
53
+ ### `GET /auth/callback` — revenir de Sirius
54
+
55
+ L’URL publique de cette route = `SIRIUS_OIDC_REDIRECT_URI`.
56
+
57
+ ```ts
58
+ export const GET = siriusAuth.handleCallback;
59
+ ```
60
+
61
+ En cas de souci, l’utilisateur arrive sur `/?error=…`.
62
+
63
+ ### `GET /logout` — fermer la session de l’outil
64
+
65
+ Ça ne déconnecte pas Sirius.
66
+
67
+ ```ts
68
+ export const GET = siriusAuth.handleLogout;
69
+ ```
70
+
71
+ ## Session
72
+
73
+ ```ts
74
+ const session = await siriusAuth.getSession(request.headers.get("cookie"));
75
+
76
+ if (!session) {
77
+ // afficher le bouton de connexion
78
+ } else {
79
+ // session.user.email, session.user.name
80
+ }
81
+ ```
82
+
83
+ Pour mémoriser le compte en base, n’utilisez **pas** seulement l’e-mail.
84
+ Gardez **l’instance Sirius + l’identifiant** (`session.user.iss` et
85
+ `session.user.sub`). Un changement d’e-mail ne cassera pas le lien ; un même
86
+ e-mail sur deux sites Sirius restera deux personnes.
87
+
88
+ La session outil dure **cinq minutes**. Au-delà, renvoyer vers `/login`.
89
+ Il n’y a pas de « rester connecté » automatique.
90
+
91
+ Pour un second outil ou une autre instance, nouveau client Sirius et nouvelles
92
+ variables `SIRIUS_OIDC_*`.
@@ -0,0 +1,67 @@
1
+ type SiriusUser = {
2
+ iss: string;
3
+ sub: string;
4
+ name?: string;
5
+ given_name?: string;
6
+ family_name?: string;
7
+ email?: string;
8
+ };
9
+ type SiriusTokens = {
10
+ access_token: string;
11
+ id_token?: string;
12
+ token_type?: string;
13
+ expires_in?: number;
14
+ scope?: string;
15
+ };
16
+ type SiriusSession = {
17
+ user: SiriusUser;
18
+ expiresAt: number;
19
+ tokens?: SiriusTokens;
20
+ };
21
+ type CreateSiriusAuthOptions = {
22
+ issuer: string;
23
+ clientId: string;
24
+ clientSecret: string;
25
+ redirectUri: string;
26
+ cookieSecret: string;
27
+ scopes?: string;
28
+ sessionTtl?: number;
29
+ postLoginPath?: string;
30
+ postLogoutPath?: string;
31
+ cookieName?: string;
32
+ };
33
+
34
+ declare function createSiriusAuth(options: CreateSiriusAuthOptions): {
35
+ handleLogin: () => Promise<Response>;
36
+ handleCallback: (request: Request) => Promise<Response>;
37
+ handleLogout: (request: Request) => Promise<Response>;
38
+ getSession: (cookieHeader: string | null | undefined, { includeTokens }?: {
39
+ includeTokens?: boolean | undefined;
40
+ }) => Promise<SiriusSession | null>;
41
+ getSessionFromCookieStore: (store: {
42
+ getAll: () => {
43
+ name: string;
44
+ value: string;
45
+ }[];
46
+ }, options?: {
47
+ includeTokens?: boolean;
48
+ }) => Promise<SiriusSession | null>;
49
+ };
50
+ declare function createSiriusAuthFromEnv(env?: NodeJS.ProcessEnv): {
51
+ handleLogin: () => Promise<Response>;
52
+ handleCallback: (request: Request) => Promise<Response>;
53
+ handleLogout: (request: Request) => Promise<Response>;
54
+ getSession: (cookieHeader: string | null | undefined, { includeTokens }?: {
55
+ includeTokens?: boolean | undefined;
56
+ }) => Promise<SiriusSession | null>;
57
+ getSessionFromCookieStore: (store: {
58
+ getAll: () => {
59
+ name: string;
60
+ value: string;
61
+ }[];
62
+ }, options?: {
63
+ includeTokens?: boolean;
64
+ }) => Promise<SiriusSession | null>;
65
+ };
66
+
67
+ export { type CreateSiriusAuthOptions, type SiriusSession, type SiriusTokens, type SiriusUser, createSiriusAuth, createSiriusAuthFromEnv };
package/dist/index.js ADDED
@@ -0,0 +1,244 @@
1
+ // src/auth.ts
2
+ import * as client from "openid-client";
3
+
4
+ // src/cookies.ts
5
+ import { CompactEncrypt, compactDecrypt } from "jose";
6
+ function parseCookieHeader(header) {
7
+ const cookies = {};
8
+ for (const part of String(header ?? "").split(";")) {
9
+ const index = part.indexOf("=");
10
+ if (index === -1) continue;
11
+ cookies[part.slice(0, index).trim()] = decodeURIComponent(
12
+ part.slice(index + 1).trim()
13
+ );
14
+ }
15
+ return cookies;
16
+ }
17
+ function serializeCookie(cookie) {
18
+ const pieces = [
19
+ `${cookie.name}=${encodeURIComponent(cookie.value)}`,
20
+ `Path=${cookie.path}`,
21
+ `Max-Age=${cookie.maxAge}`,
22
+ `SameSite=${cookie.sameSite}`
23
+ ];
24
+ if (cookie.httpOnly) pieces.push("HttpOnly");
25
+ if (cookie.secure) pieces.push("Secure");
26
+ return pieces.join("; ");
27
+ }
28
+ function cookieChange(name, value, maxAge) {
29
+ return {
30
+ name,
31
+ value,
32
+ maxAge,
33
+ path: "/",
34
+ httpOnly: true,
35
+ secure: true,
36
+ sameSite: "lax"
37
+ };
38
+ }
39
+ function deleteCookie(name) {
40
+ return cookieChange(name, "", 0);
41
+ }
42
+ async function secretKey(secret) {
43
+ return new Uint8Array(
44
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))
45
+ );
46
+ }
47
+ async function encryptJson(secret, payload) {
48
+ return new CompactEncrypt(
49
+ new TextEncoder().encode(JSON.stringify(payload))
50
+ ).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).encrypt(await secretKey(secret));
51
+ }
52
+ async function decryptJson(secret, token) {
53
+ try {
54
+ const { plaintext } = await compactDecrypt(token, await secretKey(secret));
55
+ return JSON.parse(new TextDecoder().decode(plaintext));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ // src/auth.ts
62
+ var PKCE_COOKIE = "sirius_oidc_pkce";
63
+ var DEFAULT_SESSION_TTL = 300;
64
+ var DEFAULT_SCOPES = "openid profile email";
65
+ function normalizeIssuer(issuer) {
66
+ return issuer.replace(/\/$/, "");
67
+ }
68
+ function asString(value) {
69
+ return typeof value === "string" && value.length > 0 ? value : void 0;
70
+ }
71
+ function redirect(location, cookies = [], status = 303) {
72
+ const headers = new Headers({ Location: String(location) });
73
+ for (const cookie of cookies) {
74
+ headers.append("Set-Cookie", serializeCookie(cookie));
75
+ }
76
+ return new Response(null, { status, headers });
77
+ }
78
+ function homeUrl(request, path, error) {
79
+ const url = new URL(path, request.url);
80
+ if (error) url.searchParams.set("error", error);
81
+ else url.searchParams.delete("error");
82
+ return url;
83
+ }
84
+ function toUser(issuer, userinfo) {
85
+ const sub = asString(userinfo.sub);
86
+ if (!sub) return null;
87
+ return {
88
+ iss: issuer,
89
+ sub,
90
+ name: asString(userinfo.name),
91
+ given_name: asString(userinfo.given_name),
92
+ family_name: asString(userinfo.family_name),
93
+ email: asString(userinfo.email)
94
+ };
95
+ }
96
+ function createSiriusAuth(options) {
97
+ if (options.cookieSecret.length < 32) {
98
+ throw new Error("cookieSecret must be at least 32 characters");
99
+ }
100
+ const issuer = normalizeIssuer(options.issuer);
101
+ const scopes = options.scopes ?? DEFAULT_SCOPES;
102
+ const sessionTtl = options.sessionTtl ?? DEFAULT_SESSION_TTL;
103
+ const postLoginPath = options.postLoginPath ?? "/";
104
+ const postLogoutPath = options.postLogoutPath ?? "/";
105
+ const sessionCookie = options.cookieName ?? "sirius_oidc_session";
106
+ let discovered;
107
+ async function configuration() {
108
+ discovered ??= await client.discovery(
109
+ new URL(issuer),
110
+ options.clientId,
111
+ { token_endpoint_auth_method: "client_secret_basic" },
112
+ client.ClientSecretBasic(options.clientSecret)
113
+ );
114
+ return discovered;
115
+ }
116
+ async function handleLogin() {
117
+ const config = await configuration();
118
+ const verifier = client.randomPKCECodeVerifier();
119
+ const challenge = await client.calculatePKCECodeChallenge(verifier);
120
+ const state = client.randomState();
121
+ const pkce = await encryptJson(options.cookieSecret, {
122
+ verifier,
123
+ state
124
+ });
125
+ const authorizeUrl = client.buildAuthorizationUrl(config, {
126
+ redirect_uri: options.redirectUri,
127
+ scope: scopes,
128
+ code_challenge: challenge,
129
+ code_challenge_method: "S256",
130
+ state
131
+ });
132
+ return redirect(authorizeUrl, [cookieChange(PKCE_COOKIE, pkce, 10 * 60)]);
133
+ }
134
+ async function handleCallback(request) {
135
+ const currentUrl = new URL(request.url);
136
+ const oidcError = currentUrl.searchParams.get("error");
137
+ if (oidcError) {
138
+ const description = currentUrl.searchParams.get("error_description");
139
+ return redirect(
140
+ homeUrl(
141
+ request,
142
+ postLoginPath,
143
+ description ? `${oidcError}: ${description}` : oidcError
144
+ ),
145
+ [deleteCookie(PKCE_COOKIE)]
146
+ );
147
+ }
148
+ const cookies = parseCookieHeader(request.headers.get("cookie"));
149
+ const pkce = cookies[PKCE_COOKIE] ? await decryptJson(options.cookieSecret, cookies[PKCE_COOKIE]) : null;
150
+ if (!pkce) {
151
+ return redirect(
152
+ homeUrl(request, postLoginPath, "PKCE cookie missing or invalid"),
153
+ [deleteCookie(PKCE_COOKIE)]
154
+ );
155
+ }
156
+ try {
157
+ const config = await configuration();
158
+ const tokens = await client.authorizationCodeGrant(config, currentUrl, {
159
+ pkceCodeVerifier: pkce.verifier,
160
+ expectedState: pkce.state,
161
+ idTokenExpected: true
162
+ });
163
+ const claims = tokens.claims();
164
+ const sub = claims?.sub;
165
+ if (!sub) throw new Error("ID token is missing sub");
166
+ const userinfo = await client.fetchUserInfo(
167
+ config,
168
+ tokens.access_token,
169
+ sub
170
+ );
171
+ const user = toUser(issuer, userinfo);
172
+ if (!user) throw new Error("userinfo is missing sub");
173
+ const session = {
174
+ user,
175
+ expiresAt: Date.now() + sessionTtl * 1e3,
176
+ tokens: {
177
+ access_token: tokens.access_token,
178
+ id_token: tokens.id_token,
179
+ token_type: tokens.token_type,
180
+ expires_in: tokens.expires_in,
181
+ scope: asString(tokens.scope)
182
+ }
183
+ };
184
+ const encrypted = await encryptJson(options.cookieSecret, session);
185
+ return redirect(homeUrl(request, postLoginPath), [
186
+ deleteCookie(PKCE_COOKIE),
187
+ cookieChange(sessionCookie, encrypted, sessionTtl)
188
+ ]);
189
+ } catch (error) {
190
+ const message = error instanceof Error ? error.message : String(error);
191
+ return redirect(homeUrl(request, postLoginPath, message), [
192
+ deleteCookie(PKCE_COOKIE)
193
+ ]);
194
+ }
195
+ }
196
+ async function handleLogout(request) {
197
+ return redirect(homeUrl(request, postLogoutPath), [
198
+ deleteCookie(PKCE_COOKIE),
199
+ deleteCookie(sessionCookie)
200
+ ]);
201
+ }
202
+ async function getSession(cookieHeader, { includeTokens = false } = {}) {
203
+ const cookies = parseCookieHeader(cookieHeader);
204
+ const raw = cookies[sessionCookie];
205
+ if (!raw) return null;
206
+ const session = await decryptJson(
207
+ options.cookieSecret,
208
+ raw
209
+ );
210
+ if (!session || session.expiresAt <= Date.now()) return null;
211
+ if (includeTokens) return session;
212
+ return { user: session.user, expiresAt: session.expiresAt };
213
+ }
214
+ async function getSessionFromCookieStore(store, options2) {
215
+ const header = store.getAll().map((cookie) => `${cookie.name}=${encodeURIComponent(cookie.value)}`).join("; ");
216
+ return getSession(header, options2);
217
+ }
218
+ return {
219
+ handleLogin,
220
+ handleCallback,
221
+ handleLogout,
222
+ getSession,
223
+ getSessionFromCookieStore
224
+ };
225
+ }
226
+ function createSiriusAuthFromEnv(env = process.env) {
227
+ const read = (name) => {
228
+ const value = env[name];
229
+ if (!value) throw new Error(`Missing ${name}`);
230
+ return value;
231
+ };
232
+ return createSiriusAuth({
233
+ issuer: read("SIRIUS_OIDC_ISSUER"),
234
+ clientId: read("SIRIUS_OIDC_CLIENT_ID"),
235
+ clientSecret: read("SIRIUS_OIDC_CLIENT_SECRET"),
236
+ redirectUri: read("SIRIUS_OIDC_REDIRECT_URI"),
237
+ cookieSecret: read("SIRIUS_OIDC_COOKIE_SECRET"),
238
+ scopes: env.SIRIUS_OIDC_SCOPE
239
+ });
240
+ }
241
+ export {
242
+ createSiriusAuth,
243
+ createSiriusAuthFromEnv
244
+ };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@canicula/sirius-oidc-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Client OpenID Connect Sirius pour le backend d’un outil interne.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": ["dist"],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "scripts": {
21
+ "build": "tsup src/index.ts --format esm --dts --clean",
22
+ "prepare": "npm run build"
23
+ },
24
+ "dependencies": {
25
+ "jose": "6.1.3",
26
+ "openid-client": "6.8.1"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^24.10.1",
30
+ "tsup": "^8.5.1",
31
+ "typescript": "^5.9.3"
32
+ },
33
+ "engines": {
34
+ "node": ">=20"
35
+ }
36
+ }