@rsanjur-dev/id 0.0.0-stage → 1.1.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/dist/core.js ADDED
@@ -0,0 +1,585 @@
1
+ /**
2
+ * @rsanjur-dev/id/core
3
+ * Zero-dependency Web Standard client for RS ID (https://id.rsanjur.com).
4
+ * Compatible with Cloudflare Workers, Hono, Astro, Next.js, SvelteKit, Bun, and Node.
5
+ */
6
+ export const RSID_DEFAULT_ORIGIN = "https://id.rsanjur.com";
7
+ const CLIENT_ID_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/u;
8
+ const STATE_RE = /^[A-Za-z0-9_-]{43,128}$/u;
9
+ const VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/u;
10
+ const CODE_RE = /^[A-Za-z0-9_-]{32,128}$/u;
11
+ const MAX_COOKIE_VALUE_LEN = 4096;
12
+ const MAX_RESPONSE_BYTES = 32_768;
13
+ export class RsidExchangeError extends Error {
14
+ kind;
15
+ status;
16
+ constructor(kind, message, status) {
17
+ super(message || `RS ID exchange failed (${kind})`);
18
+ this.name = "RsidExchangeError";
19
+ this.kind = kind;
20
+ this.status = status;
21
+ }
22
+ }
23
+ export class RsidAccessError extends Error {
24
+ kind;
25
+ status;
26
+ constructor(kind, message, status) {
27
+ super(message || `RS ID access check failed (${kind})`);
28
+ this.name = "RsidAccessError";
29
+ this.kind = kind;
30
+ this.status = status;
31
+ }
32
+ }
33
+ const encoder = new TextEncoder();
34
+ const decoder = new TextDecoder();
35
+ export function toBase64Url(bytes) {
36
+ let binary = "";
37
+ for (let i = 0; i < bytes.length; i++) {
38
+ binary += String.fromCharCode(bytes[i]);
39
+ }
40
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
41
+ }
42
+ export function fromBase64Url(input) {
43
+ if (typeof input !== "string" || !/^[A-Za-z0-9_-]+$/.test(input))
44
+ return null;
45
+ try {
46
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
47
+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
48
+ const binary = atob(padded);
49
+ const out = new Uint8Array(binary.length);
50
+ for (let i = 0; i < binary.length; i++)
51
+ out[i] = binary.charCodeAt(i);
52
+ return out;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ export function constantTimeEqual(a, b) {
59
+ if (typeof a !== "string" || typeof b !== "string")
60
+ return false;
61
+ let diff = a.length ^ b.length;
62
+ const max = Math.max(a.length, b.length);
63
+ for (let i = 0; i < max; i++) {
64
+ diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
65
+ }
66
+ return diff === 0;
67
+ }
68
+ export function normalizeRsidOrigin(origin) {
69
+ const url = new URL(origin || RSID_DEFAULT_ORIGIN);
70
+ const isLocal = url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");
71
+ if ((url.protocol !== "https:" && !isLocal) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
72
+ throw new TypeError("baseUrl de RS ID debe ser un origen HTTPS válido (o localhost en pruebas)");
73
+ }
74
+ return url.origin;
75
+ }
76
+ export function attemptCookieName(clientId) {
77
+ if (!CLIENT_ID_RE.test(clientId))
78
+ throw new TypeError("clientId inválido para RS ID");
79
+ return `__Host-rsid-sso-${clientId}`;
80
+ }
81
+ export function parseCookieHeader(cookieHeader) {
82
+ const result = new Map();
83
+ if (!cookieHeader)
84
+ return result;
85
+ for (const part of cookieHeader.split(";")) {
86
+ const trimmed = part.trim();
87
+ if (!trimmed)
88
+ continue;
89
+ const eq = trimmed.indexOf("=");
90
+ if (eq <= 0)
91
+ continue;
92
+ const name = trimmed.slice(0, eq).trim();
93
+ const value = trimmed.slice(eq + 1).trim();
94
+ const list = result.get(name) ?? [];
95
+ list.push(value);
96
+ result.set(name, list);
97
+ }
98
+ return result;
99
+ }
100
+ export function formatSetCookie(name, value, options = {}) {
101
+ const parts = [`${name}=${value}`];
102
+ parts.push(`Path=${options.path ?? "/"}`);
103
+ if (options.domain)
104
+ parts.push(`Domain=${options.domain}`);
105
+ if (options.maxAge !== undefined)
106
+ parts.push(`Max-Age=${Math.max(0, Math.floor(options.maxAge))}`);
107
+ if (options.secure !== false)
108
+ parts.push("Secure");
109
+ if (options.httpOnly !== false)
110
+ parts.push("HttpOnly");
111
+ parts.push(`SameSite=${options.sameSite ?? "Lax"}`);
112
+ return parts.join("; ");
113
+ }
114
+ export function formatClearCookie(name, options = {}) {
115
+ return formatSetCookie(name, "", { ...options, maxAge: 0 });
116
+ }
117
+ function randomBase64UrlToken(byteLength = 32) {
118
+ if (!globalThis.crypto?.getRandomValues) {
119
+ throw new Error("Web Crypto getRandomValues no disponible");
120
+ }
121
+ const bytes = new Uint8Array(byteLength);
122
+ globalThis.crypto.getRandomValues(bytes);
123
+ return toBase64Url(bytes);
124
+ }
125
+ /**
126
+ * Generates a PKCE S256 authorization URL + host-only attempt cookie for RS ID.
127
+ */
128
+ export async function createAuthorizeUrl(options) {
129
+ const clientId = String(options.clientId || "").trim();
130
+ if (!CLIENT_ID_RE.test(clientId))
131
+ throw new TypeError("clientId inválido");
132
+ const base = normalizeRsidOrigin(options.baseUrl);
133
+ const state = randomBase64UrlToken(32);
134
+ const verifier = randomBase64UrlToken(32);
135
+ if (!globalThis.crypto?.subtle) {
136
+ throw new Error("Web Crypto subtle no disponible");
137
+ }
138
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", encoder.encode(verifier));
139
+ const challenge = toBase64Url(new Uint8Array(digest));
140
+ if (challenge.length !== 43) {
141
+ throw new Error("No se pudo generar el code_challenge S256");
142
+ }
143
+ const url = new URL("/api/auth/authorize", base);
144
+ url.searchParams.set("client_id", clientId);
145
+ url.searchParams.set("state", state);
146
+ url.searchParams.set("code_challenge", challenge);
147
+ url.searchParams.set("code_challenge_method", "S256");
148
+ const cookieName = attemptCookieName(clientId);
149
+ const cookieValue = `${state}.${verifier}`;
150
+ const secure = options.secure ?? true;
151
+ const maxAge = options.attemptMaxAge ?? 600;
152
+ return {
153
+ clientId,
154
+ state,
155
+ verifier,
156
+ challenge,
157
+ url: url.toString(),
158
+ cookieName,
159
+ cookieValue,
160
+ attemptCookie: formatSetCookie(cookieName, cookieValue, { path: "/", maxAge, secure, httpOnly: true, sameSite: "Lax" }),
161
+ clearAttemptCookie: formatClearCookie(cookieName, { path: "/", secure, httpOnly: true, sameSite: "Lax" }),
162
+ };
163
+ }
164
+ /**
165
+ * Validates the PKCE attempt cookie against the returned callback `state`.
166
+ * Rejects duplicate cookies to prevent cookie-tossing attacks.
167
+ */
168
+ export function readAttemptCookie(cookieHeaderOrValue, options) {
169
+ const { clientId, state, isRawValue } = options;
170
+ if (!CLIENT_ID_RE.test(clientId) || typeof state !== "string" || !STATE_RE.test(state)) {
171
+ return null;
172
+ }
173
+ let rawValue;
174
+ if (isRawValue) {
175
+ rawValue = typeof cookieHeaderOrValue === "string" ? cookieHeaderOrValue : undefined;
176
+ }
177
+ else {
178
+ const header = typeof cookieHeaderOrValue === "string"
179
+ ? cookieHeaderOrValue
180
+ : cookieHeaderOrValue instanceof Request
181
+ ? cookieHeaderOrValue.headers.get("cookie")
182
+ : null;
183
+ const name = attemptCookieName(clientId);
184
+ const matches = parseCookieHeader(header).get(name) ?? [];
185
+ if (matches.length !== 1)
186
+ return null;
187
+ rawValue = matches[0];
188
+ }
189
+ if (!rawValue)
190
+ return null;
191
+ const dot = rawValue.indexOf(".");
192
+ if (dot < 1 || rawValue.indexOf(".", dot + 1) !== -1)
193
+ return null;
194
+ const cookieState = rawValue.slice(0, dot);
195
+ const verifier = rawValue.slice(dot + 1);
196
+ if (!STATE_RE.test(cookieState) || !VERIFIER_RE.test(verifier) || !constantTimeEqual(cookieState, state)) {
197
+ return null;
198
+ }
199
+ return { clientId, state: cookieState, verifier };
200
+ }
201
+ export function resolvePhotoUrl(raw, baseUrl = RSID_DEFAULT_ORIGIN) {
202
+ if (typeof raw !== "string")
203
+ return "";
204
+ const trimmed = raw.trim();
205
+ if (!trimmed)
206
+ return "";
207
+ const base = normalizeRsidOrigin(baseUrl);
208
+ if (trimmed.startsWith("/id/foto/")) {
209
+ return `${base}${trimmed}`;
210
+ }
211
+ try {
212
+ const parsed = new URL(trimmed);
213
+ if (parsed.origin === base && parsed.pathname.startsWith("/id/foto/")) {
214
+ return parsed.toString();
215
+ }
216
+ }
217
+ catch {
218
+ return "";
219
+ }
220
+ return "";
221
+ }
222
+ function normalizeRole(value) {
223
+ return value === "owner" || value === "admin" ? value : "usuario";
224
+ }
225
+ async function readBoundedJson(response) {
226
+ const contentLength = response.headers.get("content-length");
227
+ if (contentLength !== null && /^\d+$/.test(contentLength) && Number(contentLength) > MAX_RESPONSE_BYTES) {
228
+ return null;
229
+ }
230
+ const text = await response.text();
231
+ if (text.length > MAX_RESPONSE_BYTES)
232
+ return null;
233
+ try {
234
+ const parsed = JSON.parse(text);
235
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
236
+ ? parsed
237
+ : null;
238
+ }
239
+ catch {
240
+ return null;
241
+ }
242
+ }
243
+ /**
244
+ * Exchanges a one-time PKCE code with POST /api/auth/canjear.
245
+ */
246
+ export async function exchangeCode(options) {
247
+ const { clientId, code, state, verifier } = options;
248
+ if (!CLIENT_ID_RE.test(clientId) || !CODE_RE.test(code) || !STATE_RE.test(state) || !VERIFIER_RE.test(verifier)) {
249
+ throw new RsidExchangeError("rejected", "Parámetros PKCE inválidos");
250
+ }
251
+ const base = normalizeRsidOrigin(options.baseUrl);
252
+ const fetcher = options.fetcher ?? globalThis.fetch;
253
+ let response;
254
+ try {
255
+ response = await fetcher(`${base}/api/auth/canjear`, {
256
+ method: "POST",
257
+ headers: { "content-type": "application/json", accept: "application/json" },
258
+ body: JSON.stringify({
259
+ client_id: clientId,
260
+ codigo: code,
261
+ code_verifier: verifier,
262
+ state,
263
+ }),
264
+ redirect: "manual",
265
+ cache: "no-store",
266
+ });
267
+ }
268
+ catch {
269
+ throw new RsidExchangeError("unavailable", "RS ID no respondió durante el canje");
270
+ }
271
+ if (response.status >= 300 && response.status < 400) {
272
+ throw new RsidExchangeError("rejected", "Redirección inesperada de RS ID", response.status);
273
+ }
274
+ if (response.status >= 500) {
275
+ throw new RsidExchangeError("unavailable", `RS ID no disponible (HTTP ${response.status})`, response.status);
276
+ }
277
+ const data = await readBoundedJson(response);
278
+ if (!response.ok) {
279
+ const codeErr = typeof data?.error === "string" ? data.error : "";
280
+ if (response.status === 403 && codeErr === "acceso_pendiente") {
281
+ throw new RsidExchangeError("pending", "Acceso pendiente de aprobación en RS ID", 403);
282
+ }
283
+ if (response.status === 403 && codeErr === "acceso_revocado") {
284
+ throw new RsidExchangeError("revoked", "Acceso revocado en RS ID", 403);
285
+ }
286
+ throw new RsidExchangeError("rejected", `RS ID rechazó el canje (HTTP ${response.status})`, response.status);
287
+ }
288
+ if (!data || typeof data.email !== "string" || !data.email || typeof data.cuenta_id !== "string" || !data.cuenta_id) {
289
+ throw new RsidExchangeError("rejected", "Respuesta incompleta de RS ID");
290
+ }
291
+ const perfil = data.perfil && typeof data.perfil === "object" && !Array.isArray(data.perfil)
292
+ ? data.perfil
293
+ : {};
294
+ return {
295
+ email: data.email.trim().toLowerCase(),
296
+ cuentaId: data.cuenta_id,
297
+ rol: normalizeRole(data.rol),
298
+ foto: resolvePhotoUrl(data.foto, base),
299
+ perfil,
300
+ perfilCompleto: data.perfil_completo === true,
301
+ perfilFalta: Array.isArray(data.perfil_falta) ? data.perfil_falta.map(String) : [],
302
+ compraFalta: Array.isArray(data.compra_falta) ? data.compra_falta.map(String) : [],
303
+ };
304
+ }
305
+ /**
306
+ * Extracts only RS ID session cookies (`rs_id` and Better Auth `rsid.*`) from a Cookie header.
307
+ */
308
+ export function extractRsidCookieHeader(cookieHeader) {
309
+ if (!cookieHeader)
310
+ return "";
311
+ const kept = [];
312
+ for (const part of cookieHeader.split(";")) {
313
+ const trimmed = part.trim();
314
+ const eq = trimmed.indexOf("=");
315
+ if (eq <= 0)
316
+ continue;
317
+ const name = trimmed.slice(0, eq).trim();
318
+ const value = trimmed.slice(eq + 1).trim();
319
+ if (!value || value.length > MAX_COOKIE_VALUE_LEN || /[\r\n;]/.test(value))
320
+ continue;
321
+ if (name === "rs_id" ||
322
+ /^__Secure-rsid\.(session_token|session_data)(\.\d+)?$/u.test(name) ||
323
+ /^rsid\.(session_token|session_data)(\.\d+)?$/u.test(name)) {
324
+ kept.push(`${name}=${value}`);
325
+ }
326
+ }
327
+ return kept.join("; ");
328
+ }
329
+ /**
330
+ * Fetches full RS ID session state (`GET /api/auth/yo`) using forwarded RS ID cookies.
331
+ * Works on *.rsanjur.com subdomains (or browser with credentials: "include").
332
+ */
333
+ export async function fetchSession(options = {}) {
334
+ const base = normalizeRsidOrigin(options.baseUrl);
335
+ const fetcher = options.fetcher ?? globalThis.fetch;
336
+ const rawCookie = options.cookieHeader ?? options.request?.headers.get("cookie") ?? null;
337
+ const cookie = extractRsidCookieHeader(rawCookie);
338
+ if (options.request !== undefined && !cookie) {
339
+ return { autenticado: false };
340
+ }
341
+ const headers = { accept: "application/json" };
342
+ if (cookie)
343
+ headers.cookie = cookie;
344
+ const response = await fetcher(`${base}/api/auth/yo`, {
345
+ method: "GET",
346
+ headers,
347
+ credentials: cookie ? "omit" : "include",
348
+ redirect: "manual",
349
+ cache: "no-store",
350
+ });
351
+ if (!response.ok)
352
+ return { autenticado: false };
353
+ const data = await readBoundedJson(response);
354
+ if (!data || data.autenticado !== true)
355
+ return { autenticado: false };
356
+ return {
357
+ autenticado: true,
358
+ cuentaId: typeof data.cuenta_id === "string" ? data.cuenta_id : undefined,
359
+ email: typeof data.email === "string" ? data.email.trim().toLowerCase() : undefined,
360
+ foto: resolvePhotoUrl(data.foto, base),
361
+ perfil: data.perfil && typeof data.perfil === "object" && !Array.isArray(data.perfil)
362
+ ? data.perfil
363
+ : {},
364
+ perfilCompleto: data.perfil_completo === true,
365
+ perfilFalta: Array.isArray(data.perfil_falta) ? data.perfil_falta.map(String) : [],
366
+ esAdmin: data.es_admin === true,
367
+ raw: data,
368
+ };
369
+ }
370
+ /**
371
+ * Lightweight session check (`GET /api/auth/identidad`).
372
+ */
373
+ export async function fetchIdentity(options = {}) {
374
+ const base = normalizeRsidOrigin(options.baseUrl);
375
+ const fetcher = options.fetcher ?? globalThis.fetch;
376
+ const rawCookie = options.cookieHeader ?? options.request?.headers.get("cookie") ?? null;
377
+ const cookie = extractRsidCookieHeader(rawCookie);
378
+ if (options.request !== undefined && !cookie) {
379
+ return { autenticado: false };
380
+ }
381
+ const headers = { accept: "application/json" };
382
+ if (cookie)
383
+ headers.cookie = cookie;
384
+ const response = await fetcher(`${base}/api/auth/identidad`, {
385
+ method: "GET",
386
+ headers,
387
+ credentials: cookie ? "omit" : "include",
388
+ redirect: "manual",
389
+ cache: "no-store",
390
+ });
391
+ if (!response.ok)
392
+ return { autenticado: false };
393
+ const data = await readBoundedJson(response);
394
+ if (!data || data.autenticado !== true || typeof data.cuenta_id !== "string") {
395
+ return { autenticado: false };
396
+ }
397
+ return { autenticado: true, cuentaId: data.cuenta_id };
398
+ }
399
+ /**
400
+ * Live access check (`POST /api/auth/acceso`) for accessManaged apps (e.g., ritmo, neurodesarrollo, rs-agents).
401
+ */
402
+ export async function checkAppAccess(options) {
403
+ if (!CLIENT_ID_RE.test(options.clientId)) {
404
+ throw new RsidAccessError("denied", "clientId inválido");
405
+ }
406
+ const base = normalizeRsidOrigin(options.baseUrl);
407
+ const origin = new URL(options.appOrigin).origin;
408
+ const cookie = extractRsidCookieHeader(options.cookieHeader);
409
+ if (!cookie) {
410
+ throw new RsidAccessError("unauthenticated", "Sin cookie de sesión RS ID", 401);
411
+ }
412
+ const fetcher = options.fetcher ?? globalThis.fetch;
413
+ let response;
414
+ try {
415
+ response = await fetcher(`${base}/api/auth/acceso`, {
416
+ method: "POST",
417
+ headers: {
418
+ "content-type": "application/json",
419
+ accept: "application/json",
420
+ origin,
421
+ cookie,
422
+ },
423
+ body: JSON.stringify({ client_id: options.clientId }),
424
+ redirect: "manual",
425
+ cache: "no-store",
426
+ });
427
+ }
428
+ catch {
429
+ throw new RsidAccessError("unavailable", "No se pudo consultar /api/auth/acceso");
430
+ }
431
+ if (response.status === 401) {
432
+ throw new RsidAccessError("unauthenticated", "Sesión RS ID expirada o inválida", 401);
433
+ }
434
+ if (response.status >= 500) {
435
+ throw new RsidAccessError("unavailable", `RS ID no disponible (HTTP ${response.status})`, response.status);
436
+ }
437
+ const data = await readBoundedJson(response);
438
+ if (!response.ok || !data || data.ok !== true || typeof data.cuenta_id !== "string") {
439
+ throw new RsidAccessError("denied", "Acceso denegado por RS ID", response.status);
440
+ }
441
+ const estado = String(data.estado || "pendiente");
442
+ const permitido = data.permitido === true;
443
+ if (!permitido) {
444
+ throw new RsidAccessError("denied", `Estado de acceso no permitido: ${estado}`, 403);
445
+ }
446
+ return {
447
+ ok: true,
448
+ clientId: options.clientId,
449
+ cuentaId: data.cuenta_id,
450
+ estado,
451
+ permitido,
452
+ rol: normalizeRole(data.rol),
453
+ };
454
+ }
455
+ const SERVER_KEY_RE = /^rsk_[A-Za-z0-9_-]{32,128}$/u;
456
+ const ACCOUNT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/u;
457
+ /**
458
+ * Chequeo de acceso servidor a servidor (`POST /api/auth/acceso/servidor`), sin cookie:
459
+ * un backend registrado (p. ej. un servidor MCP de RS Connect) pregunta si `cuentaId`
460
+ * sigue aprobada para su app en Accesos. Se autentica con su clave de servidor `rsk_…`
461
+ * (secreto del Worker; nunca la pongas en el navegador ni en el repo).
462
+ * No lanza por acceso denegado: devuelve `permitido: false` con su `estado`.
463
+ */
464
+ export async function checkServerAccess(options) {
465
+ if (!CLIENT_ID_RE.test(options.clientId))
466
+ throw new TypeError("clientId inválido");
467
+ if (!ACCOUNT_ID_RE.test(options.cuentaId))
468
+ throw new TypeError("cuentaId inválido");
469
+ if (!SERVER_KEY_RE.test(options.serverKey))
470
+ throw new TypeError("serverKey inválida");
471
+ const base = normalizeRsidOrigin(options.baseUrl);
472
+ const fetcher = options.fetcher ?? globalThis.fetch;
473
+ let response;
474
+ try {
475
+ response = await fetcher(`${base}/api/auth/acceso/servidor`, {
476
+ method: "POST",
477
+ headers: {
478
+ "content-type": "application/json",
479
+ accept: "application/json",
480
+ authorization: `Bearer ${options.serverKey}`,
481
+ },
482
+ body: JSON.stringify({ client_id: options.clientId, cuenta_id: options.cuentaId }),
483
+ redirect: "manual",
484
+ cache: "no-store",
485
+ });
486
+ }
487
+ catch {
488
+ throw new RsidAccessError("unavailable", "No se pudo consultar /api/auth/acceso/servidor");
489
+ }
490
+ if (response.status === 401) {
491
+ throw new RsidAccessError("unauthenticated", "RS ID rechazó la clave de servidor", 401);
492
+ }
493
+ if (response.status >= 500) {
494
+ throw new RsidAccessError("unavailable", `RS ID no disponible (HTTP ${response.status})`, response.status);
495
+ }
496
+ const data = await readBoundedJson(response);
497
+ if (!response.ok || !data || data.ok !== true || data.cuenta_id !== options.cuentaId) {
498
+ throw new RsidAccessError("unavailable", `Respuesta inesperada de RS ID (HTTP ${response.status})`, response.status);
499
+ }
500
+ return {
501
+ clientId: options.clientId,
502
+ cuentaId: options.cuentaId,
503
+ estado: String(data.estado || "pendiente"),
504
+ permitido: data.permitido === true,
505
+ rol: normalizeRole(data.rol),
506
+ };
507
+ }
508
+ /**
509
+ * Ensures `returnPath` stays within `appOrigin` (prevents open redirects) and builds `https://id.rsanjur.com/salir?volver=...`.
510
+ */
511
+ export function sanitizeReturnPath(path, fallback = "/") {
512
+ if (typeof path !== "string")
513
+ return fallback;
514
+ const trimmed = path.trim();
515
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || /[\r\n\\]/.test(trimmed)) {
516
+ return fallback;
517
+ }
518
+ return trimmed;
519
+ }
520
+ export function buildLogoutUrl(options) {
521
+ const base = normalizeRsidOrigin(options.baseUrl);
522
+ const origin = new URL(options.appOrigin).origin;
523
+ const safePath = sanitizeReturnPath(options.returnPath, "/");
524
+ const url = new URL("/salir", base);
525
+ url.searchParams.set("volver", `${origin}${safePath}`);
526
+ return url.toString();
527
+ }
528
+ /* ---------- Local HMAC-SHA256 Session Cookie Helpers (Web Crypto) ---------- */
529
+ async function importHmacKey(secret, namespace) {
530
+ if (typeof secret !== "string" || secret.length < 16) {
531
+ throw new TypeError("El secreto de sesión HMAC debe tener al menos 16 caracteres");
532
+ }
533
+ return globalThis.crypto.subtle.importKey("raw", encoder.encode(`${namespace}|${secret}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
534
+ }
535
+ /**
536
+ * Signs a JSON payload as `<base64url(payload)>.<base64url(hmac-sha256)>` with expiration (`exp` in Unix ms).
537
+ */
538
+ export async function signSessionCookie(payload, options) {
539
+ const now = options.nowMs ?? Date.now();
540
+ const maxAgeSeconds = options.maxAgeSeconds ?? 7 * 24 * 60 * 60;
541
+ const envelope = {
542
+ ...payload,
543
+ iat: now,
544
+ exp: now + maxAgeSeconds * 1000,
545
+ };
546
+ const body = toBase64Url(encoder.encode(JSON.stringify(envelope)));
547
+ const key = await importHmacKey(options.secret, options.namespace ?? "rsid-session-v1");
548
+ const sigBytes = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(body)));
549
+ return `${body}.${toBase64Url(sigBytes)}`;
550
+ }
551
+ /**
552
+ * Verifies an HMAC-SHA256 signed session cookie and returns the payload if valid and unexpired.
553
+ */
554
+ export async function verifySessionCookie(token, options) {
555
+ if (typeof token !== "string" || !token || token.length > MAX_COOKIE_VALUE_LEN)
556
+ return null;
557
+ const dot = token.indexOf(".");
558
+ if (dot <= 0 || token.indexOf(".", dot + 1) !== -1)
559
+ return null;
560
+ const body = token.slice(0, dot);
561
+ const sig = token.slice(dot + 1);
562
+ if (!body || !sig)
563
+ return null;
564
+ const key = await importHmacKey(options.secret, options.namespace ?? "rsid-session-v1");
565
+ const expectedBytes = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(body)));
566
+ const expectedSig = toBase64Url(expectedBytes);
567
+ if (!constantTimeEqual(sig, expectedSig))
568
+ return null;
569
+ const decodedBytes = fromBase64Url(body);
570
+ if (!decodedBytes)
571
+ return null;
572
+ try {
573
+ const parsed = JSON.parse(decoder.decode(decodedBytes));
574
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
575
+ return null;
576
+ const now = options.nowMs ?? Date.now();
577
+ if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp) || parsed.exp <= now) {
578
+ return null;
579
+ }
580
+ return parsed;
581
+ }
582
+ catch {
583
+ return null;
584
+ }
585
+ }
@@ -0,0 +1 @@
1
+ export * from "./core.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./core.js";
@@ -0,0 +1,22 @@
1
+ import * as React from "react";
2
+ export interface RsidReactSession {
3
+ loading: boolean;
4
+ authenticated: boolean;
5
+ email?: string;
6
+ name?: string;
7
+ photo?: string;
8
+ role?: string;
9
+ isAdmin?: boolean;
10
+ }
11
+ /**
12
+ * Lightweight React hook to read the consumer's `/api/sesion/yo` endpoint.
13
+ */
14
+ export declare function useRsidSession(endpoint?: string): RsidReactSession;
15
+ export interface RsidLoginButtonProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
16
+ href?: string;
17
+ label?: string;
18
+ }
19
+ /**
20
+ * Zero-secret login link/button for React, Next.js, and Astro-React apps.
21
+ */
22
+ export declare function RsidLoginButton({ href, label, className, children, ...rest }: RsidLoginButtonProps): React.ReactElement;
package/dist/react.js ADDED
@@ -0,0 +1,57 @@
1
+ import * as React from "react";
2
+ /**
3
+ * Lightweight React hook to read the consumer's `/api/sesion/yo` endpoint.
4
+ */
5
+ export function useRsidSession(endpoint = "/api/sesion/yo") {
6
+ const [state, setState] = React.useState({
7
+ loading: true,
8
+ authenticated: false,
9
+ });
10
+ React.useEffect(() => {
11
+ let active = true;
12
+ const controller = new AbortController();
13
+ fetch(endpoint, {
14
+ credentials: "same-origin",
15
+ cache: "no-store",
16
+ headers: { accept: "application/json" },
17
+ signal: controller.signal,
18
+ })
19
+ .then((res) => (res.ok ? res.json() : { autenticado: false }))
20
+ .then((data) => {
21
+ if (!active)
22
+ return;
23
+ if (data?.autenticado !== true) {
24
+ setState({ loading: false, authenticated: false });
25
+ return;
26
+ }
27
+ const perfil = data.perfil ?? {};
28
+ const name = (typeof data.nombre === "string" && data.nombre) ||
29
+ [perfil.nombre, perfil.apellido].filter(Boolean).join(" ").trim() ||
30
+ undefined;
31
+ setState({
32
+ loading: false,
33
+ authenticated: true,
34
+ email: typeof data.email === "string" ? data.email : undefined,
35
+ name,
36
+ photo: typeof data.foto === "string" ? data.foto : undefined,
37
+ role: typeof data.rol === "string" ? data.rol : undefined,
38
+ isAdmin: data.es_admin === true,
39
+ });
40
+ })
41
+ .catch(() => {
42
+ if (active)
43
+ setState({ loading: false, authenticated: false });
44
+ });
45
+ return () => {
46
+ active = false;
47
+ controller.abort();
48
+ };
49
+ }, [endpoint]);
50
+ return state;
51
+ }
52
+ /**
53
+ * Zero-secret login link/button for React, Next.js, and Astro-React apps.
54
+ */
55
+ export function RsidLoginButton({ href = "/api/auth/start", label = "Entrar con RS ID", className = "rs-btn-primary", children, ...rest }) {
56
+ return React.createElement("a", { href, className, ...rest }, children ?? label);
57
+ }