@rsanjur-dev/id 0.0.0-stage → 1.0.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.d.ts ADDED
@@ -0,0 +1,183 @@
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 declare const RSID_DEFAULT_ORIGIN = "https://id.rsanjur.com";
7
+ export type RsidRole = "usuario" | "admin" | "owner";
8
+ export type RsidAccessState = "administrador" | "sin_restriccion" | "aprobado" | "pendiente" | "revocado";
9
+ export interface RsidProfile {
10
+ nombre?: string;
11
+ apellido?: string;
12
+ telefono?: string;
13
+ pais?: string;
14
+ cedula?: string;
15
+ [key: string]: unknown;
16
+ }
17
+ export interface RsidAuthorizeResult {
18
+ clientId: string;
19
+ state: string;
20
+ verifier: string;
21
+ challenge: string;
22
+ url: string;
23
+ cookieName: string;
24
+ cookieValue: string;
25
+ attemptCookie: string;
26
+ clearAttemptCookie: string;
27
+ }
28
+ export interface RsidAttempt {
29
+ clientId: string;
30
+ state: string;
31
+ verifier: string;
32
+ }
33
+ export interface RsidExchangedAccount {
34
+ email: string;
35
+ cuentaId: string;
36
+ rol: RsidRole;
37
+ foto: string;
38
+ perfil: RsidProfile;
39
+ perfilCompleto: boolean;
40
+ perfilFalta: string[];
41
+ compraFalta: string[];
42
+ }
43
+ export interface RsidSessionResponse {
44
+ autenticado: boolean;
45
+ cuentaId?: string;
46
+ email?: string;
47
+ foto?: string;
48
+ perfil?: RsidProfile;
49
+ perfilCompleto?: boolean;
50
+ perfilFalta?: string[];
51
+ esAdmin?: boolean;
52
+ raw?: Record<string, unknown>;
53
+ }
54
+ export interface RsidIdentityResponse {
55
+ autenticado: boolean;
56
+ cuentaId?: string;
57
+ }
58
+ export interface RsidAccessCheckResult {
59
+ ok: boolean;
60
+ clientId: string;
61
+ cuentaId: string;
62
+ estado: RsidAccessState;
63
+ permitido: boolean;
64
+ rol: RsidRole;
65
+ }
66
+ export interface CookieOptions {
67
+ path?: string;
68
+ domain?: string;
69
+ maxAge?: number;
70
+ httpOnly?: boolean;
71
+ secure?: boolean;
72
+ sameSite?: "Lax" | "Strict" | "None";
73
+ }
74
+ export declare class RsidExchangeError extends Error {
75
+ readonly kind: "rejected" | "unavailable" | "pending" | "revoked";
76
+ readonly status?: number;
77
+ constructor(kind: "rejected" | "unavailable" | "pending" | "revoked", message?: string, status?: number);
78
+ }
79
+ export declare class RsidAccessError extends Error {
80
+ readonly kind: "denied" | "unauthenticated" | "unavailable";
81
+ readonly status?: number;
82
+ constructor(kind: "denied" | "unauthenticated" | "unavailable", message?: string, status?: number);
83
+ }
84
+ export declare function toBase64Url(bytes: Uint8Array): string;
85
+ export declare function fromBase64Url(input: string): Uint8Array | null;
86
+ export declare function constantTimeEqual(a: string, b: string): boolean;
87
+ export declare function normalizeRsidOrigin(origin?: string): string;
88
+ export declare function attemptCookieName(clientId: string): string;
89
+ export declare function parseCookieHeader(cookieHeader: string | null | undefined): Map<string, string[]>;
90
+ export declare function formatSetCookie(name: string, value: string, options?: CookieOptions): string;
91
+ export declare function formatClearCookie(name: string, options?: Omit<CookieOptions, "maxAge">): string;
92
+ /**
93
+ * Generates a PKCE S256 authorization URL + host-only attempt cookie for RS ID.
94
+ */
95
+ export declare function createAuthorizeUrl(options: {
96
+ clientId: string;
97
+ baseUrl?: string;
98
+ attemptMaxAge?: number;
99
+ secure?: boolean;
100
+ }): Promise<RsidAuthorizeResult>;
101
+ /**
102
+ * Validates the PKCE attempt cookie against the returned callback `state`.
103
+ * Rejects duplicate cookies to prevent cookie-tossing attacks.
104
+ */
105
+ export declare function readAttemptCookie(cookieHeaderOrValue: string | Request | null | undefined, options: {
106
+ clientId: string;
107
+ state: string;
108
+ isRawValue?: boolean;
109
+ }): RsidAttempt | null;
110
+ export declare function resolvePhotoUrl(raw: unknown, baseUrl?: string): string;
111
+ /**
112
+ * Exchanges a one-time PKCE code with POST /api/auth/canjear.
113
+ */
114
+ export declare function exchangeCode(options: {
115
+ clientId: string;
116
+ code: string;
117
+ state: string;
118
+ verifier: string;
119
+ baseUrl?: string;
120
+ fetcher?: typeof fetch;
121
+ }): Promise<RsidExchangedAccount>;
122
+ /**
123
+ * Extracts only RS ID session cookies (`rs_id` and Better Auth `rsid.*`) from a Cookie header.
124
+ */
125
+ export declare function extractRsidCookieHeader(cookieHeader: string | null | undefined): string;
126
+ /**
127
+ * Fetches full RS ID session state (`GET /api/auth/yo`) using forwarded RS ID cookies.
128
+ * Works on *.rsanjur.com subdomains (or browser with credentials: "include").
129
+ */
130
+ export declare function fetchSession(options?: {
131
+ cookieHeader?: string | null;
132
+ request?: Request;
133
+ baseUrl?: string;
134
+ fetcher?: typeof fetch;
135
+ }): Promise<RsidSessionResponse>;
136
+ /**
137
+ * Lightweight session check (`GET /api/auth/identidad`).
138
+ */
139
+ export declare function fetchIdentity(options?: {
140
+ cookieHeader?: string | null;
141
+ request?: Request;
142
+ baseUrl?: string;
143
+ fetcher?: typeof fetch;
144
+ }): Promise<RsidIdentityResponse>;
145
+ /**
146
+ * Live access check (`POST /api/auth/acceso`) for accessManaged apps (e.g., ritmo, neurodesarrollo, rs-agents).
147
+ */
148
+ export declare function checkAppAccess(options: {
149
+ clientId: string;
150
+ appOrigin: string;
151
+ cookieHeader: string;
152
+ baseUrl?: string;
153
+ fetcher?: typeof fetch;
154
+ }): Promise<RsidAccessCheckResult>;
155
+ /**
156
+ * Ensures `returnPath` stays within `appOrigin` (prevents open redirects) and builds `https://id.rsanjur.com/salir?volver=...`.
157
+ */
158
+ export declare function sanitizeReturnPath(path: string | null | undefined, fallback?: string): string;
159
+ export declare function buildLogoutUrl(options: {
160
+ appOrigin: string;
161
+ returnPath?: string;
162
+ baseUrl?: string;
163
+ }): string;
164
+ /**
165
+ * Signs a JSON payload as `<base64url(payload)>.<base64url(hmac-sha256)>` with expiration (`exp` in Unix ms).
166
+ */
167
+ export declare function signSessionCookie<T extends Record<string, unknown>>(payload: T, options: {
168
+ secret: string;
169
+ maxAgeSeconds?: number;
170
+ namespace?: string;
171
+ nowMs?: number;
172
+ }): Promise<string>;
173
+ /**
174
+ * Verifies an HMAC-SHA256 signed session cookie and returns the payload if valid and unexpired.
175
+ */
176
+ export declare function verifySessionCookie<T extends Record<string, unknown> = Record<string, unknown>>(token: string | null | undefined, options: {
177
+ secret: string;
178
+ namespace?: string;
179
+ nowMs?: number;
180
+ }): Promise<(T & {
181
+ iat: number;
182
+ exp: number;
183
+ }) | null>;
package/dist/core.js ADDED
@@ -0,0 +1,532 @@
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
+ /**
456
+ * Ensures `returnPath` stays within `appOrigin` (prevents open redirects) and builds `https://id.rsanjur.com/salir?volver=...`.
457
+ */
458
+ export function sanitizeReturnPath(path, fallback = "/") {
459
+ if (typeof path !== "string")
460
+ return fallback;
461
+ const trimmed = path.trim();
462
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//") || /[\r\n\\]/.test(trimmed)) {
463
+ return fallback;
464
+ }
465
+ return trimmed;
466
+ }
467
+ export function buildLogoutUrl(options) {
468
+ const base = normalizeRsidOrigin(options.baseUrl);
469
+ const origin = new URL(options.appOrigin).origin;
470
+ const safePath = sanitizeReturnPath(options.returnPath, "/");
471
+ const url = new URL("/salir", base);
472
+ url.searchParams.set("volver", `${origin}${safePath}`);
473
+ return url.toString();
474
+ }
475
+ /* ---------- Local HMAC-SHA256 Session Cookie Helpers (Web Crypto) ---------- */
476
+ async function importHmacKey(secret, namespace) {
477
+ if (typeof secret !== "string" || secret.length < 16) {
478
+ throw new TypeError("El secreto de sesión HMAC debe tener al menos 16 caracteres");
479
+ }
480
+ return globalThis.crypto.subtle.importKey("raw", encoder.encode(`${namespace}|${secret}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
481
+ }
482
+ /**
483
+ * Signs a JSON payload as `<base64url(payload)>.<base64url(hmac-sha256)>` with expiration (`exp` in Unix ms).
484
+ */
485
+ export async function signSessionCookie(payload, options) {
486
+ const now = options.nowMs ?? Date.now();
487
+ const maxAgeSeconds = options.maxAgeSeconds ?? 7 * 24 * 60 * 60;
488
+ const envelope = {
489
+ ...payload,
490
+ iat: now,
491
+ exp: now + maxAgeSeconds * 1000,
492
+ };
493
+ const body = toBase64Url(encoder.encode(JSON.stringify(envelope)));
494
+ const key = await importHmacKey(options.secret, options.namespace ?? "rsid-session-v1");
495
+ const sigBytes = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(body)));
496
+ return `${body}.${toBase64Url(sigBytes)}`;
497
+ }
498
+ /**
499
+ * Verifies an HMAC-SHA256 signed session cookie and returns the payload if valid and unexpired.
500
+ */
501
+ export async function verifySessionCookie(token, options) {
502
+ if (typeof token !== "string" || !token || token.length > MAX_COOKIE_VALUE_LEN)
503
+ return null;
504
+ const dot = token.indexOf(".");
505
+ if (dot <= 0 || token.indexOf(".", dot + 1) !== -1)
506
+ return null;
507
+ const body = token.slice(0, dot);
508
+ const sig = token.slice(dot + 1);
509
+ if (!body || !sig)
510
+ return null;
511
+ const key = await importHmacKey(options.secret, options.namespace ?? "rsid-session-v1");
512
+ const expectedBytes = new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(body)));
513
+ const expectedSig = toBase64Url(expectedBytes);
514
+ if (!constantTimeEqual(sig, expectedSig))
515
+ return null;
516
+ const decodedBytes = fromBase64Url(body);
517
+ if (!decodedBytes)
518
+ return null;
519
+ try {
520
+ const parsed = JSON.parse(decoder.decode(decodedBytes));
521
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
522
+ return null;
523
+ const now = options.nowMs ?? Date.now();
524
+ if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp) || parsed.exp <= now) {
525
+ return null;
526
+ }
527
+ return parsed;
528
+ }
529
+ catch {
530
+ return null;
531
+ }
532
+ }
@@ -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
+ }
@@ -0,0 +1,77 @@
1
+ <script lang="ts">
2
+ import { onMount } from "svelte";
3
+ import { ProfileMenu } from "@rsanjur-dev/ui/svelte";
4
+ import type { ProfileMenuItem, ProfileMenuTheme, ProfileUser } from "@rsanjur-dev/ui/svelte";
5
+
6
+ interface Props {
7
+ user?: ProfileUser | null;
8
+ sessionEndpoint?: string;
9
+ profileHref?: string;
10
+ loginHref?: string;
11
+ loginLabel?: string;
12
+ logoutHref?: string;
13
+ onLogout?: () => void | Promise<void>;
14
+ items?: ProfileMenuItem[];
15
+ theme?: ProfileMenuTheme;
16
+ display?: "auto" | "name" | "photo";
17
+ class?: string;
18
+ }
19
+
20
+ let {
21
+ user = null,
22
+ sessionEndpoint = "/api/sesion/yo",
23
+ profileHref = "https://id.rsanjur.com/cuenta",
24
+ loginHref = "/api/auth/start",
25
+ loginLabel = "Entrar",
26
+ logoutHref = "/api/auth/logout",
27
+ onLogout,
28
+ items = [],
29
+ theme = "light",
30
+ display = "auto",
31
+ class: className = "",
32
+ }: Props = $props();
33
+
34
+ let resolvedUser = $state<ProfileUser | null>(null);
35
+
36
+ const activeUser = $derived(user ?? resolvedUser);
37
+
38
+ onMount(async () => {
39
+ if (user || !sessionEndpoint) return;
40
+ try {
41
+ const res = await fetch(sessionEndpoint, {
42
+ credentials: "same-origin",
43
+ cache: "no-store",
44
+ headers: { accept: "application/json" },
45
+ });
46
+ if (!res.ok) return;
47
+ const data = (await res.json()) as Record<string, unknown>;
48
+ if (data?.autenticado !== true) return;
49
+ const perfil = (data.perfil as Record<string, unknown> | undefined) ?? {};
50
+ const fullName =
51
+ (typeof data.nombre === "string" && data.nombre) ||
52
+ [perfil.nombre, perfil.apellido].filter(Boolean).join(" ").trim() ||
53
+ null;
54
+ resolvedUser = {
55
+ name: fullName,
56
+ email: typeof data.email === "string" ? data.email : null,
57
+ photoUrl: typeof data.foto === "string" ? data.foto : null,
58
+ accountId: typeof data.cuenta_id === "string" ? data.cuenta_id : null,
59
+ };
60
+ } catch {
61
+ // Best-effort client hydration; never breaks page rendering.
62
+ }
63
+ });
64
+ </script>
65
+
66
+ <ProfileMenu
67
+ user={activeUser}
68
+ {items}
69
+ {profileHref}
70
+ {loginHref}
71
+ {loginLabel}
72
+ {logoutHref}
73
+ {onLogout}
74
+ {theme}
75
+ {display}
76
+ class={className}
77
+ />
@@ -0,0 +1,17 @@
1
+ import type { ProfileMenuItem, ProfileMenuTheme, ProfileUser } from "@rsanjur-dev/ui/svelte";
2
+ interface Props {
3
+ user?: ProfileUser | null;
4
+ sessionEndpoint?: string;
5
+ profileHref?: string;
6
+ loginHref?: string;
7
+ loginLabel?: string;
8
+ logoutHref?: string;
9
+ onLogout?: () => void | Promise<void>;
10
+ items?: ProfileMenuItem[];
11
+ theme?: ProfileMenuTheme;
12
+ display?: "auto" | "name" | "photo";
13
+ class?: string;
14
+ }
15
+ declare const RsidProfileMenu: import("svelte").Component<Props, {}, "">;
16
+ type RsidProfileMenu = ReturnType<typeof RsidProfileMenu>;
17
+ export default RsidProfileMenu;
@@ -0,0 +1 @@
1
+ export { default as RsidProfileMenu } from "./RsidProfileMenu.svelte";
@@ -0,0 +1 @@
1
+ export { default as RsidProfileMenu } from "./RsidProfileMenu.svelte";
@@ -0,0 +1,107 @@
1
+ import { type RsidExchangedAccount, type RsidProfile, type RsidRole } from "./core.js";
2
+ export interface SvelteKitCookiesLike {
3
+ get(name: string): string | undefined;
4
+ set(name: string, value: string, options: {
5
+ path: string;
6
+ httpOnly?: boolean;
7
+ secure?: boolean;
8
+ sameSite?: "lax" | "strict" | "none" | boolean;
9
+ maxAge?: number;
10
+ }): void;
11
+ delete(name: string, options: {
12
+ path: string;
13
+ }): void;
14
+ }
15
+ export interface SvelteKitEventLike {
16
+ request: Request;
17
+ url: URL;
18
+ cookies: SvelteKitCookiesLike;
19
+ locals: Record<string, unknown>;
20
+ platform?: unknown;
21
+ }
22
+ export interface RsidLocalSession {
23
+ email: string;
24
+ cuentaId: string;
25
+ rol: RsidRole;
26
+ foto?: string;
27
+ perfil?: RsidProfile;
28
+ [key: string]: unknown;
29
+ }
30
+ export interface RsidHandleOptions<Event extends SvelteKitEventLike = SvelteKitEventLike, Session extends Record<string, unknown> = RsidLocalSession> {
31
+ cookieName?: string;
32
+ getSecret(event: Event): string | undefined;
33
+ namespace?: string;
34
+ localKey?: string;
35
+ /** Optional consumer revalidation (e.g. D1 check for Comibox or Stryd Panama). */
36
+ revalidate?(session: Session & {
37
+ iat: number;
38
+ exp: number;
39
+ }, event: Event): Promise<Session | null>;
40
+ }
41
+ /**
42
+ * SvelteKit Handle that verifies the local HMAC session cookie and optionally revalidates against D1/RS ID.
43
+ */
44
+ export declare function createRsidHandle<Event extends SvelteKitEventLike = SvelteKitEventLike, Session extends Record<string, unknown> = RsidLocalSession>(options: RsidHandleOptions<Event, Session>): ({ event, resolve, }: {
45
+ event: Event;
46
+ resolve(event: Event): Promise<Response>;
47
+ }) => Promise<Response>;
48
+ /**
49
+ * GET handler that initiates PKCE S256 login with RS ID and optionally stores a safe return path.
50
+ */
51
+ export declare function createAuthStartHandler<Event extends SvelteKitEventLike = SvelteKitEventLike>(options: {
52
+ clientId: string;
53
+ baseUrl?: string;
54
+ returnCookieName?: string;
55
+ returnQueryParam?: string;
56
+ defaultReturnPath?: string;
57
+ }): (event: Event) => Promise<Response>;
58
+ /**
59
+ * GET handler for RS ID PKCE callback (`?code=...&state=...`).
60
+ * Validates PKCE attempt cookie, exchanges code, optionally authorizes against local DB (e.g., D1),
61
+ * signs local session cookie, and redirects to safe return path.
62
+ */
63
+ export declare function createAuthCallbackHandler<Event extends SvelteKitEventLike = SvelteKitEventLike, Session extends Record<string, unknown> = RsidLocalSession>(options: {
64
+ clientId: string;
65
+ cookieName?: string;
66
+ returnCookieName?: string;
67
+ baseUrl?: string;
68
+ namespace?: string;
69
+ maxAgeSeconds?: number;
70
+ defaultRedirect?: string;
71
+ errorRedirect?: string;
72
+ getSecret(event: Event): string | undefined;
73
+ fetcher?: typeof fetch;
74
+ /** Optional consumer authorization hook (e.g., D1 user lookup / allowlist). Return null to reject. */
75
+ authorizeUser?(account: RsidExchangedAccount, event: Event): Promise<Session | null>;
76
+ }): (event: Event) => Promise<Response>;
77
+ /**
78
+ * Clears local session cookie and redirects once to RS ID global logout (`/salir?volver=...`).
79
+ */
80
+ export declare function createLogoutHandler<Event extends SvelteKitEventLike = SvelteKitEventLike>(options?: {
81
+ cookieName?: string;
82
+ baseUrl?: string;
83
+ defaultReturnPath?: string;
84
+ getAppOrigin?(event: Event): string;
85
+ }): (event: Event) => Promise<Response>;
86
+ export interface SessionEndpointPayload {
87
+ autenticado: boolean;
88
+ email?: string;
89
+ nombre?: string;
90
+ foto?: string;
91
+ rol?: string;
92
+ es_admin?: boolean;
93
+ perfil?: RsidProfile;
94
+ [key: string]: unknown;
95
+ }
96
+ /**
97
+ * Standardized `GET /api/sesion/yo` endpoint.
98
+ * Fail-closed: returns `{ autenticado: false }` with HTTP 200 and `cache-control: no-store` if unauthenticated or if D1 revalidation throws.
99
+ */
100
+ export declare function createSessionEndpoint<Event extends SvelteKitEventLike = SvelteKitEventLike, Session extends Record<string, unknown> = RsidLocalSession>(options: {
101
+ cookieName?: string;
102
+ namespace?: string;
103
+ localKey?: string;
104
+ getSecret(event: Event): string | undefined;
105
+ /** Optional consumer hook (e.g., D1 lookup + role/avatar enrichment). Return null if unauthorized. */
106
+ resolveProfile?(session: Session, event: Event): Promise<SessionEndpointPayload | null>;
107
+ }): (event: Event) => Promise<Response>;
@@ -0,0 +1,233 @@
1
+ import { RSID_DEFAULT_ORIGIN, RsidExchangeError, attemptCookieName, buildLogoutUrl, createAuthorizeUrl, exchangeCode, readAttemptCookie, sanitizeReturnPath, signSessionCookie, verifySessionCookie, } from "./core.js";
2
+ /**
3
+ * SvelteKit Handle that verifies the local HMAC session cookie and optionally revalidates against D1/RS ID.
4
+ */
5
+ export function createRsidHandle(options) {
6
+ const cookieName = options.cookieName ?? "rs_session";
7
+ const localKey = options.localKey ?? "session";
8
+ return async function handle({ event, resolve, }) {
9
+ event.locals[localKey] = null;
10
+ const secret = options.getSecret(event);
11
+ const raw = event.cookies.get(cookieName);
12
+ if (secret && raw) {
13
+ try {
14
+ const verified = await verifySessionCookie(raw, {
15
+ secret,
16
+ namespace: options.namespace,
17
+ });
18
+ if (verified) {
19
+ event.locals[localKey] = options.revalidate
20
+ ? await options.revalidate(verified, event)
21
+ : verified;
22
+ }
23
+ }
24
+ catch {
25
+ event.locals[localKey] = null;
26
+ }
27
+ }
28
+ return resolve(event);
29
+ };
30
+ }
31
+ /**
32
+ * GET handler that initiates PKCE S256 login with RS ID and optionally stores a safe return path.
33
+ */
34
+ export function createAuthStartHandler(options) {
35
+ const returnCookieName = options.returnCookieName ?? "__Host-rsid-return";
36
+ const returnQueryParam = options.returnQueryParam ?? "volver";
37
+ const defaultReturnPath = options.defaultReturnPath ?? "/";
38
+ return async function GET(event) {
39
+ const secure = event.url.protocol === "https:";
40
+ const attempt = await createAuthorizeUrl({
41
+ clientId: options.clientId,
42
+ baseUrl: options.baseUrl ?? RSID_DEFAULT_ORIGIN,
43
+ secure,
44
+ });
45
+ event.cookies.set(attempt.cookieName, attempt.cookieValue, {
46
+ path: "/",
47
+ httpOnly: true,
48
+ secure,
49
+ sameSite: "lax",
50
+ maxAge: 600,
51
+ });
52
+ const requestedReturn = event.url.searchParams.get(returnQueryParam);
53
+ const safeReturn = sanitizeReturnPath(requestedReturn, defaultReturnPath);
54
+ if (safeReturn) {
55
+ event.cookies.set(returnCookieName, safeReturn, {
56
+ path: "/",
57
+ httpOnly: true,
58
+ secure,
59
+ sameSite: "lax",
60
+ maxAge: 600,
61
+ });
62
+ }
63
+ return new Response(null, {
64
+ status: 302,
65
+ headers: {
66
+ location: attempt.url,
67
+ "cache-control": "no-store",
68
+ },
69
+ });
70
+ };
71
+ }
72
+ /**
73
+ * GET handler for RS ID PKCE callback (`?code=...&state=...`).
74
+ * Validates PKCE attempt cookie, exchanges code, optionally authorizes against local DB (e.g., D1),
75
+ * signs local session cookie, and redirects to safe return path.
76
+ */
77
+ export function createAuthCallbackHandler(options) {
78
+ const cookieName = options.cookieName ?? "rs_session";
79
+ const returnCookieName = options.returnCookieName ?? "__Host-rsid-return";
80
+ const defaultRedirect = options.defaultRedirect ?? "/";
81
+ const errorRedirect = options.errorRedirect ?? "/?auth_error=1";
82
+ return async function GET(event) {
83
+ const code = event.url.searchParams.get("code") ?? event.url.searchParams.get("rsid") ?? "";
84
+ const state = event.url.searchParams.get("state") ?? "";
85
+ const attemptName = attemptCookieName(options.clientId);
86
+ const attempt = readAttemptCookie(event.request, {
87
+ clientId: options.clientId,
88
+ state,
89
+ });
90
+ event.cookies.delete(attemptName, { path: "/" });
91
+ const savedReturn = sanitizeReturnPath(event.cookies.get(returnCookieName), defaultRedirect);
92
+ event.cookies.delete(returnCookieName, { path: "/" });
93
+ if (!attempt || !code) {
94
+ return new Response(null, {
95
+ status: 302,
96
+ headers: { location: errorRedirect, "cache-control": "no-store" },
97
+ });
98
+ }
99
+ let account;
100
+ try {
101
+ account = await exchangeCode({
102
+ clientId: options.clientId,
103
+ code,
104
+ state: attempt.state,
105
+ verifier: attempt.verifier,
106
+ baseUrl: options.baseUrl ?? RSID_DEFAULT_ORIGIN,
107
+ fetcher: options.fetcher,
108
+ });
109
+ }
110
+ catch (err) {
111
+ const reason = err instanceof RsidExchangeError ? err.kind : "rejected";
112
+ const target = new URL(errorRedirect, event.url.origin);
113
+ target.searchParams.set("reason", reason);
114
+ return new Response(null, {
115
+ status: 302,
116
+ headers: { location: `${target.pathname}${target.search}`, "cache-control": "no-store" },
117
+ });
118
+ }
119
+ const sessionPayload = options.authorizeUser
120
+ ? await options.authorizeUser(account, event)
121
+ : {
122
+ email: account.email,
123
+ cuentaId: account.cuentaId,
124
+ rol: account.rol,
125
+ foto: account.foto,
126
+ perfil: account.perfil,
127
+ };
128
+ if (!sessionPayload) {
129
+ const target = new URL(errorRedirect, event.url.origin);
130
+ target.searchParams.set("reason", "unauthorized");
131
+ return new Response(null, {
132
+ status: 302,
133
+ headers: { location: `${target.pathname}${target.search}`, "cache-control": "no-store" },
134
+ });
135
+ }
136
+ const secret = options.getSecret(event);
137
+ if (!secret) {
138
+ return new Response(JSON.stringify({ error: "session_not_configured" }), {
139
+ status: 503,
140
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
141
+ });
142
+ }
143
+ const maxAgeSeconds = options.maxAgeSeconds ?? 7 * 24 * 60 * 60;
144
+ const token = await signSessionCookie(sessionPayload, {
145
+ secret,
146
+ maxAgeSeconds,
147
+ namespace: options.namespace,
148
+ });
149
+ const secure = event.url.protocol === "https:";
150
+ event.cookies.set(cookieName, token, {
151
+ path: "/",
152
+ httpOnly: true,
153
+ secure,
154
+ sameSite: "lax",
155
+ maxAge: maxAgeSeconds,
156
+ });
157
+ return new Response(null, {
158
+ status: 302,
159
+ headers: { location: savedReturn, "cache-control": "no-store" },
160
+ });
161
+ };
162
+ }
163
+ /**
164
+ * Clears local session cookie and redirects once to RS ID global logout (`/salir?volver=...`).
165
+ */
166
+ export function createLogoutHandler(options = {}) {
167
+ const cookieName = options.cookieName ?? "rs_session";
168
+ const defaultReturnPath = options.defaultReturnPath ?? "/";
169
+ return async function handleLogout(event) {
170
+ event.cookies.delete(cookieName, { path: "/" });
171
+ const appOrigin = options.getAppOrigin ? options.getAppOrigin(event) : event.url.origin;
172
+ const returnPath = sanitizeReturnPath(event.url.searchParams.get("volver"), defaultReturnPath);
173
+ const logoutUrl = buildLogoutUrl({
174
+ appOrigin,
175
+ returnPath,
176
+ baseUrl: options.baseUrl ?? RSID_DEFAULT_ORIGIN,
177
+ });
178
+ return new Response(null, {
179
+ status: 302,
180
+ headers: { location: logoutUrl, "cache-control": "no-store" },
181
+ });
182
+ };
183
+ }
184
+ /**
185
+ * Standardized `GET /api/sesion/yo` endpoint.
186
+ * Fail-closed: returns `{ autenticado: false }` with HTTP 200 and `cache-control: no-store` if unauthenticated or if D1 revalidation throws.
187
+ */
188
+ export function createSessionEndpoint(options) {
189
+ const cookieName = options.cookieName ?? "rs_session";
190
+ const localKey = options.localKey ?? "session";
191
+ return async function GET(event) {
192
+ const json = (body) => new Response(JSON.stringify(body), {
193
+ status: 200,
194
+ headers: {
195
+ "content-type": "application/json; charset=utf-8",
196
+ "cache-control": "no-store",
197
+ },
198
+ });
199
+ try {
200
+ let session = event.locals[localKey] ?? null;
201
+ if (!session) {
202
+ const secret = options.getSecret(event);
203
+ const raw = event.cookies.get(cookieName);
204
+ if (secret && raw) {
205
+ session = await verifySessionCookie(raw, {
206
+ secret,
207
+ namespace: options.namespace,
208
+ });
209
+ }
210
+ }
211
+ if (!session)
212
+ return json({ autenticado: false });
213
+ if (options.resolveProfile) {
214
+ const resolved = await options.resolveProfile(session, event);
215
+ return json(resolved ?? { autenticado: false });
216
+ }
217
+ const perfil = session.perfil ?? {};
218
+ const nombre = [perfil.nombre, perfil.apellido].filter(Boolean).join(" ").trim() || undefined;
219
+ return json({
220
+ autenticado: true,
221
+ email: typeof session.email === "string" ? session.email : undefined,
222
+ nombre,
223
+ foto: typeof session.foto === "string" ? session.foto : undefined,
224
+ rol: typeof session.rol === "string" ? session.rol : undefined,
225
+ es_admin: session.rol === "admin" || session.rol === "owner",
226
+ perfil,
227
+ });
228
+ }
229
+ catch {
230
+ return json({ autenticado: false });
231
+ }
232
+ };
233
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@rsanjur-dev/id",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "SDK oficial de RS ID (id.rsanjur.com): PKCE S256, sesión/identidad, cookies HMAC Web Crypto, SvelteKit, Svelte 5 y React.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/rsanjur-dev/rs-sdk.git",
10
+ "directory": "packages/id"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./core": {
25
+ "types": "./dist/core.d.ts",
26
+ "default": "./dist/core.js"
27
+ },
28
+ "./sveltekit": {
29
+ "types": "./dist/sveltekit.d.ts",
30
+ "default": "./dist/sveltekit.js"
31
+ },
32
+ "./svelte": {
33
+ "types": "./dist/svelte/index.d.ts",
34
+ "svelte": "./dist/svelte/index.js",
35
+ "default": "./dist/svelte/index.js"
36
+ },
37
+ "./react": {
38
+ "types": "./dist/react.d.ts",
39
+ "default": "./dist/react.js"
40
+ }
41
+ },
42
+ "scripts": {
43
+ "build": "svelte-package -i src -o dist",
44
+ "check": "svelte-check --tsconfig ./tsconfig.json"
45
+ },
46
+ "peerDependencies": {
47
+ "@rsanjur-dev/ui": "^1.0.0",
48
+ "@sveltejs/kit": "^2.0.0",
49
+ "react": "^18.0.0 || ^19.0.0",
50
+ "svelte": "^5.0.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@rsanjur-dev/ui": {
54
+ "optional": true
55
+ },
56
+ "@sveltejs/kit": {
57
+ "optional": true
58
+ },
59
+ "react": {
60
+ "optional": true
61
+ },
62
+ "svelte": {
63
+ "optional": true
64
+ }
65
+ }
66
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.