@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.
@@ -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.1.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.