@opensas/oidc-sveltekit-adapter 0.0.0-stage → 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/COPYING +674 -0
- package/COPYING.LESSER +165 -0
- package/README.md +222 -2
- package/dist/index.d.ts +7 -0
- package/dist/index.js +10 -0
- package/dist/oidc/domain-user.d.ts +7 -0
- package/dist/oidc/domain-user.js +35 -0
- package/dist/oidc/errors.d.ts +14 -0
- package/dist/oidc/errors.js +27 -0
- package/dist/oidc/permissions.d.ts +3 -0
- package/dist/oidc/permissions.js +32 -0
- package/dist/oidc/provider.d.ts +33 -0
- package/dist/oidc/provider.js +134 -0
- package/dist/oidc/request.d.ts +4 -0
- package/dist/oidc/request.js +23 -0
- package/dist/oidc/types.d.ts +1 -0
- package/dist/oidc/types.js +1 -0
- package/dist/oidc/user.d.ts +10 -0
- package/dist/oidc/user.js +27 -0
- package/dist/sveltekit-handlers.d.ts +18 -0
- package/dist/sveltekit-handlers.js +122 -0
- package/package.json +118 -3
package/COPYING.LESSER
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
package/README.md
CHANGED
|
@@ -1,3 +1,223 @@
|
|
|
1
|
-
#
|
|
1
|
+
# oidc-sveltekit-adapter
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Proyecto _de uso interno_ que resuelve el login por **OpenID Connect** (ADFS, Keycloak) para las
|
|
4
|
+
aplicaciones SvelteKit.
|
|
5
|
+
|
|
6
|
+
npm: `@opensas/oidc-sveltekit-adapter` (todavía sin publicar).
|
|
7
|
+
|
|
8
|
+
## Estado
|
|
9
|
+
|
|
10
|
+
Etapas 1 y 2 terminadas: la API genérica (`createOidcProvider` y helpers, en `src/lib/oidc/`, sin
|
|
11
|
+
SvelteKit) y `createOidcSvelteKitHandlers`, con la app de prueba (`src/routes/`) usando las dos, con
|
|
12
|
+
unitarios y e2e contra el Keycloak de Docker. Quedan para después el diagnóstico del proveedor y la
|
|
13
|
+
prueba con ADFS. El diseño
|
|
14
|
+
completo (API, cookies, flujo) y el plan de trabajo están en
|
|
15
|
+
[`docs/todos/oidc-sveltekit-adapter.md`](docs/todos/oidc-sveltekit-adapter.md).
|
|
16
|
+
|
|
17
|
+
## Uso
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pnpm add @opensas/oidc-sveltekit-adapter
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Authorization Code Flow con PKCE, sobre `openid-client`. Dos formas de usarlo.
|
|
24
|
+
|
|
25
|
+
### SvelteKit: `createOidcSvelteKitHandlers`
|
|
26
|
+
|
|
27
|
+
El componente arma las rutas `<basePath>/login`, `/callback` y `/logout`, las cookies del login y
|
|
28
|
+
los redirects. La app arma su sesión en `onLogin` y la borra en `onLogout`.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
// src/lib/server/oidc.ts
|
|
32
|
+
import { getUser } from '@opensas/oidc-sveltekit-adapter';
|
|
33
|
+
import { createOidcSvelteKitHandlers } from '@opensas/oidc-sveltekit-adapter/sveltekit';
|
|
34
|
+
|
|
35
|
+
import { AUTH_CLIENT_ID, AUTH_CLIENT_SECRET, AUTH_ISSUER } from '$env/static/private';
|
|
36
|
+
|
|
37
|
+
export const oidc = createOidcSvelteKitHandlers({
|
|
38
|
+
issuer: AUTH_ISSUER, // el realm de Keycloak o https://<adfs>/adfs
|
|
39
|
+
clientId: AUTH_CLIENT_ID,
|
|
40
|
+
clientSecret: AUTH_CLIENT_SECRET, // sin él, client público (solo PKCE)
|
|
41
|
+
basePath: '/api/auth',
|
|
42
|
+
cookiePrefix: 'miapp',
|
|
43
|
+
sessionMaxAge: 8 * 3600,
|
|
44
|
+
onLogin: (tokens, { cookies }) => {
|
|
45
|
+
const user = getUser(tokens, { defaultDomain: 'ORGANIZACION' });
|
|
46
|
+
if (!user) return false; // sin usuario de red: 401
|
|
47
|
+
createSession(cookies, user); // la sesión es de la app
|
|
48
|
+
},
|
|
49
|
+
onLogout: ({ cookies }) => deleteSession(cookies),
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// src/routes/api/auth/[...path]/+server.ts
|
|
55
|
+
import { oidc } from '$lib/server/oidc';
|
|
56
|
+
|
|
57
|
+
export const GET = oidc.handler;
|
|
58
|
+
export const POST = oidc.handler;
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// src/hooks.server.ts: sin sesión, las navegaciones van al login (con returnTo)
|
|
63
|
+
export const handle: Handle = ({ event, resolve }) => {
|
|
64
|
+
event.locals.user = getSession(event.cookies);
|
|
65
|
+
if (!event.locals.user) {
|
|
66
|
+
const login = oidc.loginRedirect(event);
|
|
67
|
+
if (login) redirect(303, login);
|
|
68
|
+
}
|
|
69
|
+
return resolve(event);
|
|
70
|
+
};
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
El logout es un `POST` a `<basePath>/logout` (por ejemplo, un `<form method="POST">`).
|
|
74
|
+
|
|
75
|
+
En el proveedor, el redirect URI del client es `<origin><basePath>/callback`
|
|
76
|
+
(`http://localhost:5173/api/auth/callback`), y el post logout redirect URI, `<origin>/`.
|
|
77
|
+
|
|
78
|
+
### Cualquier app Node: `createOidcProvider`
|
|
79
|
+
|
|
80
|
+
Desde `@opensas/oidc-sveltekit-adapter`, sin SvelteKit (`@sveltejs/kit` es una peer dependency
|
|
81
|
+
opcional: solo la pide `/sveltekit`). Los tres pasos del flujo, sin cookies ni redirects: los arma la app. Ejemplo completo en la app de
|
|
82
|
+
prueba (`src/routes/api/auth/`).
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
const oidc = createOidcProvider({
|
|
86
|
+
issuer,
|
|
87
|
+
clientId,
|
|
88
|
+
clientSecret,
|
|
89
|
+
callbackPath: '/api/auth/callback',
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// GET /login: guardar pendingLogin (cookie HttpOnly) y redirigir a providerUrl
|
|
93
|
+
const { providerUrl, pendingLogin } = await oidc.buildLoginUrl(requestUrl);
|
|
94
|
+
|
|
95
|
+
// GET /callback: valida state, PKCE y el id_token; lanza OidcError si falla
|
|
96
|
+
const tokens = await oidc.exchangeCode(requestUrl, pendingLogin);
|
|
97
|
+
const user = getUser(tokens);
|
|
98
|
+
|
|
99
|
+
// POST /logout: redirigir al logout del proveedor (undefined si no lo publica)
|
|
100
|
+
const logoutUrl = await oidc.buildLogoutUrl(idToken, 'https://miapp/');
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Helpers: `getUser`, `getDomainUser`, `getPermissions`, `isSameOrigin`, `isNavigation`, `OidcError`
|
|
104
|
+
(con `code`: `PROVIDER_ERROR`, `NO_LOGIN_IN_PROGRESS`, `STATE_MISMATCH`, `TOKEN_EXCHANGE`,
|
|
105
|
+
`INVALID_ID_TOKEN`, `DISCOVERY`, `LOGIN_REJECTED`).
|
|
106
|
+
|
|
107
|
+
El paso a paso del flujo, con los mensajes HTTP, está en la app de prueba: `pnpm dev` y
|
|
108
|
+
`/como-funciona`.
|
|
109
|
+
|
|
110
|
+
## Proveedores probados
|
|
111
|
+
|
|
112
|
+
El flujo se probó en la prueba de concepto (`keycloak-poc`), con la misma app y cambiando solo el
|
|
113
|
+
`.env`. El componente se va a probar contra los mismos proveedores:
|
|
114
|
+
|
|
115
|
+
| Proveedor | Versión | Notas |
|
|
116
|
+
| --------- | ------------------------------------------------------------- | -------------------------------------------------- |
|
|
117
|
+
| Keycloak | 26.8.1 | En Docker (`start-dev`) y en Windows Server 2022 |
|
|
118
|
+
| ADFS | AD FS 2019 (farm behavior level 4), sobre Windows Server 2022 | Client confidencial y público (PKCE), con Kerberos |
|
|
119
|
+
|
|
120
|
+
## Estructura
|
|
121
|
+
|
|
122
|
+
Dos capas:
|
|
123
|
+
|
|
124
|
+
- `src/lib/oidc/`: la capa genérica, para cualquier app Node. Sobre `openid-client`; no importa
|
|
125
|
+
nada de SvelteKit (lo controla ESLint).
|
|
126
|
+
- La capa SvelteKit: los handlers de `/api/auth/login`, `/callback` y `/logout`, y
|
|
127
|
+
`createOidcSvelteKitHandlers` (etapa 2).
|
|
128
|
+
|
|
129
|
+
`src/routes/` es la app de prueba, contra Keycloak en Docker.
|
|
130
|
+
|
|
131
|
+
## Desarrollo
|
|
132
|
+
|
|
133
|
+
Requisitos: las versiones de `mise.toml` (Node, pnpm), Docker y `openssl` (para Keycloak). pnpm lo
|
|
134
|
+
instala corepack según `packageManager` de `package.json`.
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
pnpm install
|
|
138
|
+
cp .env.example .env # trae activo el bloque del Keycloak de Docker
|
|
139
|
+
pnpm keycloak:start
|
|
140
|
+
pnpm dev # la app de prueba, en http://localhost:5173
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Tareas de pnpm
|
|
144
|
+
|
|
145
|
+
Todas las de `package.json`. **Al agregar, cambiar o borrar una, actualizar esta lista.**
|
|
146
|
+
|
|
147
|
+
App de prueba:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
pnpm dev # vite dev; confía en el certificado de Keycloak (NODE_EXTRA_CA_CERTS)
|
|
151
|
+
pnpm build # vite build y después prepack
|
|
152
|
+
pnpm preview # sirve el build en el 4173, el que usan los e2e; mismo certificado que dev
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Calidad:
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
pnpm verify # ESLint con --fix, Prettier y svelte-check: correrlo antes de commitear
|
|
159
|
+
pnpm lint # solo ESLint, sin --fix
|
|
160
|
+
pnpm format # solo Prettier
|
|
161
|
+
pnpm check # solo svelte-check (check:watch, en modo watch)
|
|
162
|
+
pnpm lint:clean # borra las cachés de ESLint y Prettier
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Tests. `pnpm test` usa el Keycloak de dev ya levantado (`pnpm keycloak:start`), como una base de
|
|
166
|
+
fixture; `pnpm test:ci` levanta uno propio y lo borra al terminar:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
pnpm test # test:vite y test:play
|
|
170
|
+
pnpm test:unit # Vitest, solo los unitarios
|
|
171
|
+
pnpm test:vite # Vitest, todos los proyectos
|
|
172
|
+
pnpm test:e2e # Playwright, solo los e2e
|
|
173
|
+
pnpm test:play # Playwright, todos los proyectos
|
|
174
|
+
pnpm test:ci # como en GitLab: Keycloak desechable (puerto 3112), test:vite y test:play
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Keycloak en Docker (`docker/keycloak/`, `https://localhost:3102`, realm `oidc-test`, admin
|
|
178
|
+
`admin`/`admin`):
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
pnpm keycloak:start # keycloak:cert y levanta el contenedor; importa el realm si no existe
|
|
182
|
+
pnpm keycloak:stop # lo frena, sin perder los datos
|
|
183
|
+
pnpm keycloak:status # estado y puertos del contenedor
|
|
184
|
+
pnpm keycloak:logs # los logs, en vivo
|
|
185
|
+
pnpm keycloak:purge # borra el contenedor y sus datos: el próximo start reimporta el realm
|
|
186
|
+
pnpm keycloak:cert # genera el certificado autofirmado, si no existe o vence en 30 días
|
|
187
|
+
pnpm keycloak:init # espera e importa el realm por la API de admin (el de CI; KEYCLOAK_URL)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Paquete y dependencias:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
pnpm prepack # arma dist/ y lo valida con publint
|
|
194
|
+
pnpm up:safe # dentro de los rangos, con 24 h de antigüedad mínima
|
|
195
|
+
pnpm sv:sync-deps # compara las mayores con las que trae hoy el scaffold de SvelteKit (sv)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
VM de ADFS (`keycloak-poc`: `docs/adfs-paso-a-paso.md`):
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
pnpm vm:pack # build de adapter-node con node_modules → build-vm/oidc-app.zip (.env.vm.example)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Runner de GitLab local (con `sudo`):
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
pnpm gitlab-runner:start
|
|
208
|
+
pnpm gitlab-runner:stop
|
|
209
|
+
pnpm gitlab-runner:status
|
|
210
|
+
pnpm gitlab-runner:logs # los logs del servicio, en vivo
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
`prepare` (`svelte-kit sync`) no se corre a mano: lo corre `pnpm install`.
|
|
214
|
+
|
|
215
|
+
## Licencia
|
|
216
|
+
|
|
217
|
+
[LGPL-3.0-or-later](COPYING.LESSER) (con el texto de la GPL-3.0 en [`COPYING`](COPYING)). Una app
|
|
218
|
+
puede usar el paquete sin cambiar su licencia; los cambios al paquete se publican con la misma.
|
|
219
|
+
|
|
220
|
+
## Versiones y commits
|
|
221
|
+
|
|
222
|
+
SemVer. Commits y títulos de merge request en Conventional Commits, en español. `main` protegida:
|
|
223
|
+
todo entra por merge request, con squash.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export * from './oidc/domain-user.ts';
|
|
2
|
+
export * from './oidc/errors.ts';
|
|
3
|
+
export { isNavigation, isSameOrigin } from './oidc/request.ts';
|
|
4
|
+
export * from './oidc/permissions.ts';
|
|
5
|
+
export * from './oidc/provider.ts';
|
|
6
|
+
export type { Claims } from './oidc/types.ts';
|
|
7
|
+
export * from './oidc/user.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// La API pública, para cualquier app Node: el provider (buildLoginUrl, exchangeCode,
|
|
2
|
+
// buildLogoutUrl) y helpers; las cookies, la sesión y los redirects los arma la app. La capa
|
|
3
|
+
// SvelteKit (createOidcSvelteKitHandlers) va aparte, en '<paquete>/sveltekit': así este punto de
|
|
4
|
+
// entrada no importa @sveltejs/kit.
|
|
5
|
+
export * from "./oidc/domain-user.js";
|
|
6
|
+
export * from "./oidc/errors.js";
|
|
7
|
+
export { isNavigation, isSameOrigin } from "./oidc/request.js";
|
|
8
|
+
export * from "./oidc/permissions.js";
|
|
9
|
+
export * from "./oidc/provider.js";
|
|
10
|
+
export * from "./oidc/user.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Claims } from './types.ts';
|
|
2
|
+
export declare const DOMAIN_USER_CLAIMS: readonly ["unique_name", "upn", "preferred_username", "email"];
|
|
3
|
+
export declare const DOMAIN_CLAIM = "dominio";
|
|
4
|
+
export type DomainUserOptions = {
|
|
5
|
+
defaultDomain?: string;
|
|
6
|
+
};
|
|
7
|
+
export declare function getDomainUser(idTokenClaims: Claims, accessTokenClaims: Claims | undefined, options?: DomainUserOptions): string | undefined;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Dónde manda cada proveedor el usuario de red, en orden: gana el primero con contenido. ADFS (sin
|
|
2
|
+
// reglas de claims): unique_name ('ORGANIZACION\user1') y upn; Keycloak: preferred_username (con
|
|
3
|
+
// LDAP, el userPrincipalName del AD). Verificado en la POC (keycloak-poc).
|
|
4
|
+
export const DOMAIN_USER_CLAIMS = ['unique_name', 'upn', 'preferred_username', 'email'];
|
|
5
|
+
// Mapper del client en Keycloak: el dominio de Windows del usuario. Solo en el access token.
|
|
6
|
+
export const DOMAIN_CLAIM = 'dominio';
|
|
7
|
+
const DOMAIN_SEPARATOR = '\\';
|
|
8
|
+
const UPN_SEPARATOR = '@';
|
|
9
|
+
// El usuario de red, 'DOMINIO\usuario', o undefined si ningún claim lo trae. Por cada claim de
|
|
10
|
+
// DOMAIN_USER_CLAIMS mira primero el id_token (validado) y después el access token. Si el valor ya
|
|
11
|
+
// trae el dominio queda tal cual; si es 'usuario@dominio.algo' (o solo 'usuario'), arma
|
|
12
|
+
// '<dominio>\usuario' con el claim dominio o, si no está, con defaultDomain (sin él, undefined).
|
|
13
|
+
export function getDomainUser(idTokenClaims, accessTokenClaims, options = {}) {
|
|
14
|
+
const value = DOMAIN_USER_CLAIMS.flatMap((claim) => [
|
|
15
|
+
stringClaim(idTokenClaims, claim),
|
|
16
|
+
stringClaim(accessTokenClaims, claim),
|
|
17
|
+
]).find(Boolean);
|
|
18
|
+
if (!value)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (value.includes(DOMAIN_SEPARATOR))
|
|
21
|
+
return value;
|
|
22
|
+
const [user] = value.split(UPN_SEPARATOR);
|
|
23
|
+
if (!user)
|
|
24
|
+
return undefined;
|
|
25
|
+
const domain = stringClaim(accessTokenClaims, DOMAIN_CLAIM) ??
|
|
26
|
+
stringClaim(idTokenClaims, DOMAIN_CLAIM) ??
|
|
27
|
+
options.defaultDomain;
|
|
28
|
+
if (!domain)
|
|
29
|
+
return undefined;
|
|
30
|
+
return `${domain}${DOMAIN_SEPARATOR}${user}`;
|
|
31
|
+
}
|
|
32
|
+
function stringClaim(claims, name) {
|
|
33
|
+
const value = claims?.[name];
|
|
34
|
+
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
35
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const OIDC_ERROR_CODES: readonly ["PROVIDER_ERROR", "NO_LOGIN_IN_PROGRESS", "STATE_MISMATCH", "TOKEN_EXCHANGE", "INVALID_ID_TOKEN", "DISCOVERY", "LOGIN_REJECTED"];
|
|
2
|
+
export type OidcErrorCode = (typeof OIDC_ERROR_CODES)[number];
|
|
3
|
+
export type ProviderErrorDetails = {
|
|
4
|
+
providerError?: string;
|
|
5
|
+
providerErrorDescription?: string;
|
|
6
|
+
};
|
|
7
|
+
export declare class OidcError extends Error {
|
|
8
|
+
readonly code: OidcErrorCode;
|
|
9
|
+
readonly providerError?: string;
|
|
10
|
+
readonly providerErrorDescription?: string;
|
|
11
|
+
constructor(code: OidcErrorCode, message: string, details?: ProviderErrorDetails & {
|
|
12
|
+
cause?: unknown;
|
|
13
|
+
});
|
|
14
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const OIDC_ERROR_CODES = [
|
|
2
|
+
// El proveedor volvió con ?error= (el usuario canceló, client mal configurado)
|
|
3
|
+
'PROVIDER_ERROR',
|
|
4
|
+
// Sin <prefix>_login: vencida, o el callback abierto a mano
|
|
5
|
+
'NO_LOGIN_IN_PROGRESS',
|
|
6
|
+
'STATE_MISMATCH',
|
|
7
|
+
// Falló el canje del code
|
|
8
|
+
'TOKEN_EXCHANGE',
|
|
9
|
+
// Firma, iss, aud, exp o nonce del id_token
|
|
10
|
+
'INVALID_ID_TOKEN',
|
|
11
|
+
// El proveedor no responde
|
|
12
|
+
'DISCOVERY',
|
|
13
|
+
// El login salió bien, pero la app no lo aceptó (por ejemplo, sin usuario de red)
|
|
14
|
+
'LOGIN_REJECTED',
|
|
15
|
+
];
|
|
16
|
+
export class OidcError extends Error {
|
|
17
|
+
code;
|
|
18
|
+
providerError;
|
|
19
|
+
providerErrorDescription;
|
|
20
|
+
constructor(code, message, details = {}) {
|
|
21
|
+
super(message, { cause: details.cause });
|
|
22
|
+
this.name = 'OidcError';
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.providerError = details.providerError;
|
|
25
|
+
this.providerErrorDescription = details.providerErrorDescription;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const ROLE_SEPARATOR = ':';
|
|
2
|
+
// Los roles del client en Keycloak ('Recurso:accion', en resource_access.<clientId>.roles, la unión
|
|
3
|
+
// de los de todos los grupos del usuario) como permisos. Solo vienen en el access token. Los roles
|
|
4
|
+
// que no tienen la forma 'Recurso:accion' se ignoran. Sin roles (ADFS sin reglas), {}.
|
|
5
|
+
//
|
|
6
|
+
// ['Provincia:alta', 'Provincia:consulta', 'Dato:consulta']
|
|
7
|
+
// → { Dato: ['consulta'], Provincia: ['alta', 'consulta'] }
|
|
8
|
+
export function getPermissions(accessTokenClaims, clientId) {
|
|
9
|
+
const permissions = {};
|
|
10
|
+
for (const role of clientRoles(accessTokenClaims, clientId)) {
|
|
11
|
+
const [resource, action, ...rest] = role.split(ROLE_SEPARATOR);
|
|
12
|
+
if (!resource || !action || rest.length > 0)
|
|
13
|
+
continue;
|
|
14
|
+
(permissions[resource] ??= new Set()).add(action);
|
|
15
|
+
}
|
|
16
|
+
// El orden de los roles en el token no es estable: recursos y acciones ordenados
|
|
17
|
+
return Object.fromEntries(Object.keys(permissions)
|
|
18
|
+
.toSorted()
|
|
19
|
+
.map((resource) => [resource, [...permissions[resource]].toSorted()]));
|
|
20
|
+
}
|
|
21
|
+
function clientRoles(claims, clientId) {
|
|
22
|
+
const resourceAccess = claims?.resource_access;
|
|
23
|
+
if (!isRecord(resourceAccess))
|
|
24
|
+
return [];
|
|
25
|
+
const client = resourceAccess[clientId];
|
|
26
|
+
if (!isRecord(client) || !Array.isArray(client.roles))
|
|
27
|
+
return [];
|
|
28
|
+
return client.roles.filter((role) => typeof role === 'string');
|
|
29
|
+
}
|
|
30
|
+
function isRecord(value) {
|
|
31
|
+
return typeof value === 'object' && value !== null;
|
|
32
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Claims } from './types.ts';
|
|
2
|
+
export declare const DEFAULT_SCOPE = "openid profile email";
|
|
3
|
+
export declare const RETURN_TO_PARAM = "returnTo";
|
|
4
|
+
export type OidcProviderOptions = {
|
|
5
|
+
issuer: string;
|
|
6
|
+
clientId: string;
|
|
7
|
+
clientSecret?: string;
|
|
8
|
+
callbackPath: string;
|
|
9
|
+
scope?: string;
|
|
10
|
+
allowInsecureRequests?: boolean;
|
|
11
|
+
};
|
|
12
|
+
export type PendingLogin = {
|
|
13
|
+
codeVerifier: string;
|
|
14
|
+
state: string;
|
|
15
|
+
nonce: string;
|
|
16
|
+
returnTo: string;
|
|
17
|
+
};
|
|
18
|
+
export type Tokens = {
|
|
19
|
+
idToken: string;
|
|
20
|
+
accessToken: string;
|
|
21
|
+
refreshToken?: string;
|
|
22
|
+
idTokenClaims: Claims;
|
|
23
|
+
accessTokenClaims?: Claims;
|
|
24
|
+
};
|
|
25
|
+
export type OidcProvider = {
|
|
26
|
+
buildLoginUrl(loginUrl: URL): Promise<{
|
|
27
|
+
providerUrl: URL;
|
|
28
|
+
pendingLogin: PendingLogin;
|
|
29
|
+
}>;
|
|
30
|
+
exchangeCode(callbackUrl: URL, pendingLogin: PendingLogin | undefined): Promise<Tokens>;
|
|
31
|
+
buildLogoutUrl(idToken: string | undefined, postLogoutRedirectUri: string): Promise<URL | undefined>;
|
|
32
|
+
};
|
|
33
|
+
export declare function createOidcProvider(options: OidcProviderOptions): OidcProvider;
|