@dacyti-gsi/auth 0.0.0-stage → 0.2.0
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/LICENSE +202 -0
- package/README.md +419 -3
- package/package.json +71 -4
- package/src/config.ts +212 -0
- package/src/core.ts +451 -0
- package/src/errors.ts +53 -0
- package/src/index.ts +673 -0
- package/src/next.ts +296 -0
- package/src/pkce.ts +48 -0
- package/src/policy.ts +102 -0
- package/src/react.tsx +171 -0
- package/src/session-cookie.ts +86 -0
- package/src/types.ts +143 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Carlos Burelo
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,419 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @dacyti-gsi/auth
|
|
2
|
+
|
|
3
|
+
Cliente del Portal SSO. Autenticación OIDC y permisos con la mínima ceremonia.
|
|
4
|
+
|
|
5
|
+
> **Es el cliente de servidor.** Mantiene el `client_secret` y guarda la sesión
|
|
6
|
+
> en una cookie `HttpOnly`, así que necesita un backend: Next.js, un BFF, un
|
|
7
|
+
> servicio Node. **Un frontend en el navegador no debe usarlo** —no puede
|
|
8
|
+
> guardar un secreto ni una cookie—: se registra en el portal como cliente
|
|
9
|
+
> público (`spa` o `native`, solo PKCE, sin secreto) y usa una librería OIDC
|
|
10
|
+
> estándar contra `https://sso.<tu-dominio>/api/auth`.
|
|
11
|
+
|
|
12
|
+
## Instalar
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @dacyti-gsi/auth
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Integrar una aplicación Next.js
|
|
19
|
+
|
|
20
|
+
**1. Declara el cliente**
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// lib/sso.ts
|
|
24
|
+
import { defineNextSSO } from "@dacyti-gsi/auth/next";
|
|
25
|
+
|
|
26
|
+
export const sso = defineNextSSO({
|
|
27
|
+
// Convierte una errata en un error de compilación
|
|
28
|
+
permissions: ["documentos:crear", "documentos:anular"],
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Nada más: `issuer`, `clientId`, `clientSecret` y `secret` salen de
|
|
33
|
+
`SSO_ISSUER`, `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` y `SSO_SECRET`. Si falta
|
|
34
|
+
alguna, revienta al arrancar diciendo cuál.
|
|
35
|
+
|
|
36
|
+
**2. Monta las rutas**
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// app/api/sso/[...sso]/route.ts
|
|
40
|
+
import { sso } from "@/lib/sso";
|
|
41
|
+
|
|
42
|
+
export const { GET, POST } = sso.handlers();
|
|
43
|
+
export const runtime = "nodejs";
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**3. Úsalo**
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
// app/panel/page.tsx
|
|
50
|
+
import { sso } from "@/lib/sso";
|
|
51
|
+
|
|
52
|
+
export default async function PanelPage() {
|
|
53
|
+
const session = await sso.protectPage();
|
|
54
|
+
|
|
55
|
+
return <p>Hola, {session.user.name}</p>;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Eso es todo. No hay que escribir PKCE, ni manejar el `state`, ni canjear
|
|
60
|
+
códigos, ni saber que los claims van bajo un espacio de nombres.
|
|
61
|
+
|
|
62
|
+
## Variables de entorno
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
SSO_ISSUER=https://sso.ejemplo.com/api/auth
|
|
66
|
+
SSO_CLIENT_ID=…
|
|
67
|
+
SSO_CLIENT_SECRET=…
|
|
68
|
+
|
|
69
|
+
# Cifra la cookie de sesión. Mínimo 32 caracteres.
|
|
70
|
+
# node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
|
|
71
|
+
SSO_SECRET=…
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Al registrar la aplicación en el portal indica esta URI de redirección:
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
https://tuapp.com/api/sso/callback
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Y, si quieres que cerrar sesión devuelva al usuario aquí, añade también una URI
|
|
81
|
+
de cierre de sesión:
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
https://tuapp.com/
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
El portal solo redirige a URIs registradas, así que sin ella la sesión se cierra
|
|
88
|
+
igual pero el navegador se queda en el portal. Si la registras, indícala también
|
|
89
|
+
en `postLogoutRedirectUri`.
|
|
90
|
+
|
|
91
|
+
## Renovar el acceso (`proxy.ts`)
|
|
92
|
+
|
|
93
|
+
El acceso dura 15 minutos. Los Server Components no pueden escribir cookies, así que
|
|
94
|
+
sin ayuda cada página renderizada después vuelve a canjear tokens con el portal. Monta
|
|
95
|
+
el proxy una vez por app y la cookie renovada viaja en la respuesta:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
// src/proxy.ts
|
|
99
|
+
import { sso } from "@/lib/sso";
|
|
100
|
+
|
|
101
|
+
export const proxy = sso.proxy;
|
|
102
|
+
export const config = {
|
|
103
|
+
matcher: ["/((?!_next/|api/sso/|favicon.ico|.*\..*).*)"],
|
|
104
|
+
};
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Si el portal no responde, no hace nada y la página decide con lo que tenga.
|
|
108
|
+
|
|
109
|
+
## Robustez
|
|
110
|
+
|
|
111
|
+
- Toda llamada al portal tiene tope de 10 s: un portal colgado no congela la app.
|
|
112
|
+
- Las rutas `/api/sso/*` responden 503/502 genéricos (el detalle va al log del servidor).
|
|
113
|
+
- Renovaciones simultáneas del mismo refresh token se unifican en una sola llamada.
|
|
114
|
+
- Cada intento de ingreso tiene su cookie (`sso_attempt_<state>`): varias pestañas no se pisan.
|
|
115
|
+
- Si la sesión no cabe en una cookie (~4 KB) falla con un mensaje claro en vez de un bucle de login.
|
|
116
|
+
- `protectPage({ access: true })` deja fuera a quien se autenticó pero no tiene ningún permiso de la app.
|
|
117
|
+
|
|
118
|
+
## Proteger
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
// Solo exige sesión
|
|
122
|
+
const session = await sso.protectPage();
|
|
123
|
+
|
|
124
|
+
// Declarativo: permiso + segundo factor + permisos vivos
|
|
125
|
+
const session = await sso.protectPage({
|
|
126
|
+
permission: "documentos:anular",
|
|
127
|
+
requireMfa: true,
|
|
128
|
+
revalidate: true,
|
|
129
|
+
});
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Sin sesión, `protectPage()` **redirige** a autenticarse. Con sesión pero sin el
|
|
133
|
+
permiso, **lanza `SSOForbiddenError`**. Sin segundo factor cuando se exige,
|
|
134
|
+
**lanza `SSOMfaRequiredError`**. Son tres situaciones distintas.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// app/panel/error.tsx o un try/catch
|
|
138
|
+
import { SSOForbiddenError } from "@dacyti-gsi/auth/next";
|
|
139
|
+
|
|
140
|
+
if (error instanceof SSOForbiddenError) {
|
|
141
|
+
// responde 403, no 500
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Server Actions declarativas
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// app/panel/actions.ts
|
|
149
|
+
export const anularPedido = sso.action("documentos:anular", async (session, id: string) => {
|
|
150
|
+
// sesión ya autorizada con permisos vivos (revalidate por defecto)
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`action()` revalida por defecto: las escrituras consultan al portal en el
|
|
155
|
+
momento. Solo lectura barata usa `{ revalidate: false }`.
|
|
156
|
+
|
|
157
|
+
Sin sesión, sin permiso o sin segundo factor, lanza por defecto —lo correcto
|
|
158
|
+
para páginas y rutas. Para formularios con `useActionState`, `onDenied`
|
|
159
|
+
convierte la denegación en valor. Un fallo del portal nunca se convierte:
|
|
160
|
+
una caída no es una denegación.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
export const anular = sso.action("documentos:anular", run, {
|
|
164
|
+
onDenied: (error) => ({ ok: false as const, message: "Sin permiso." }),
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Componentes RSC
|
|
169
|
+
|
|
170
|
+
Salen del cliente, ya atados a él y con el catálogo de permisos tipado:
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
// lib/sso.ts
|
|
174
|
+
export const sso = defineNextSSO({ permissions: ["documentos:ver", "documentos:anular"] });
|
|
175
|
+
export const { Can, SignedIn, SignedOut, SignInLink, SignOutLink } = sso.components;
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
<SignedOut>
|
|
180
|
+
<SignInLink returnTo="/panel">Entrar</SignInLink>
|
|
181
|
+
</SignedOut>
|
|
182
|
+
|
|
183
|
+
<SignedIn>
|
|
184
|
+
<SignOutLink>Salir</SignOutLink>
|
|
185
|
+
</SignedIn>
|
|
186
|
+
|
|
187
|
+
<Can permission="documentos:anular" fallback={<p>Sin acceso.</p>}>
|
|
188
|
+
<BotonAnular />
|
|
189
|
+
</Can>
|
|
190
|
+
|
|
191
|
+
<Can permission={["documentos:ver", "documentos:anular"]} mode="all" requireMfa>
|
|
192
|
+
<Auditoria />
|
|
193
|
+
</Can>
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
- `Can` (alias `Protect`): niega por defecto —sin permiso pintan `fallback` o
|
|
197
|
+
nada. Nunca redirigen ni lanzan. Para páginas completas usa `protectPage()`,
|
|
198
|
+
que redirige a entrar.
|
|
199
|
+
- `SignedIn` / `SignedOut`: según haya sesión o no.
|
|
200
|
+
- `SignInLink` / `SignOutLink`: enlaces de entrada (con vuelta) y salida
|
|
201
|
+
(local y portal). Son Server Components sin JS: solo un `<a>` bien armado.
|
|
202
|
+
|
|
203
|
+
Las versiones sueltas de `@dacyti-gsi/auth/react` (`<Can sso={sso} …>`) siguen
|
|
204
|
+
existiendo, pero lo normal es usar las atadas.
|
|
205
|
+
|
|
206
|
+
## Configuración fail-fast
|
|
207
|
+
|
|
208
|
+
El cliente valida al crearse: `issuer` https (http solo localhost), `secret` de
|
|
209
|
+
32+, catálogo sin vacíos ni duplicados, `basePath` con `/` inicial. Un
|
|
210
|
+
error de configuración revienta al arrancar, no en el primer login.
|
|
211
|
+
|
|
212
|
+
La cookie es `__Host-sso_session` por defecto (`Secure`, `HttpOnly`,
|
|
213
|
+
`SameSite=Lax`, `Path=/`). Rompe sesiones previas una vez: salida y entrada.
|
|
214
|
+
|
|
215
|
+
## Leer sin exigir
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
const session = await sso.session(); // SSOSession | null
|
|
219
|
+
|
|
220
|
+
if (session?.can("documentos:anular")) {
|
|
221
|
+
// …
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
## Que un cambio de rol surta efecto ya
|
|
226
|
+
|
|
227
|
+
`session()` lee la cookie: es un descifrado local, sin red, y por eso los
|
|
228
|
+
permisos son la foto del momento en que se autorizó la aplicación. Si un
|
|
229
|
+
administrador retira un rol, esa foto sigue diciendo lo mismo hasta que
|
|
230
|
+
caduque.
|
|
231
|
+
|
|
232
|
+
Para las operaciones donde eso no vale, pide permisos vivos:
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
// Una ida y vuelta al portal. Renueva el access token si caducó y vuelve a
|
|
236
|
+
// resolver los permisos.
|
|
237
|
+
const session = await sso.protectPage({ permission: "documentos:anular", revalidate: true });
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`revalidate` cuesta una llamada, así que no es el valor por defecto. Ponlo en
|
|
241
|
+
las pantallas y acciones que dependen de un permiso concreto —anular, pagar,
|
|
242
|
+
borrar— y deja el resto en el camino rápido. `action()` ya revalida por
|
|
243
|
+
defecto.
|
|
244
|
+
|
|
245
|
+
Además, si el portal responde que la credencial ya no vale —token revocado,
|
|
246
|
+
cliente desactivado, cuenta bloqueada— la sesión se da por terminada y
|
|
247
|
+
`protectPage()` vuelve a mandar a autenticarse. Un fallo de red o un 502 del
|
|
248
|
+
portal, en cambio, cae a la foto local: no son motivo para echar a nadie.
|
|
249
|
+
|
|
250
|
+
**Lo que `revalidate` no hace:** cerrar la sesión *en el portal* no apaga la
|
|
251
|
+
sesión local de tu aplicación. Son sesiones distintas y no hay cierre de sesión
|
|
252
|
+
en segundo plano; la copia local vive hasta `sessionMaxAge`. Si eso importa,
|
|
253
|
+
revalida en las operaciones sensibles o baja `sessionMaxAge`.
|
|
254
|
+
|
|
255
|
+
## Renovar el acceso
|
|
256
|
+
|
|
257
|
+
El `access_token` dura quince minutos. Pasados, cualquier llamada a una API con
|
|
258
|
+
`session.accessToken` responde 401 aunque la cookie siga viva.
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
if (session.isExpired()) {
|
|
262
|
+
// Renueva desde una Server Action declarada, o navega a la ruta del SDK:
|
|
263
|
+
const renovar = sso.action({}, async () => {});
|
|
264
|
+
// o un enlace a sso.refreshPath("/panel")
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
- **`sso.action()`** revalida y persiste la cookie nueva. Es el camino para
|
|
269
|
+
Server Actions y mutaciones.
|
|
270
|
+
- **`refreshPath(returnTo)`** apunta a la ruta del SDK que renueva, guarda la
|
|
271
|
+
cookie y devuelve al usuario. Sirve desde cualquier sitio, incluido un enlace.
|
|
272
|
+
- **`resolveSession(cookie)`** es la versión de bajo nivel, para otros
|
|
273
|
+
frameworks: devuelve `{ session, cookie }` y decide tú dónde guardarla.
|
|
274
|
+
|
|
275
|
+
Todo esto solo funciona si la autorización pidió el scope `offline_access`, que
|
|
276
|
+
el SDK incluye por defecto. La aplicación tiene que tenerlo permitido en el
|
|
277
|
+
portal: si no, el canje del código responde `invalid_scope`.
|
|
278
|
+
|
|
279
|
+
## La sesión
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
session.user.id // identificador estable — úsalo como clave
|
|
283
|
+
session.user.email
|
|
284
|
+
session.user.emailVerified
|
|
285
|
+
session.user.name
|
|
286
|
+
|
|
287
|
+
session.roles // ["gerente"]
|
|
288
|
+
session.permissions // ["documentos:anular", "documentos:crear"]
|
|
289
|
+
session.amr // ["pwd", "otp", "mfa"]
|
|
290
|
+
|
|
291
|
+
session.can("documentos:anular")
|
|
292
|
+
session.canAll("documentos:crear", "documentos:anular")
|
|
293
|
+
session.canAny("documentos:crear", "informes:ver")
|
|
294
|
+
session.requires("documentos:anular") // lanza SSOForbiddenError
|
|
295
|
+
|
|
296
|
+
session.usedSecondFactor() // true si amr incluye "mfa"
|
|
297
|
+
session.isExpired() // true si el access token ya caducó
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## Permisos tipados
|
|
301
|
+
|
|
302
|
+
El portal define los permisos y tu aplicación les da significado al exigirlos.
|
|
303
|
+
Esta lista es el espejo para TypeScript —declara primero en la consola del
|
|
304
|
+
portal— y con ella los nombres se comprueban al compilar:
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
export const sso = defineNextSSO({
|
|
308
|
+
// …
|
|
309
|
+
permissions: ["documentos:crear", "documentos:anular"],
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
session.can("documentos:crear"); // ✔
|
|
313
|
+
session.can("documentos:crea"); // ✘ error de compilación
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
Sin esa lista todo sigue funcionando, pero una errata devuelve `false` en
|
|
317
|
+
silencio en producción en lugar de fallar al compilar. El SDK nunca valida la
|
|
318
|
+
forma de un permiso: el portal acepta cualquier cadena opaca y lo que no está
|
|
319
|
+
declarado ahí, simplemente nunca llega en la sesión.
|
|
320
|
+
|
|
321
|
+
## Exigir segundo factor
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
const session = await sso.protectPage({ permission: "documentos:anular", requireMfa: true });
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
## Enlaces
|
|
328
|
+
|
|
329
|
+
```tsx
|
|
330
|
+
<a href={sso.signInPath("/panel")}>Entrar</a>
|
|
331
|
+
<a href={sso.signOutPath()}>Salir</a>
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
`signOutPath()` cierra la sesión local **y** la del portal. Cerrar solo la local
|
|
335
|
+
dejaría a la persona dentro del portal, y el siguiente `signIn` la devolvería sin
|
|
336
|
+
pedir nada.
|
|
337
|
+
|
|
338
|
+
Cerrar la sesión del portal exige que la aplicación esté registrada con
|
|
339
|
+
`enable_end_session` y con al menos una URI de cierre de sesión. Ambas cosas las
|
|
340
|
+
pone el portal al registrar la aplicación desde la consola.
|
|
341
|
+
|
|
342
|
+
## Fuera de Next.js
|
|
343
|
+
|
|
344
|
+
El núcleo no depende de ningún framework:
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
import { defineSSO } from "@dacyti-gsi/auth";
|
|
348
|
+
|
|
349
|
+
const sso = defineSSO({ issuer, clientId, clientSecret, secret });
|
|
350
|
+
|
|
351
|
+
// En tu router, para cualquier ruta bajo /api/sso/
|
|
352
|
+
const response = await sso.handleRequest(request); // Response | null
|
|
353
|
+
|
|
354
|
+
// Con el valor de la cookie
|
|
355
|
+
const session = await sso.readSession(cookieValue);
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
`handleRequest` devuelve `null` si la ruta no le compete, para que puedas
|
|
359
|
+
encadenarlo con el resto de tu enrutado. Las rutas que atiende son `sign-in`,
|
|
360
|
+
`callback`, `sign-out` y `refresh`.
|
|
361
|
+
|
|
362
|
+
`resolveSession` es la que habla con el portal: renueva el acceso caducado,
|
|
363
|
+
vuelve a resolver los permisos si le pasas `revalidate` y te devuelve la cookie
|
|
364
|
+
nueva para que la guardes donde guardes la tuya.
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
const resolved = await sso.resolveSession(cookie, { revalidate: true });
|
|
368
|
+
// resolved === null → la sesión terminó
|
|
369
|
+
// resolved.cookie → guárdala; `null` si nada cambió
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
## Opciones
|
|
373
|
+
|
|
374
|
+
| Opción | Por defecto | |
|
|
375
|
+
|---|---|---|
|
|
376
|
+
| `issuer` | — | **Obligatoria** |
|
|
377
|
+
| `clientId` | — | **Obligatoria** |
|
|
378
|
+
| `clientSecret` | — | **Obligatoria** |
|
|
379
|
+
| `secret` | — | **Obligatoria.** Mínimo 32 caracteres |
|
|
380
|
+
| `permissions` | — | Espejo del catálogo del portal, solo para tipado |
|
|
381
|
+
| `basePath` | `/api/sso` | Dónde montas los handlers |
|
|
382
|
+
| `appUrl` | se deduce | Indícala si el proxy no reescribe `X-Forwarded-Host` |
|
|
383
|
+
| `postLogoutRedirectUri` | — | A dónde vuelve el navegador tras cerrar sesión. Debe estar registrada en el portal |
|
|
384
|
+
| `scopes` | `openid profile email offline_access` | |
|
|
385
|
+
| `cookieName` | `__Host-sso_session` | |
|
|
386
|
+
| `sessionMaxAge` | 7 días | Sesión local, en segundos |
|
|
387
|
+
|
|
388
|
+
## Qué hace por dentro
|
|
389
|
+
|
|
390
|
+
- **PKCE `S256` obligatorio.** Verifier de 48 bytes, challenge SHA-256.
|
|
391
|
+
- **`state` comprobado en tiempo constante.** Sin esa comprobación, un tercero
|
|
392
|
+
puede forzar a alguien a completar un flujo que empezó él, y acabar con la
|
|
393
|
+
sesión del atacante iniciada en el navegador de la víctima.
|
|
394
|
+
- **Cookie de sesión cifrada** (AES-256-GCM), no solo firmada: contiene el access
|
|
395
|
+
token, y una cookie firmada es legible por cualquiera que la tenga delante.
|
|
396
|
+
- **El destino tras entrar solo puede ser una ruta de tu aplicación.** Se
|
|
397
|
+
rechazan las URLs absolutas, las relativas al protocolo y las barras
|
|
398
|
+
invertidas.
|
|
399
|
+
- **Los claims se localizan por sufijo**, así que no hay que configurar el
|
|
400
|
+
dominio del portal ni actualizarlo si se mueve.
|
|
401
|
+
- **La cookie temporal del intento se borra al usarla.**
|
|
402
|
+
- **El `id_token` se guarda** porque el cierre de sesión del portal lo exige.
|
|
403
|
+
- **El access token se renueva solo** cuando se pide con `revalidate`.
|
|
404
|
+
|
|
405
|
+
## Limitación conocida
|
|
406
|
+
|
|
407
|
+
Los permisos llegan en `/oauth2/userinfo`, no en el token. El SDK los pide en el
|
|
408
|
+
callback y los guarda en la sesión local.
|
|
409
|
+
|
|
410
|
+
**Consecuencia:** por defecto, un cambio de rol no se ve hasta que la sesión
|
|
411
|
+
local se renueve —hasta `sessionMaxAge`—. Para las operaciones que dependen de un
|
|
412
|
+
permiso concreto, usa `protect(permiso, { revalidate: true })`, que consulta al
|
|
413
|
+
portal en ese momento.
|
|
414
|
+
|
|
415
|
+
## Licencia
|
|
416
|
+
|
|
417
|
+
Apache-2.0. El código fuente del cliente vive en
|
|
418
|
+
[dacyti-gsi/auth](https://github.com/dacyti-gsi/auth) y el del portal en
|
|
419
|
+
[dacyti-gsi/sso](https://github.com/dacyti-gsi/sso).
|