@rsanjur-dev/connect 0.0.0-stage → 0.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/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @rsanjur-dev/connect
2
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.
3
+ Estándar **RS Connect** para servidores MCP de RSanjur en Cloudflare Workers. Es la base de RS Brain y de cualquier app nueva (Contabell, Comibox, Carreras…) que quiera conectarse a Claude o ChatGPT.
4
+
5
+ | Pieza | Qué hace |
6
+ |---|---|
7
+ | `createRsidMcpAuth` | `/authorize` + `/callback` sobre `@cloudflare/workers-oauth-provider`: consentimiento, SSO registrado de RS ID con PKCE S256 y token MCP con `props.userId = cuenta_id`. RS ID aplica Accesos en el canje. |
8
+ | `createAccessGuard` | Chequeo en vivo (`checkServerAccess` de `@rsanjur-dev/id/core`) con caché de 60 s: una revocación en RS ID → Accesos corta el acceso en segundos. Si RS ID se cae, mantiene 10 min solo a quien ya estaba permitido. |
9
+ | `registerLogin` / `isActiveAccount` + `ACCOUNTS_SCHEMA_SQL` | Tabla `accounts`: quién entró y bloqueo local inmediato. |
10
+ | `verifyPersonalToken` + `SERVICE_TOKENS_SCHEMA_SQL` | Tokens personales (solo SHA-256 en D1) para agentes sin navegador. |
11
+
12
+ **Regla de oro:** cada dato lleva su `owner_id` y cada consulta filtra por él. Nadie, ni el admin, lee datos de otra cuenta.
13
+
14
+ ## Uso (Worker)
15
+
16
+ ```ts
17
+ import OAuthProvider from "@cloudflare/workers-oauth-provider";
18
+ import { createAccessGuard, createRsidMcpAuth, isActiveAccount, registerLogin, verifyPersonalToken } from "@rsanjur-dev/connect";
19
+
20
+ const auth = createRsidMcpAuth({
21
+ appName: "Mi App", clientId: "mi-app", scope: ["mi-app"],
22
+ consentText: "Podrá <strong>leer</strong> tus datos (solo los tuyos).",
23
+ onAccount: (cuentaId, env) => registerLogin((env as Env).DB, cuentaId),
24
+ });
25
+
26
+ // En cada petición a /mcp: cuenta activa localmente y aprobada en vivo por RS ID.
27
+ const allowed = async (env: Env, id: string) =>
28
+ (await isActiveAccount(env.DB, id)) &&
29
+ (await createAccessGuard({ clientId: "mi-app", serverKey: env.RSID_SERVER_KEY }).isAllowed(id));
30
+ ```
31
+
32
+ Crea la guardia una vez por isolate (fuera del handler) para aprovechar la caché.
33
+
34
+ ## Registro en RS ID
35
+
36
+ 1. Cliente SSO en `rs-id/src/lib/server/sso-clientes.js` con callback exacto `https://<app>/callback`, PKCE y `requiresApprovalDefault: true`.
37
+ 2. SHA-256 de la clave de servidor `rsk_…` en `rs-id/src/lib/server/acceso-servidor.js`. La clave en claro va solo como secreto `RSID_SERVER_KEY` del Worker.
38
+ 3. Agrega la app a `consumers.json` para recibir las actualizaciones de este paquete.
@@ -0,0 +1,26 @@
1
+ export interface AccessGuardOptions {
2
+ clientId: string;
3
+ /** Clave de servidor `rsk_…` registrada en RS ID (secreto del Worker). */
4
+ serverKey: string;
5
+ baseUrl?: string;
6
+ fetcher?: typeof fetch;
7
+ /** Cuánto se reutiliza una respuesta de RS ID. Por defecto 60 s. */
8
+ ttlMs?: number;
9
+ /**
10
+ * Si RS ID no responde, se sigue aceptando a quien estaba permitido hace menos de esto.
11
+ * Por defecto 10 min. Una cuenta revocada o nunca vista se rechaza siempre.
12
+ */
13
+ graceMs?: number;
14
+ now?: () => number;
15
+ }
16
+ export interface AccessGuard {
17
+ /** true si la cuenta sigue aprobada en RS ID → Accesos para esta app. */
18
+ isAllowed(cuentaId: string): Promise<boolean>;
19
+ /** Olvida la caché (p. ej. tras un cambio de acceso conocido). */
20
+ forget(cuentaId?: string): void;
21
+ }
22
+ /**
23
+ * Chequeo en vivo de Accesos con caché corta por isolate. Así una revocación en RS ID
24
+ * corta el acceso del servidor en segundos, aunque sus tokens sigan vigentes.
25
+ */
26
+ export declare function createAccessGuard(options: AccessGuardOptions): AccessGuard;
package/dist/access.js ADDED
@@ -0,0 +1,45 @@
1
+ import { RsidAccessError, checkServerAccess } from "@rsanjur-dev/id/core";
2
+ /**
3
+ * Chequeo en vivo de Accesos con caché corta por isolate. Así una revocación en RS ID
4
+ * corta el acceso del servidor en segundos, aunque sus tokens sigan vigentes.
5
+ */
6
+ export function createAccessGuard(options) {
7
+ const ttl = options.ttlMs ?? 60_000;
8
+ const grace = options.graceMs ?? 600_000;
9
+ const now = options.now ?? Date.now;
10
+ const cache = new Map();
11
+ return {
12
+ async isAllowed(cuentaId) {
13
+ if (!cuentaId)
14
+ return false;
15
+ const hit = cache.get(cuentaId);
16
+ if (hit && now() - hit.at < ttl)
17
+ return hit.allowed;
18
+ let result;
19
+ try {
20
+ result = await checkServerAccess({
21
+ clientId: options.clientId,
22
+ cuentaId,
23
+ serverKey: options.serverKey,
24
+ baseUrl: options.baseUrl,
25
+ fetcher: options.fetcher,
26
+ });
27
+ }
28
+ catch (error) {
29
+ if (error instanceof RsidAccessError && error.kind === "unavailable") {
30
+ // RS ID caído: solo se mantiene a quien estaba permitido hace poco.
31
+ return Boolean(hit?.allowed && now() - hit.at < grace);
32
+ }
33
+ throw error;
34
+ }
35
+ cache.set(cuentaId, { allowed: result.permitido, at: now() });
36
+ return result.permitido;
37
+ },
38
+ forget(cuentaId) {
39
+ if (cuentaId)
40
+ cache.delete(cuentaId);
41
+ else
42
+ cache.clear();
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,11 @@
1
+ import type { D1Like } from "./d1.js";
2
+ /**
3
+ * Cuentas de una app RS Connect. Quién puede entrar lo decide RS ID (Accesos); esta tabla
4
+ * recuerda quién entró y permite bloquear una cuenta al instante (`status = 'blocked'`).
5
+ * Nunca da acceso a datos ajenos: cada cuenta solo ve lo suyo (`owner_id`).
6
+ */
7
+ export declare const ACCOUNTS_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS accounts (\n owner_id TEXT PRIMARY KEY,\n status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'blocked')),\n created_at TEXT NOT NULL,\n last_login_at TEXT\n);";
8
+ /** Registra un inicio de sesión aprobado por RS ID. Devuelve false si la cuenta está bloqueada. */
9
+ export declare function registerLogin(db: D1Like, ownerId: string, now?: Date): Promise<boolean>;
10
+ /** true solo si la cuenta ya entró por RS ID y no está bloqueada localmente. */
11
+ export declare function isActiveAccount(db: D1Like, ownerId: string): Promise<boolean>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Cuentas de una app RS Connect. Quién puede entrar lo decide RS ID (Accesos); esta tabla
3
+ * recuerda quién entró y permite bloquear una cuenta al instante (`status = 'blocked'`).
4
+ * Nunca da acceso a datos ajenos: cada cuenta solo ve lo suyo (`owner_id`).
5
+ */
6
+ export const ACCOUNTS_SCHEMA_SQL = `CREATE TABLE IF NOT EXISTS accounts (
7
+ owner_id TEXT PRIMARY KEY,
8
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'blocked')),
9
+ created_at TEXT NOT NULL,
10
+ last_login_at TEXT
11
+ );`;
12
+ /** Registra un inicio de sesión aprobado por RS ID. Devuelve false si la cuenta está bloqueada. */
13
+ export async function registerLogin(db, ownerId, now = new Date()) {
14
+ if (!ownerId)
15
+ return false;
16
+ const at = now.toISOString();
17
+ const row = await db
18
+ .prepare(`INSERT INTO accounts (owner_id, status, created_at, last_login_at) VALUES (?, 'active', ?, ?)
19
+ ON CONFLICT (owner_id) DO UPDATE SET last_login_at = excluded.last_login_at
20
+ RETURNING status`)
21
+ .bind(ownerId, at, at)
22
+ .first();
23
+ return row?.status === "active";
24
+ }
25
+ /** true solo si la cuenta ya entró por RS ID y no está bloqueada localmente. */
26
+ export async function isActiveAccount(db, ownerId) {
27
+ if (!ownerId)
28
+ return false;
29
+ const row = await db.prepare("SELECT status FROM accounts WHERE owner_id = ?").bind(ownerId).first();
30
+ return row?.status === "active";
31
+ }
package/dist/d1.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** Interfaz mínima de D1 que usa RS Connect (compatible con `D1Database` de Workers). */
2
+ export interface D1Like {
3
+ prepare(query: string): {
4
+ bind(...values: unknown[]): {
5
+ first<T = Record<string, unknown>>(): Promise<T | null>;
6
+ run(): Promise<unknown>;
7
+ };
8
+ };
9
+ }
package/dist/d1.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @rsanjur-dev/connect — estándar RS Connect para servidores MCP de RSanjur en Cloudflare Workers.
3
+ *
4
+ * - Login con RS ID (OAuth 2.1 + PKCE) sobre `@cloudflare/workers-oauth-provider`.
5
+ * - Accesos en vivo: una revocación en RS ID corta el acceso en segundos.
6
+ * - Cuentas con bloqueo inmediato y tokens personales (PAT).
7
+ * - Regla de oro: cada dato lleva su `owner_id`; nadie, ni el admin, lee datos de otra cuenta.
8
+ */
9
+ export type { D1Like } from "./d1.js";
10
+ export { ACCOUNTS_SCHEMA_SQL, isActiveAccount, registerLogin } from "./accounts.js";
11
+ export { SERVICE_TOKENS_SCHEMA_SQL, generatePersonalToken, isPersonalToken, sha256Hex, verifyPersonalToken, } from "./tokens.js";
12
+ export { createAccessGuard, type AccessGuard, type AccessGuardOptions } from "./access.js";
13
+ export { createRsidMcpAuth, page, type RsidMcpAuthOptions } from "./rsid-oauth.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { ACCOUNTS_SCHEMA_SQL, isActiveAccount, registerLogin } from "./accounts.js";
2
+ export { SERVICE_TOKENS_SCHEMA_SQL, generatePersonalToken, isPersonalToken, sha256Hex, verifyPersonalToken, } from "./tokens.js";
3
+ export { createAccessGuard } from "./access.js";
4
+ export { createRsidMcpAuth, page } from "./rsid-oauth.js";
@@ -0,0 +1,32 @@
1
+ import { type OAuthHelpers } from "@cloudflare/workers-oauth-provider";
2
+ export interface RsidMcpAuthOptions {
3
+ /** Nombre visible de la app, p. ej. "RS Brain". */
4
+ appName: string;
5
+ /** client_id registrado en RS ID (SSO con PKCE, callback exacto `<app>/callback`). */
6
+ clientId: string;
7
+ /** Alcances que se conceden al cliente MCP. */
8
+ scope: string[];
9
+ /** Qué podrá hacer la app conectada, en una frase para la pantalla de consentimiento. */
10
+ consentText: string;
11
+ /** Origen de RS ID. Por defecto https://id.rsanjur.com. */
12
+ baseUrl?: string;
13
+ fetcher?: typeof fetch;
14
+ /**
15
+ * Se llama con la cuenta que RS ID aprobó. Devuelve false para negar la entrada
16
+ * (p. ej. cuenta bloqueada localmente). Es el lugar para `registerLogin`.
17
+ */
18
+ onAccount?: (cuentaId: string, env: unknown) => Promise<boolean>;
19
+ }
20
+ export declare function page(appName: string, title: string, body: string, status?: number, headers?: Headers): Response;
21
+ /**
22
+ * Login de RS ID para un servidor MCP con `@cloudflare/workers-oauth-provider`:
23
+ * `/authorize` muestra el consentimiento y manda al SSO registrado de RS ID (PKCE S256,
24
+ * sin redirect_uri); `/callback` canjea el código (RS ID aplica Accesos) y emite el token MCP
25
+ * con `props.userId = cuenta_id`.
26
+ */
27
+ export declare function createRsidMcpAuth(options: RsidMcpAuthOptions): {
28
+ /** GET/POST /authorize */
29
+ authorize(request: Request, oauth: OAuthHelpers): Promise<Response>;
30
+ /** GET /callback */
31
+ callback(request: Request, oauth: OAuthHelpers, env?: unknown): Promise<Response>;
32
+ };
@@ -0,0 +1,157 @@
1
+ import { AuthorizationError, CimdFetchError, authorizationErrorRedirect, } from "@cloudflare/workers-oauth-provider";
2
+ import { RsidExchangeError, exchangeCode, toBase64Url } from "@rsanjur-dev/id/core";
3
+ const escape = (value) => value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
4
+ export function page(appName, title, body, status = 200, headers = new Headers()) {
5
+ headers.set("Content-Type", "text/html; charset=utf-8");
6
+ headers.set("Cache-Control", "no-store");
7
+ headers.set("X-Frame-Options", "DENY");
8
+ headers.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' https:; frame-ancestors 'none'");
9
+ const html = `<!doctype html>
10
+ <html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
11
+ <title>${escape(title)} · ${escape(appName)}</title>
12
+ <style>
13
+ :root{color-scheme:light dark;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}
14
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:Canvas;color:CanvasText}
15
+ main{max-width:26rem;margin:1.5rem;padding:1.75rem;border:1px solid color-mix(in srgb,CanvasText 15%,transparent);border-radius:1rem}
16
+ h1{font-size:1.35rem;margin:0 0 .75rem}
17
+ p{line-height:1.5;margin:.5rem 0}
18
+ .warn{padding:.75rem;border-radius:.6rem;background:color-mix(in srgb,orange 18%,transparent)}
19
+ .row{display:flex;gap:.75rem;margin-top:1.25rem}
20
+ button{flex:1;font:inherit;font-size:1rem;min-height:3rem;border-radius:.7rem;border:1px solid color-mix(in srgb,CanvasText 25%,transparent);background:transparent;color:inherit;cursor:pointer}
21
+ button.primary{background:#2563eb;border-color:#2563eb;color:#fff;font-weight:600}
22
+ code{font-size:.9em;word-break:break-all}
23
+ </style></head><body><main>${body}</main></body></html>`;
24
+ return new Response(html, { status, headers });
25
+ }
26
+ async function s256(verifier) {
27
+ return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
28
+ }
29
+ /**
30
+ * Login de RS ID para un servidor MCP con `@cloudflare/workers-oauth-provider`:
31
+ * `/authorize` muestra el consentimiento y manda al SSO registrado de RS ID (PKCE S256,
32
+ * sin redirect_uri); `/callback` canjea el código (RS ID aplica Accesos) y emite el token MCP
33
+ * con `props.userId = cuenta_id`.
34
+ */
35
+ export function createRsidMcpAuth(options) {
36
+ const { appName } = options;
37
+ const view = (title, body, status, headers) => page(appName, title, body, status, headers);
38
+ function renderAuthError(error) {
39
+ if (error instanceof AuthorizationError && error.redirectTo)
40
+ return Response.redirect(error.redirectTo, 302);
41
+ if (error instanceof AuthorizationError || error instanceof CimdFetchError) {
42
+ const message = error instanceof AuthorizationError ? error.description : "No se pudo verificar esta app.";
43
+ return view("No se pudo autorizar", `<h1>No se pudo autorizar</h1><p>${escape(message || "Solicitud inválida.")}</p><p>Vuelve a conectar ${escape(appName)} desde tu app.</p>`, 400);
44
+ }
45
+ throw error;
46
+ }
47
+ function consentPage(details, handle, headers) {
48
+ const origin = details.clientDomain
49
+ ? `Publicada por <strong>${escape(details.clientDomain)}</strong>.`
50
+ : "Esta app se registró sola; su nombre no está verificado.";
51
+ const loopback = details.redirectIsLoopback
52
+ ? `<p class="warn"><strong>El acceso irá a una app en tu computadora.</strong> Continúa solo si acabas de iniciar la conexión desde ella.</p>`
53
+ : "";
54
+ return view("Autorizar acceso", `<h1>¿Permitir que ${escape(details.clientName)} use tu ${escape(appName)}?</h1>
55
+ <p>${origin}</p>
56
+ <p>${options.consentText} El acceso se enviará a <strong>${escape(details.redirectHost)}</strong>.</p>
57
+ ${loopback}
58
+ <p>Después vas a entrar con tu cuenta RS ID.</p>
59
+ <form method="post">
60
+ <input type="hidden" name="handle" value="${escape(handle)}">
61
+ <div class="row">
62
+ <button name="decision" value="deny">Cancelar</button>
63
+ <button class="primary" name="decision" value="approve">Permitir</button>
64
+ </div>
65
+ </form>`, 200, headers);
66
+ }
67
+ return {
68
+ /** GET/POST /authorize */
69
+ async authorize(request, oauth) {
70
+ try {
71
+ if (request.method === "GET") {
72
+ const authRequest = await oauth.parseAuthRequest(request);
73
+ const details = await oauth.describeConsent(authRequest);
74
+ const consent = await oauth.beginConsent(authRequest);
75
+ return consentPage(details, consent.handle, consent.headers);
76
+ }
77
+ if (request.method === "POST") {
78
+ const form = await request.formData();
79
+ const handle = String(form.get("handle") ?? "");
80
+ if (form.get("decision") !== "approve") {
81
+ const denied = await oauth.denyConsent(request, handle);
82
+ return new Response(null, { status: 302, headers: denied.headers });
83
+ }
84
+ const approved = await oauth.approveConsent(request, handle, { scope: options.scope });
85
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
86
+ const verifier = toBase64Url(bytes);
87
+ const { state, headers } = await oauth.beginUpstream(approved.request, { data: { verifier }, headers: approved.headers });
88
+ const upstream = new URL("/api/auth/authorize", options.baseUrl ?? "https://id.rsanjur.com");
89
+ upstream.search = new URLSearchParams({
90
+ client_id: options.clientId,
91
+ state,
92
+ code_challenge: await s256(verifier),
93
+ code_challenge_method: "S256",
94
+ }).toString();
95
+ headers.set("Location", upstream.toString());
96
+ return new Response(null, { status: 302, headers });
97
+ }
98
+ return new Response("Method Not Allowed", { status: 405, headers: { Allow: "GET, POST" } });
99
+ }
100
+ catch (error) {
101
+ return renderAuthError(error);
102
+ }
103
+ },
104
+ /** GET /callback */
105
+ async callback(request, oauth, env) {
106
+ let finished;
107
+ try {
108
+ finished = await oauth.finishUpstream(request);
109
+ }
110
+ catch (error) {
111
+ return renderAuthError(error);
112
+ }
113
+ const { request: original, data, headers } = finished;
114
+ const params = new URL(request.url).searchParams;
115
+ const code = params.get("code");
116
+ const state = params.get("state") ?? "";
117
+ if (params.get("error") || !code) {
118
+ headers.set("Location", authorizationErrorRedirect(original, "access_denied"));
119
+ return new Response(null, { status: 302, headers });
120
+ }
121
+ let cuentaId;
122
+ try {
123
+ const account = await exchangeCode({
124
+ clientId: options.clientId,
125
+ code,
126
+ state,
127
+ verifier: data.verifier,
128
+ baseUrl: options.baseUrl,
129
+ fetcher: options.fetcher,
130
+ });
131
+ cuentaId = account.cuentaId;
132
+ }
133
+ catch (error) {
134
+ if (error instanceof RsidExchangeError && error.kind === "pending") {
135
+ return view("Acceso pendiente", `<h1>Tu acceso a ${escape(appName)} está pendiente</h1><p>El dueño debe aprobar tu cuenta en <strong>Accesos</strong> de RS ID. Después vuelve a conectar.</p>`, 403, headers);
136
+ }
137
+ if (error instanceof RsidExchangeError && error.kind === "revoked") {
138
+ return view("Acceso revocado", `<h1>Tu acceso a ${escape(appName)} fue revocado</h1><p>Habla con el dueño si crees que es un error.</p>`, 403, headers);
139
+ }
140
+ console.error("rsid canje failed", error instanceof RsidExchangeError ? `${error.kind} ${error.status ?? ""}` : "unknown");
141
+ return view("Error con RS ID", "<h1>No se pudo completar el inicio de sesión</h1><p>RS ID no aceptó el código. Vuelve a intentarlo.</p>", 502, headers);
142
+ }
143
+ if (options.onAccount && !(await options.onAccount(cuentaId, env))) {
144
+ return view("Acceso bloqueado", `<h1>Esta cuenta está bloqueada en ${escape(appName)}</h1><p>Si crees que es un error, habla con el dueño.</p>`, 403, headers);
145
+ }
146
+ const { redirectTo } = await oauth.completeAuthorization({
147
+ request: original,
148
+ userId: cuentaId,
149
+ metadata: { label: "RS ID" },
150
+ scope: options.scope,
151
+ props: { userId: cuentaId },
152
+ });
153
+ headers.set("Location", redirectTo);
154
+ return new Response(null, { status: 302, headers });
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,20 @@
1
+ import type { D1Like } from "./d1.js";
2
+ /**
3
+ * Tokens personales (PAT) para scripts y agentes sin navegador: `Authorization: Bearer <prefijo>…`.
4
+ * Solo se guarda el SHA-256; el token en claro se muestra una sola vez al crearlo.
5
+ */
6
+ export declare const SERVICE_TOKENS_SCHEMA_SQL = "CREATE TABLE IF NOT EXISTS service_tokens (\n id TEXT PRIMARY KEY,\n owner_id TEXT NOT NULL,\n name TEXT NOT NULL,\n token_hash TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n expires_at TEXT,\n revoked_at TEXT,\n last_used_at TEXT\n);";
7
+ export declare function sha256Hex(text: string): Promise<string>;
8
+ /** true si `token` tiene la forma `<prefix>` + 32–128 caracteres base64url. */
9
+ export declare function isPersonalToken(token: string, prefix: string): boolean;
10
+ /** Crea un token nuevo con el prefijo dado; guarda su hash con `hashPersonalToken`. */
11
+ export declare function generatePersonalToken(prefix: string): string;
12
+ /**
13
+ * Devuelve el dueño del token si es válido, vigente, no revocado y `isAllowed(owner)` lo acepta
14
+ * (p. ej. cuenta activa y aprobada en RS ID); si no, null.
15
+ */
16
+ export declare function verifyPersonalToken(db: D1Like, token: string, options: {
17
+ prefix: string;
18
+ isAllowed: (ownerId: string) => Promise<boolean>;
19
+ now?: Date;
20
+ }): Promise<string | null>;
package/dist/tokens.js ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Tokens personales (PAT) para scripts y agentes sin navegador: `Authorization: Bearer <prefijo>…`.
3
+ * Solo se guarda el SHA-256; el token en claro se muestra una sola vez al crearlo.
4
+ */
5
+ export const SERVICE_TOKENS_SCHEMA_SQL = `CREATE TABLE IF NOT EXISTS service_tokens (
6
+ id TEXT PRIMARY KEY,
7
+ owner_id TEXT NOT NULL,
8
+ name TEXT NOT NULL,
9
+ token_hash TEXT NOT NULL UNIQUE,
10
+ created_at TEXT NOT NULL,
11
+ expires_at TEXT,
12
+ revoked_at TEXT,
13
+ last_used_at TEXT
14
+ );`;
15
+ export async function sha256Hex(text) {
16
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
17
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
18
+ }
19
+ const escapeRe = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20
+ /** true si `token` tiene la forma `<prefix>` + 32–128 caracteres base64url. */
21
+ export function isPersonalToken(token, prefix) {
22
+ return new RegExp(`^${escapeRe(prefix)}[A-Za-z0-9_-]{32,128}$`).test(token);
23
+ }
24
+ /** Crea un token nuevo con el prefijo dado; guarda su hash con `hashPersonalToken`. */
25
+ export function generatePersonalToken(prefix) {
26
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
27
+ let binary = "";
28
+ for (const byte of bytes)
29
+ binary += String.fromCharCode(byte);
30
+ return prefix + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
31
+ }
32
+ /**
33
+ * Devuelve el dueño del token si es válido, vigente, no revocado y `isAllowed(owner)` lo acepta
34
+ * (p. ej. cuenta activa y aprobada en RS ID); si no, null.
35
+ */
36
+ export async function verifyPersonalToken(db, token, options) {
37
+ if (!isPersonalToken(token, options.prefix))
38
+ return null;
39
+ const row = await db
40
+ .prepare("SELECT id, owner_id, expires_at, revoked_at FROM service_tokens WHERE token_hash = ?")
41
+ .bind(await sha256Hex(token))
42
+ .first();
43
+ const now = options.now ?? new Date();
44
+ if (!row || row.revoked_at)
45
+ return null;
46
+ if (row.expires_at && Date.parse(row.expires_at) <= now.getTime())
47
+ return null;
48
+ if (!(await options.isAllowed(row.owner_id)))
49
+ return null;
50
+ await db.prepare("UPDATE service_tokens SET last_used_at = ? WHERE id = ?").bind(now.toISOString(), row.id).run();
51
+ return row.owner_id;
52
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@rsanjur-dev/connect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "SDK oficial de RS Connect: servidores MCP de RSanjur con login RS ID (OAuth 2.1 + PKCE), Accesos en vivo, cuentas con bloqueo, tokens personales y datos aislados por dueño. Cloudflare Workers.",
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/connect"
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
+ },
25
+ "scripts": {
26
+ "build": "svelte-package -i src -o dist",
27
+ "check": "tsc --noEmit -p tsconfig.json"
28
+ },
29
+ "dependencies": {
30
+ "@rsanjur-dev/id": "^1.1.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@cloudflare/workers-oauth-provider": "^1.4.0"
34
+ },
35
+ "devDependencies": {
36
+ "@cloudflare/workers-oauth-provider": "^1.4.0"
37
+ }
38
+ }