@bigso/auth-sdk 0.5.1 → 0.5.2

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,331 @@
1
+ import {
2
+ verifySignedPayload
3
+ } from "../chunk-5ECHA2VH.js";
4
+
5
+ // src/utils/crypto.ts
6
+ async function sha256Base64Url(input) {
7
+ const encoder = new TextEncoder();
8
+ const data = encoder.encode(input);
9
+ const digest = await crypto.subtle.digest("SHA-256", data);
10
+ return base64Url(new Uint8Array(digest));
11
+ }
12
+ function generateVerifier(length = 32) {
13
+ const array = new Uint8Array(length);
14
+ crypto.getRandomValues(array);
15
+ return base64Url(array);
16
+ }
17
+ function base64Url(bytes) {
18
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ }
20
+ function generateRandomId() {
21
+ return crypto.randomUUID();
22
+ }
23
+
24
+ // src/utils/events.ts
25
+ var EventEmitter = class {
26
+ constructor() {
27
+ this.events = {};
28
+ }
29
+ on(event, handler) {
30
+ if (!this.events[event]) this.events[event] = [];
31
+ this.events[event].push(handler);
32
+ }
33
+ off(event, handler) {
34
+ if (!this.events[event]) return;
35
+ this.events[event] = this.events[event].filter((h) => h !== handler);
36
+ }
37
+ emit(event, data) {
38
+ this.events[event]?.forEach((fn) => fn(data));
39
+ }
40
+ };
41
+
42
+ // src/browser/auth.ts
43
+ var BigsoAuth = class extends EventEmitter {
44
+ constructor(options) {
45
+ super();
46
+ this.authCompleted = false;
47
+ this.requestId = generateRandomId();
48
+ this.loginInProgress = false;
49
+ this.options = {
50
+ timeout: 5e3,
51
+ debug: false,
52
+ redirectUri: "",
53
+ tenantHint: "",
54
+ theme: "light",
55
+ ...options
56
+ };
57
+ }
58
+ async login() {
59
+ if (this.loginInProgress) {
60
+ this.debug("login() ya en curso, ignorando llamada duplicada");
61
+ return Promise.reject(new Error("Login already in progress"));
62
+ }
63
+ this.loginInProgress = true;
64
+ this.authCompleted = false;
65
+ const state = generateRandomId();
66
+ const nonce = generateRandomId();
67
+ const verifier = generateVerifier();
68
+ const requestId = this.requestId;
69
+ sessionStorage.setItem("sso_ctx", JSON.stringify({ state, nonce, verifier, requestId }));
70
+ this.createUI();
71
+ return new Promise((resolve, reject) => {
72
+ this.abortController = new AbortController();
73
+ const { signal } = this.abortController;
74
+ const cleanup = () => {
75
+ if (this.timeoutId) clearTimeout(this.timeoutId);
76
+ if (this.messageListener) window.removeEventListener("message", this.messageListener);
77
+ this.iframe?.remove();
78
+ this.iframe = void 0;
79
+ this.authCompleted = true;
80
+ this.loginInProgress = false;
81
+ };
82
+ this.messageListener = async (event) => {
83
+ if (event.origin !== this.options.ssoOrigin) {
84
+ this.debug("Ignorado mensaje de origen no autorizado:", event.origin);
85
+ return;
86
+ }
87
+ const msg = event.data;
88
+ this.debug("Mensaje recibido:", msg);
89
+ if (msg.requestId && msg.requestId !== requestId) {
90
+ this.debug("requestId no coincide, ignorado");
91
+ return;
92
+ }
93
+ if (msg.type === "sso-ready") {
94
+ this.debug("sso-ready recibido, iniciando timeout y enviando sso-init");
95
+ this.timeoutId = window.setTimeout(() => {
96
+ if (!this.authCompleted) {
97
+ this.debug("Timeout alcanzado, activando fallback");
98
+ this.closeUI();
99
+ cleanup();
100
+ this.emit("fallback");
101
+ window.location.href = this.buildFallbackUrl();
102
+ reject(new Error("Timeout"));
103
+ }
104
+ }, this.options.timeout);
105
+ const codeChallenge = await sha256Base64Url(verifier);
106
+ const initPayload = {
107
+ state,
108
+ nonce,
109
+ code_challenge: codeChallenge,
110
+ code_challenge_method: "S256",
111
+ origin: window.location.origin,
112
+ ...this.options.redirectUri && { redirect_uri: this.options.redirectUri },
113
+ ...this.options.tenantHint && { tenant_hint: this.options.tenantHint },
114
+ timeout_ms: this.options.timeout
115
+ };
116
+ this.iframe?.contentWindow?.postMessage({
117
+ v: "2.3",
118
+ source: "@app/widget",
119
+ type: "sso-init",
120
+ requestId: this.requestId,
121
+ payload: initPayload
122
+ }, this.options.ssoOrigin);
123
+ this.emit("ready");
124
+ return;
125
+ }
126
+ if (msg.type === "sso-success") {
127
+ this.debug("sso-success recibido");
128
+ clearTimeout(this.timeoutId);
129
+ try {
130
+ const payload = msg.payload;
131
+ const ctx = JSON.parse(sessionStorage.getItem("sso_ctx") || "{}");
132
+ if (payload.state !== ctx.state) {
133
+ throw new Error("Invalid state");
134
+ }
135
+ const decoded = await verifySignedPayload(
136
+ payload.signed_payload,
137
+ this.options.jwksUrl,
138
+ window.location.origin
139
+ );
140
+ if (decoded.nonce !== ctx.nonce) {
141
+ throw new Error("Invalid nonce");
142
+ }
143
+ this.debug("JWS v\xE1lido, payload:", decoded);
144
+ this.closeUI();
145
+ cleanup();
146
+ const result = {
147
+ code: decoded.code,
148
+ state: decoded.state || ctx.state,
149
+ nonce: ctx.nonce,
150
+ codeVerifier: ctx.verifier,
151
+ signed_payload: payload.signed_payload,
152
+ tenant: decoded.tenant,
153
+ jti: decoded.jti,
154
+ iss: decoded.iss,
155
+ aud: typeof decoded.aud === "string" ? decoded.aud : void 0,
156
+ exp: decoded.exp,
157
+ iat: decoded.iat
158
+ };
159
+ this.emit("success", result);
160
+ resolve(result);
161
+ } catch (err) {
162
+ this.debug("Error en sso-success:", err);
163
+ this.closeUI();
164
+ cleanup();
165
+ this.emit("error", err);
166
+ reject(err);
167
+ }
168
+ return;
169
+ }
170
+ if (msg.type === "sso-error") {
171
+ const errorPayload = msg.payload;
172
+ this.debug("sso-error recibido:", errorPayload);
173
+ clearTimeout(this.timeoutId);
174
+ this.closeUI();
175
+ cleanup();
176
+ if (errorPayload.code === "version_mismatch") {
177
+ this.emit("error", errorPayload);
178
+ window.location.href = this.buildFallbackUrl();
179
+ reject(new Error(`Version mismatch: expected ${errorPayload.expected_version}`));
180
+ } else {
181
+ this.emit("error", errorPayload);
182
+ reject(errorPayload);
183
+ }
184
+ }
185
+ if (msg.type === "sso-close") {
186
+ this.debug("sso-close recibido");
187
+ this.closeUI();
188
+ cleanup();
189
+ reject(new Error("Login cancelled by user"));
190
+ }
191
+ };
192
+ window.addEventListener("message", this.messageListener);
193
+ signal.addEventListener("abort", () => {
194
+ this.debug("Operaci\xF3n abortada");
195
+ this.closeUI();
196
+ cleanup();
197
+ reject(new Error("Login aborted"));
198
+ });
199
+ });
200
+ }
201
+ abort() {
202
+ this.abortController?.abort();
203
+ }
204
+ // ─── UI Management ───────────────────────────────────────────────
205
+ createUI() {
206
+ if (!this.hostEl) {
207
+ this.hostEl = document.createElement("div");
208
+ this.hostEl.id = "bigso-auth-host";
209
+ this.shadowRoot = this.hostEl.attachShadow({ mode: "open" });
210
+ const style = document.createElement("style");
211
+ style.textContent = this.getOverlayStyles();
212
+ this.shadowRoot.appendChild(style);
213
+ this.overlayEl = document.createElement("div");
214
+ this.overlayEl.className = "sso-overlay";
215
+ const closeBtn = document.createElement("button");
216
+ closeBtn.className = "sso-close-btn";
217
+ closeBtn.innerHTML = "×";
218
+ closeBtn.setAttribute("aria-label", "Cerrar modal");
219
+ closeBtn.addEventListener("click", () => this.abort());
220
+ this.overlayEl.appendChild(closeBtn);
221
+ this.overlayEl.addEventListener("click", (event) => {
222
+ if (event.target === this.overlayEl) {
223
+ this.abort();
224
+ }
225
+ });
226
+ this.shadowRoot.appendChild(this.overlayEl);
227
+ document.body.appendChild(this.hostEl);
228
+ }
229
+ this.iframe = document.createElement("iframe");
230
+ this.iframe.className = "sso-frame";
231
+ this.iframe.src = `${this.options.ssoOrigin}/auth/sign-in?v=2.3&client_id=${this.options.clientId}`;
232
+ this.iframe.setAttribute("title", "SSO Login");
233
+ this.overlayEl.appendChild(this.iframe);
234
+ this.debug("Iframe creado", this.iframe.src);
235
+ this.overlayEl.classList.remove("sso-closing");
236
+ this.overlayEl.style.display = "flex";
237
+ }
238
+ closeUI() {
239
+ if (!this.overlayEl || this.overlayEl.style.display === "none") return;
240
+ this.overlayEl.classList.add("sso-closing");
241
+ setTimeout(() => {
242
+ if (this.overlayEl) {
243
+ this.overlayEl.style.display = "none";
244
+ this.overlayEl.classList.remove("sso-closing");
245
+ }
246
+ }, 200);
247
+ }
248
+ getOverlayStyles() {
249
+ return `
250
+ .sso-overlay {
251
+ position: fixed;
252
+ inset: 0;
253
+ display: none;
254
+ justify-content: center;
255
+ align-items: center;
256
+ background: rgba(0, 0, 0, 0.6);
257
+ z-index: 999999;
258
+ backdrop-filter: blur(4px);
259
+ -webkit-backdrop-filter: blur(4px);
260
+ animation: fadeIn 0.2s ease;
261
+ }
262
+ .sso-frame {
263
+ width: 370px;
264
+ height: 350px;
265
+ border: none;
266
+ border-radius: 16px;
267
+ background: var(--card-bg, #fff);
268
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3);
269
+ animation: slideUp 0.3s ease;
270
+ }
271
+ @media (max-width: 480px), (max-height: 480px) {
272
+ .sso-frame {
273
+ width: 100%;
274
+ height: 100%;
275
+ border-radius: 0;
276
+ }
277
+ }
278
+ .sso-close-btn {
279
+ position: absolute;
280
+ top: 12px;
281
+ right: 12px;
282
+ width: 32px;
283
+ height: 32px;
284
+ background: rgba(0, 0, 0, 0.4);
285
+ color: white;
286
+ border: none;
287
+ border-radius: 50%;
288
+ font-size: 24px;
289
+ line-height: 1;
290
+ cursor: pointer;
291
+ display: flex;
292
+ align-items: center;
293
+ justify-content: center;
294
+ z-index: 1000000;
295
+ transition: background 0.2s;
296
+ }
297
+ .sso-close-btn:hover {
298
+ background: rgba(0, 0, 0, 0.8);
299
+ }
300
+ .sso-overlay.sso-closing {
301
+ animation: fadeOut 0.2s ease forwards;
302
+ }
303
+ .sso-overlay.sso-closing .sso-frame {
304
+ animation: slideDown 0.2s ease forwards;
305
+ }
306
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
307
+ @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
308
+ @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }
309
+ @keyframes slideDown { from { transform: translateY(0); opacity: 1; } to { transform: translateY(20px); opacity: 0; } }
310
+ `;
311
+ }
312
+ // ─── Helpers ──────────────────────────────────────────────────────
313
+ buildFallbackUrl() {
314
+ const url = new URL(this.options.ssoOrigin);
315
+ url.searchParams.set("app_id", this.options.clientId);
316
+ url.searchParams.set("redirect_uri", this.options.redirectUri || window.location.origin);
317
+ url.searchParams.set("response_type", "code");
318
+ url.searchParams.set("state", generateRandomId());
319
+ url.searchParams.set("code_challenge_method", "S256");
320
+ url.searchParams.set("client_id", this.options.clientId);
321
+ return url.toString();
322
+ }
323
+ debug(...args) {
324
+ if (this.options.debug) {
325
+ console.log("[BigsoAuth]", ...args);
326
+ }
327
+ }
328
+ };
329
+ export {
330
+ BigsoAuth
331
+ };
@@ -0,0 +1,32 @@
1
+ // src/utils/jws.ts
2
+ import { jwtVerify, createRemoteJWKSet } from "jose";
3
+ async function verifySignedPayload(token, jwksUrl, expectedAudience) {
4
+ const JWKS = createRemoteJWKSet(new URL(jwksUrl));
5
+ const { payload } = await jwtVerify(token, JWKS, {
6
+ audience: expectedAudience
7
+ });
8
+ return payload;
9
+ }
10
+ async function verifyAccessToken(accessToken, jwksUrl) {
11
+ const JWKS = createRemoteJWKSet(new URL(jwksUrl));
12
+ const { payload } = await jwtVerify(accessToken, JWKS);
13
+ if (!payload.sub || !payload.jti) {
14
+ throw new Error("Invalid token structure: missing sub or jti");
15
+ }
16
+ return {
17
+ sub: payload.sub,
18
+ jti: payload.jti,
19
+ iss: payload.iss,
20
+ aud: payload.aud || "",
21
+ exp: payload.exp,
22
+ iat: payload.iat,
23
+ tenants: payload.tenants || [],
24
+ systemRole: payload.systemRole || "user",
25
+ deviceFingerprint: payload.deviceFingerprint
26
+ };
27
+ }
28
+
29
+ export {
30
+ verifySignedPayload,
31
+ verifyAccessToken
32
+ };
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/express/index.ts
21
+ var express_exports = {};
22
+ __export(express_exports, {
23
+ createSsoAuthRouter: () => createSsoAuthRouter,
24
+ createSsoSyncRouter: () => createSsoSyncRouter,
25
+ ssoAuthMiddleware: () => ssoAuthMiddleware,
26
+ ssoSyncGuardMiddleware: () => ssoSyncGuardMiddleware
27
+ });
28
+ module.exports = __toCommonJS(express_exports);
29
+
30
+ // src/express/middlewares/ssoAuth.ts
31
+ function ssoAuthMiddleware(options) {
32
+ return async (req, res, next) => {
33
+ try {
34
+ const authHeader = req.headers.authorization;
35
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
36
+ res.status(401).json({ error: "Missing access token" });
37
+ return;
38
+ }
39
+ const accessToken = authHeader.substring(7);
40
+ const payload = await options.ssoClient.validateAccessToken(accessToken);
41
+ if (!payload) {
42
+ res.status(401).json({ error: "Invalid or expired access token" });
43
+ return;
44
+ }
45
+ const primaryTenant = payload.tenants?.[0];
46
+ req.user = {
47
+ userId: payload.sub,
48
+ email: "",
49
+ firstName: "",
50
+ lastName: ""
51
+ };
52
+ req.tenant = primaryTenant || void 0;
53
+ req.tokenPayload = payload;
54
+ next();
55
+ } catch (error) {
56
+ console.error("[BigsoAuthSDK] Authentication Middleware Error:", error instanceof Error ? error.message : error);
57
+ res.status(401).json({ error: "Authentication failed" });
58
+ }
59
+ };
60
+ }
61
+
62
+ // src/express/middlewares/ssoSyncGuard.ts
63
+ var import_dns = require("dns");
64
+ function ssoSyncGuardMiddleware(options) {
65
+ const isProduction = options.isProduction ?? process.env.NODE_ENV === "production";
66
+ return async (req, res, next) => {
67
+ try {
68
+ const isSecure = req.secure || req.headers["x-forwarded-proto"] === "https";
69
+ if (!isSecure && isProduction) {
70
+ console.warn("\u26A0\uFE0F [BigsoAuthSDK] Blocked non-HTTPS sync request");
71
+ res.status(403).json({ error: "HTTPS required" });
72
+ return;
73
+ }
74
+ const clientIp = req.ip || req.socket.remoteAddress || "";
75
+ const isLoopback = clientIp === "::1" || clientIp === "127.0.0.1" || clientIp === "::ffff:127.0.0.1";
76
+ if (!isProduction && isLoopback) {
77
+ return next();
78
+ }
79
+ const ssoUrl = new URL(options.ssoBackendUrl);
80
+ const ssoHostname = ssoUrl.hostname;
81
+ const ssoIps = await import_dns.promises.resolve4(ssoHostname).catch(() => []);
82
+ const cleanClientIp = clientIp.replace(/^.*:/, "");
83
+ const isPrivateIp = cleanClientIp.startsWith("10.") || cleanClientIp.startsWith("192.168.") || cleanClientIp.startsWith("172.") && parseInt(cleanClientIp.split(".")[1], 10) >= 16 && parseInt(cleanClientIp.split(".")[1], 10) <= 31;
84
+ if (!ssoIps.includes(cleanClientIp) && !isPrivateIp) {
85
+ console.warn(`\u26D4\uFE0F [BigsoAuthSDK] Blocked sync request from unauthorized IP: ${clientIp}`);
86
+ res.status(403).json({ error: "Unauthorized origin" });
87
+ return;
88
+ }
89
+ next();
90
+ } catch (error) {
91
+ console.error("\u274C [BigsoAuthSDK] Sync Guard Validation Error:", error instanceof Error ? error.message : error);
92
+ res.status(500).json({ error: "Security validation failed" });
93
+ }
94
+ };
95
+ }
96
+
97
+ // src/express/routes/createSsoAuthRouter.ts
98
+ var import_express = require("express");
99
+ function createSsoAuthRouter(options) {
100
+ const router = (0, import_express.Router)();
101
+ router.post("/exchange", async (req, res) => {
102
+ try {
103
+ const { code, codeVerifier } = req.body;
104
+ if (!code || !codeVerifier) {
105
+ res.status(400).json({ error: "code and codeVerifier are required" });
106
+ return;
107
+ }
108
+ const ssoResponse = await options.ssoClient.exchangeCode(code, codeVerifier);
109
+ if (options.onLoginSuccess) {
110
+ await options.onLoginSuccess(ssoResponse);
111
+ }
112
+ res.json({
113
+ success: true,
114
+ tokens: ssoResponse.tokens,
115
+ user: ssoResponse.user,
116
+ tenant: ssoResponse.tenant
117
+ });
118
+ } catch (error) {
119
+ console.error("[BigsoAuthSDK] Error exchanging code:", error.message);
120
+ res.status(401).json({ error: error.message || "Failed to exchange authorization code" });
121
+ }
122
+ });
123
+ router.post("/exchange-v2", async (req, res) => {
124
+ try {
125
+ const { payload } = req.body;
126
+ if (!payload) {
127
+ res.status(400).json({ error: "Signed payload is required" });
128
+ return;
129
+ }
130
+ const verified = await options.ssoClient.verifySignedPayload(payload, options.frontendUrl);
131
+ if (!verified.code) {
132
+ res.status(400).json({ error: "No authorization code found in payload" });
133
+ return;
134
+ }
135
+ const codeVerifier = verified.code_verifier;
136
+ if (!codeVerifier) {
137
+ res.status(400).json({ error: "code_verifier is required for PKCE exchange" });
138
+ return;
139
+ }
140
+ const ssoResponse = await options.ssoClient.exchangeCode(verified.code, codeVerifier);
141
+ if (options.onLoginSuccess) {
142
+ await options.onLoginSuccess(ssoResponse);
143
+ }
144
+ res.json({
145
+ success: true,
146
+ tokens: ssoResponse.tokens,
147
+ user: ssoResponse.user,
148
+ tenant: ssoResponse.tenant
149
+ });
150
+ } catch (error) {
151
+ console.error("[BigsoAuthSDK] Error exchanging v2 payload:", error.message);
152
+ res.status(401).json({ error: error.message || "Failed to verify signed payload" });
153
+ }
154
+ });
155
+ router.get("/session", ssoAuthMiddleware({ ssoClient: options.ssoClient }), (req, res) => {
156
+ res.set("Cache-Control", "no-store, no-cache, must-revalidate, private");
157
+ res.set("Pragma", "no-cache");
158
+ res.set("Expires", "0");
159
+ res.json({
160
+ success: true,
161
+ user: req.user,
162
+ tenant: req.tenant,
163
+ tokenPayload: req.tokenPayload
164
+ });
165
+ });
166
+ router.post("/refresh", async (req, res) => {
167
+ try {
168
+ const ssoResponse = await options.ssoClient.refreshTokens();
169
+ res.json({
170
+ success: true,
171
+ tokens: ssoResponse.tokens
172
+ });
173
+ } catch (error) {
174
+ console.error("[BigsoAuthSDK] Error refreshing tokens:", error.message);
175
+ res.status(401).json({ error: error.message || "Failed to refresh tokens" });
176
+ }
177
+ });
178
+ router.post("/logout", ssoAuthMiddleware({ ssoClient: options.ssoClient }), async (req, res) => {
179
+ try {
180
+ const accessToken = req.headers.authorization?.substring(7) || "";
181
+ const { revokeAll = false } = req.body || {};
182
+ await options.ssoClient.logout(accessToken, revokeAll);
183
+ if (options.onLogout) {
184
+ await options.onLogout(accessToken);
185
+ }
186
+ res.json({ success: true, message: "Logged out" });
187
+ } catch (error) {
188
+ console.warn("[BigsoAuthSDK] Failed to logout in SSO Backend.", error.message);
189
+ res.json({ success: true, message: "Logged out (backend revocation failed)" });
190
+ }
191
+ });
192
+ return router;
193
+ }
194
+
195
+ // src/express/routes/createSsoSyncRouter.ts
196
+ var import_express2 = require("express");
197
+ function createSsoSyncRouter(options) {
198
+ const router = (0, import_express2.Router)();
199
+ router.get("/resources", ssoSyncGuardMiddleware({
200
+ ssoBackendUrl: options.ssoBackendUrl,
201
+ isProduction: options.isProduction
202
+ }), (req, res) => {
203
+ try {
204
+ res.json({
205
+ success: true,
206
+ resources: options.resources,
207
+ meta: {
208
+ appId: options.appId,
209
+ count: options.resources.length,
210
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
211
+ }
212
+ });
213
+ } catch (error) {
214
+ console.error("\u274C [BigsoAuthSDK] Error in sync endpoint:", error.message);
215
+ res.status(500).json({ error: error.message });
216
+ }
217
+ });
218
+ return router;
219
+ }
220
+ // Annotate the CommonJS export names for ESM import in node:
221
+ 0 && (module.exports = {
222
+ createSsoAuthRouter,
223
+ createSsoSyncRouter,
224
+ ssoAuthMiddleware,
225
+ ssoSyncGuardMiddleware
226
+ });
@@ -0,0 +1,46 @@
1
+ import { Request, Response, NextFunction, Router } from 'express';
2
+ import { BigsoSsoClient } from '../node/index.cjs';
3
+ import { S as SsoJwtTenant, b as SsoTokenPayload, V as V2ExchangeResponse } from '../types-D5BaCbus.cjs';
4
+
5
+ interface SsoAuthMiddlewareOptions {
6
+ ssoClient: BigsoSsoClient;
7
+ }
8
+ declare global {
9
+ namespace Express {
10
+ interface Request {
11
+ user?: {
12
+ userId: string;
13
+ email: string;
14
+ firstName: string;
15
+ lastName: string;
16
+ };
17
+ tenant?: SsoJwtTenant;
18
+ tokenPayload?: SsoTokenPayload;
19
+ }
20
+ }
21
+ }
22
+ declare function ssoAuthMiddleware(options: SsoAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
23
+
24
+ interface SsoSyncGuardOptions {
25
+ ssoBackendUrl: string;
26
+ isProduction?: boolean;
27
+ }
28
+ declare function ssoSyncGuardMiddleware(options: SsoSyncGuardOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
29
+
30
+ interface CreateSsoAuthRouterOptions {
31
+ ssoClient: BigsoSsoClient;
32
+ frontendUrl: string;
33
+ onLoginSuccess?: (session: V2ExchangeResponse) => void | Promise<void>;
34
+ onLogout?: (accessToken: string) => void | Promise<void>;
35
+ }
36
+ declare function createSsoAuthRouter(options: CreateSsoAuthRouterOptions): Router;
37
+
38
+ interface SsoSyncRouterOptions {
39
+ resources: any[];
40
+ appId: string;
41
+ ssoBackendUrl: string;
42
+ isProduction?: boolean;
43
+ }
44
+ declare function createSsoSyncRouter(options: SsoSyncRouterOptions): Router;
45
+
46
+ export { type CreateSsoAuthRouterOptions, type SsoAuthMiddlewareOptions, type SsoSyncGuardOptions, type SsoSyncRouterOptions, createSsoAuthRouter, createSsoSyncRouter, ssoAuthMiddleware, ssoSyncGuardMiddleware };
@@ -0,0 +1,46 @@
1
+ import { Request, Response, NextFunction, Router } from 'express';
2
+ import { BigsoSsoClient } from '../node/index.js';
3
+ import { S as SsoJwtTenant, b as SsoTokenPayload, V as V2ExchangeResponse } from '../types-D5BaCbus.js';
4
+
5
+ interface SsoAuthMiddlewareOptions {
6
+ ssoClient: BigsoSsoClient;
7
+ }
8
+ declare global {
9
+ namespace Express {
10
+ interface Request {
11
+ user?: {
12
+ userId: string;
13
+ email: string;
14
+ firstName: string;
15
+ lastName: string;
16
+ };
17
+ tenant?: SsoJwtTenant;
18
+ tokenPayload?: SsoTokenPayload;
19
+ }
20
+ }
21
+ }
22
+ declare function ssoAuthMiddleware(options: SsoAuthMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
23
+
24
+ interface SsoSyncGuardOptions {
25
+ ssoBackendUrl: string;
26
+ isProduction?: boolean;
27
+ }
28
+ declare function ssoSyncGuardMiddleware(options: SsoSyncGuardOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
29
+
30
+ interface CreateSsoAuthRouterOptions {
31
+ ssoClient: BigsoSsoClient;
32
+ frontendUrl: string;
33
+ onLoginSuccess?: (session: V2ExchangeResponse) => void | Promise<void>;
34
+ onLogout?: (accessToken: string) => void | Promise<void>;
35
+ }
36
+ declare function createSsoAuthRouter(options: CreateSsoAuthRouterOptions): Router;
37
+
38
+ interface SsoSyncRouterOptions {
39
+ resources: any[];
40
+ appId: string;
41
+ ssoBackendUrl: string;
42
+ isProduction?: boolean;
43
+ }
44
+ declare function createSsoSyncRouter(options: SsoSyncRouterOptions): Router;
45
+
46
+ export { type CreateSsoAuthRouterOptions, type SsoAuthMiddlewareOptions, type SsoSyncGuardOptions, type SsoSyncRouterOptions, createSsoAuthRouter, createSsoSyncRouter, ssoAuthMiddleware, ssoSyncGuardMiddleware };