@innvoid/getmarket-sdk 0.1.11 → 0.1.12
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/{chunk-WK3P3MDA.js → chunk-SLB6QUUN.js} +24 -48
- package/dist/chunk-SLB6QUUN.js.map +1 -0
- package/dist/index.cjs +23 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/middlewares/index.cjs +23 -47
- package/dist/middlewares/index.cjs.map +1 -1
- package/dist/middlewares/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WK3P3MDA.js.map +0 -1
|
@@ -361,9 +361,7 @@ function readPublicKey() {
|
|
|
361
361
|
}
|
|
362
362
|
const envKey = publicKeyEnv.replace(/\\n/g, "\n").trim();
|
|
363
363
|
if (envKey) return envKey;
|
|
364
|
-
throw new Error(
|
|
365
|
-
"Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)"
|
|
366
|
-
);
|
|
364
|
+
throw new Error("Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)");
|
|
367
365
|
}
|
|
368
366
|
function verifyBackendJwtRS2562(raw) {
|
|
369
367
|
const publicKey = readPublicKey();
|
|
@@ -379,20 +377,11 @@ function normalizeUid2(v) {
|
|
|
379
377
|
const s = String(v ?? "").trim();
|
|
380
378
|
return s.length ? s : null;
|
|
381
379
|
}
|
|
382
|
-
function
|
|
383
|
-
|
|
384
|
-
const
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
if (typeof item === "string") {
|
|
388
|
-
const s2 = item.trim();
|
|
389
|
-
if (s2) out.push(s2);
|
|
390
|
-
continue;
|
|
391
|
-
}
|
|
392
|
-
const s = String(item.code || item.name || "").trim();
|
|
393
|
-
if (s) out.push(s);
|
|
394
|
-
}
|
|
395
|
-
return Array.from(new Set(out));
|
|
380
|
+
function deriveCompanyBranch(decoded, companyUid, branchUid) {
|
|
381
|
+
const companiesFromToken = Array.isArray(decoded?.companies) ? decoded.companies : [];
|
|
382
|
+
const company = decoded?.company ?? (companyUid ? companiesFromToken.find((c) => c?.uid === companyUid) : null) ?? null;
|
|
383
|
+
const branch = decoded?.branch ?? (branchUid && company?.branches ? (company.branches || []).find((b) => b?.uid === branchUid) : null) ?? null;
|
|
384
|
+
return { companiesFromToken, company, branch };
|
|
396
385
|
}
|
|
397
386
|
function extractEmployeeUid(decoded) {
|
|
398
387
|
const direct = normalizeUid2(decoded?.employee_uid);
|
|
@@ -410,12 +399,6 @@ function extractCustomerUid(decoded) {
|
|
|
410
399
|
const m = /^cus:(.+)$/i.exec(sub);
|
|
411
400
|
return m?.[1] ? normalizeUid2(m[1]) : null;
|
|
412
401
|
}
|
|
413
|
-
function deriveCompanyBranch(decoded, companyUid, branchUid) {
|
|
414
|
-
const companiesFromToken = Array.isArray(decoded?.companies) ? decoded.companies : [];
|
|
415
|
-
const company = decoded?.company ?? (companyUid ? companiesFromToken.find((c) => c?.uid === companyUid) : null) ?? null;
|
|
416
|
-
const branch = decoded?.branch ?? (branchUid && company?.branches ? (company.branches || []).find((b) => b?.uid === branchUid) : null) ?? null;
|
|
417
|
-
return { companiesFromToken, company, branch };
|
|
418
|
-
}
|
|
419
402
|
function createAuthMiddleware2(opts) {
|
|
420
403
|
const { subject, allowFirebaseIdToken = false } = opts;
|
|
421
404
|
return async (req, res, next) => {
|
|
@@ -441,10 +424,9 @@ function createAuthMiddleware2(opts) {
|
|
|
441
424
|
companies: companiesFromToken,
|
|
442
425
|
company,
|
|
443
426
|
branch,
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
denied_permissions: normalizeCodes(decoded?.denied_permissions, "perm"),
|
|
427
|
+
roles: Array.isArray(decoded?.roles) ? decoded.roles : [],
|
|
428
|
+
permissions: Array.isArray(decoded?.permissions) ? decoded.permissions : [],
|
|
429
|
+
denied_permissions: Array.isArray(decoded?.denied_permissions) ? decoded.denied_permissions : [],
|
|
448
430
|
session: {
|
|
449
431
|
jti: decoded?.jti,
|
|
450
432
|
device_id: decoded?.device_id,
|
|
@@ -452,35 +434,29 @@ function createAuthMiddleware2(opts) {
|
|
|
452
434
|
}
|
|
453
435
|
};
|
|
454
436
|
if (subject === "employee") {
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
if (employeeEmbedded) {
|
|
458
|
-
ctx.employee = employeeUid ? { ...employeeEmbedded, uid: employeeEmbedded?.uid ?? employeeUid } : employeeEmbedded;
|
|
459
|
-
} else if (employeeUid) {
|
|
460
|
-
ctx.employee = { uid: employeeUid };
|
|
461
|
-
} else {
|
|
437
|
+
const employee_uid = extractEmployeeUid(decoded);
|
|
438
|
+
if (!employee_uid) {
|
|
462
439
|
return res.status(401).json({
|
|
463
440
|
ok: false,
|
|
464
|
-
code: "
|
|
465
|
-
message: "
|
|
441
|
+
code: "AUTH_EMPLOYEE_UID_MISSING",
|
|
442
|
+
message: "employee_uid missing in token (expected employee_uid or sub=emp:<uid>)"
|
|
466
443
|
});
|
|
467
444
|
}
|
|
468
|
-
ctx.employee_uid =
|
|
445
|
+
ctx.employee_uid = employee_uid;
|
|
446
|
+
const embedded = decoded?.employee ?? decoded?.user ?? null;
|
|
447
|
+
ctx.employee = embedded && typeof embedded === "object" ? embedded : { uid: employee_uid, email: decoded?.email ?? null };
|
|
469
448
|
} else {
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
if (customerEmbedded) {
|
|
473
|
-
ctx.customer = customerUid ? { ...customerEmbedded, uid: customerEmbedded?.uid ?? customerUid } : customerEmbedded;
|
|
474
|
-
} else if (customerUid) {
|
|
475
|
-
ctx.customer = { uid: customerUid };
|
|
476
|
-
} else {
|
|
449
|
+
const customer_uid = extractCustomerUid(decoded);
|
|
450
|
+
if (!customer_uid) {
|
|
477
451
|
return res.status(401).json({
|
|
478
452
|
ok: false,
|
|
479
|
-
code: "
|
|
480
|
-
message: "
|
|
453
|
+
code: "AUTH_CUSTOMER_UID_MISSING",
|
|
454
|
+
message: "customer_uid missing in token (expected customer_uid or sub=cus:<uid>)"
|
|
481
455
|
});
|
|
482
456
|
}
|
|
483
|
-
ctx.customer_uid =
|
|
457
|
+
ctx.customer_uid = customer_uid;
|
|
458
|
+
const embedded = decoded?.customer ?? null;
|
|
459
|
+
ctx.customer = embedded && typeof embedded === "object" ? embedded : { uid: customer_uid };
|
|
484
460
|
}
|
|
485
461
|
req.auth = ctx;
|
|
486
462
|
return next();
|
|
@@ -672,4 +648,4 @@ export {
|
|
|
672
648
|
allowSysAdminOrRolesOrAnyPermission,
|
|
673
649
|
allowAuthAdminOrPerm
|
|
674
650
|
};
|
|
675
|
-
//# sourceMappingURL=chunk-
|
|
651
|
+
//# sourceMappingURL=chunk-SLB6QUUN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middlewares/parseHeaders.ts","../src/middlewares/internalAuth.ts","../src/middlewares/respond.ts","../src/middlewares/authorization.ts","../src/auth/jwt.ts","../src/auth/middleware.ts","../src/auth/authentication.ts","../src/middlewares/guards.ts"],"sourcesContent":["// sdk/src/middlewares/parseHeaders.ts\nimport type {Request, Response, NextFunction} from \"express\";\nimport {getRequestContextFromHeaders} from \"../headers\";\n\n/**\n * ✅ NO-LEGACY / ESTÁNDAR:\n * - Lee SOLO x-company y x-branch (UIDs planos)\n * - Setea req.context = { company_uid, branch_uid }\n * - NO toca req.auth (auth lo setea authentication/requireAuth)\n */\nexport default function parseHeaders(req: Request, _res: Response, next: NextFunction) {\n (req as any).context = getRequestContextFromHeaders(req.headers as any);\n next();\n}\n","import type {Request, Response, NextFunction} from \"express\";\nimport fs from \"fs\";\nimport crypto from \"crypto\";\nimport {sendError} from \"./respond\";\nimport {HEADER_INTERNAL_API_KEY} from \"../headers\";\n\nfunction readSecretFile(path?: string): string | null {\n if (!path) return null;\n try {\n const v = fs.readFileSync(path, \"utf8\").trim();\n return v.length ? v : null;\n } catch {\n return null;\n }\n}\n\nfunction splitKeys(v?: string | null): string[] {\n if (!v) return [];\n return v.split(\",\").map((s) => s.trim()).filter(Boolean);\n}\n\nfunction getExpectedKeys(): string[] {\n const fileKey = readSecretFile(process.env.INTERNAL_API_KEY_FILE);\n const envKey = (process.env.INTERNAL_API_KEY || \"\").trim();\n const raw = fileKey || envKey;\n return splitKeys(raw);\n}\n\nfunction extractToken(req: Request): string | null {\n const apiKey = (req.header(HEADER_INTERNAL_API_KEY) || \"\").trim();\n return apiKey || null;\n}\n\nfunction safeEquals(a: string, b: string): boolean {\n const aa = Buffer.from(a);\n const bb = Buffer.from(b);\n if (aa.length !== bb.length) return false;\n return crypto.timingSafeEqual(aa, bb);\n}\n\nexport default function internalAuth(req: Request, res: Response, next: NextFunction) {\n const token = extractToken(req);\n\n if (!token) {\n return sendError(req, res, 401, \"UNAUTHORIZED\", `Missing internal api key (${HEADER_INTERNAL_API_KEY})`);\n }\n\n const expectedKeys = getExpectedKeys();\n if (expectedKeys.length === 0) {\n return sendError(\n req,\n res,\n 500,\n \"MISCONFIGURED_INTERNAL_AUTH\",\n \"Internal api key not configured (INTERNAL_API_KEY or INTERNAL_API_KEY_FILE)\"\n );\n }\n\n const ok = expectedKeys.some((k) => safeEquals(token, k));\n if (!ok) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Invalid internal api key\");\n }\n\n return next();\n}\n","import type {Request, Response} from \"express\";\n\nexport function sendOk<T>(_req: Request, res: Response, data: T, statusCode = 200) {\n return res.status(statusCode).json({ok: true, data, requestId: res.locals?.requestId ?? null});\n}\n\nexport function sendError(\n _req: Request,\n res: Response,\n statusCode: number,\n code: string,\n message: string,\n details?: any\n) {\n return res.status(statusCode).json({\n ok: false,\n error: {code, message, ...(details !== undefined ? {details} : {})},\n requestId: res.locals?.requestId ?? null,\n });\n}\n","// packages/sdk/src/middlewares/authorization.ts\nimport type {Request, Response, NextFunction} from \"express\";\nimport {sendError} from \"./respond\";\n\ntype AuthRole = string | { code?: string; name?: string };\ntype AuthPermission = string | { code?: string; name?: string };\n\ntype AuthShape = {\n roles?: AuthRole[];\n permissions?: AuthPermission[];\n denied_permissions?: AuthPermission[];\n};\n\nfunction getAuth(req: Request): AuthShape {\n return ((req as any).auth ?? {}) as AuthShape;\n}\n\nfunction normalizeCode(v: any): string | null {\n if (!v) return null;\n if (typeof v === \"string\") return v;\n if (typeof v === \"object\") return v.code || v.name || null;\n return null;\n}\n\nfunction rolesSet(auth: AuthShape): Set<string> {\n const out = new Set<string>();\n for (const r of auth.roles || []) {\n const c = normalizeCode(r);\n if (c) out.add(c);\n }\n return out;\n}\n\nfunction permsSet(list?: AuthPermission[]): Set<string> {\n const out = new Set<string>();\n for (const p of list || []) {\n const c = normalizeCode(p);\n if (c) out.add(c);\n }\n return out;\n}\n\n/**\n * 401 si no existe req.auth (contexto auth).\n * Útil para proteger rutas donde SIEMPRE debe existir auth.\n */\nexport function requireAuthContext() {\n return (req: Request, res: Response, next: NextFunction) => {\n if (!(req as any).auth) {\n return sendError(req, res, 401, \"UNAUTHORIZED\", \"Missing auth context\");\n }\n return next();\n };\n}\n\n/**\n * Helper: SYS_ADMIN bypass (por defecto activo)\n */\nfunction isSysAdmin(auth: AuthShape, sysAdminRole: string) {\n const have = rolesSet(auth);\n return have.has(sysAdminRole);\n}\n\n/**\n * Requiere TODOS los permisos indicados.\n * Regla: denied_permissions siempre gana sobre permissions.\n *\n * options:\n * - sysAdminBypass: default true\n * - sysAdminRole: default \"SYS_ADMIN\"\n */\nexport function requirePermissions(\n perms: string[],\n options?: { sysAdminBypass?: boolean; sysAdminRole?: string }\n) {\n const sysAdminBypass = options?.sysAdminBypass !== false;\n const sysAdminRole = options?.sysAdminRole || \"SYS_ADMIN\";\n\n return (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n\n if (sysAdminBypass && isSysAdmin(auth, sysAdminRole)) return next();\n\n const allow = permsSet(auth.permissions);\n const deny = permsSet(auth.denied_permissions);\n\n // deny gana siempre\n for (const p of perms) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied permission: ${p}`, {\n denied: p,\n });\n }\n }\n\n const missing = perms.filter((p) => !allow.has(p));\n if (missing.length) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Missing permissions\", {\n missing,\n mode: \"ALL\",\n });\n }\n\n return next();\n };\n}\n\n/**\n * Requiere AL MENOS 1 permiso de la lista (ANY/OR).\n * Regla: denied_permissions siempre gana.\n */\nexport function requireAnyPermission(\n perms: string[],\n options?: { sysAdminBypass?: boolean; sysAdminRole?: string }\n) {\n const sysAdminBypass = options?.sysAdminBypass !== false;\n const sysAdminRole = options?.sysAdminRole || \"SYS_ADMIN\";\n\n return (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n\n if (sysAdminBypass && isSysAdmin(auth, sysAdminRole)) return next();\n\n const allow = permsSet(auth.permissions);\n const deny = permsSet(auth.denied_permissions);\n\n // deny gana siempre (si alguno requerido está denegado explícitamente)\n for (const p of perms) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied permission: ${p}`, {\n denied: p,\n });\n }\n }\n\n const ok = perms.some((p) => allow.has(p));\n if (!ok) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Permission denied\", {\n required: perms,\n mode: \"ANY\",\n });\n }\n\n return next();\n };\n}\n\n/**\n * Requiere al menos 1 rol (ANY/OR).\n * options:\n * - sysAdminBypass: default true\n * - sysAdminRole: default \"SYS_ADMIN\"\n */\nexport function requireRoles(\n roles: string[],\n options?: { sysAdminBypass?: boolean; sysAdminRole?: string }\n) {\n const sysAdminBypass = options?.sysAdminBypass !== false;\n const sysAdminRole = options?.sysAdminRole || \"SYS_ADMIN\";\n\n return (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n\n // SYS_ADMIN bypass aplica también aquí\n if (sysAdminBypass && isSysAdmin(auth, sysAdminRole)) return next();\n\n const have = rolesSet(auth);\n if (!roles.some((r) => have.has(r))) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Role not allowed\", {\n required: roles,\n mode: \"ANY\",\n });\n }\n\n return next();\n };\n}\n\n/**\n * Requiere (roles ANY) OR (permissions ANY).\n * deny_permissions siempre gana sobre permissions.\n */\nexport function requireRolesOrAnyPermission(\n roles: string[],\n perms: string[],\n options?: { sysAdminBypass?: boolean; sysAdminRole?: string }\n) {\n const sysAdminBypass = options?.sysAdminBypass !== false;\n const sysAdminRole = options?.sysAdminRole || \"SYS_ADMIN\";\n\n return (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n\n if (sysAdminBypass && isSysAdmin(auth, sysAdminRole)) return next();\n\n const haveRoles = rolesSet(auth);\n const allow = permsSet(auth.permissions);\n const deny = permsSet(auth.denied_permissions);\n\n // deny gana siempre (si cualquiera de los permisos evaluados está denegado explícitamente)\n for (const p of perms) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied permission: ${p}`, {\n denied: p,\n });\n }\n }\n\n const okRole = roles.some((r) => haveRoles.has(r));\n const okPerm = perms.some((p) => allow.has(p));\n\n if (!okRole && !okPerm) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Access denied\", {\n roles,\n permissions: perms,\n mode: \"ROLES_OR_PERMS_ANY\",\n });\n }\n\n return next();\n };\n}\n","import fs from \"fs\";\nimport jwt, {JwtPayload} from \"jsonwebtoken\";\n\nfunction readFileIfExists(path?: string): string | null {\n if (!path) return null;\n try {\n const v = fs.readFileSync(path, \"utf8\").trim();\n return v.length ? v : null;\n } catch {\n return null;\n }\n}\n\n/**\n * ✅ Keys viven en getmarket-stack:\n * - JWT_PUBLIC_KEY_PATH=/run/secrets/jwtRS256.key.pub (recomendado)\n * - fallback env AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY\n */\nexport function readRs256PublicKey(): string {\n const fromFile = readFileIfExists(process.env.JWT_PUBLIC_KEY_PATH);\n if (fromFile) return fromFile;\n\n const fromEnv = String(process.env.AUTH_JWT_PUBLIC_KEY || process.env.AUTH_RSA_PUBLIC_KEY || \"\")\n .replace(/\\\\n/g, \"\\n\")\n .trim();\n\n if (fromEnv) return fromEnv;\n\n throw new Error(\"Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)\");\n}\n\nexport function verifyBackendJwtRS256(raw: string): JwtPayload {\n const publicKey = readRs256PublicKey();\n\n const audience = process.env.JWT_AUDIENCE || process.env.AUTH_JWT_AUDIENCE || \"getmarket.api\";\n const issuer = process.env.JWT_ISSUER || process.env.AUTH_JWT_ISSUER || \"getmarket-auth\";\n\n // ✅ SOLO RS256\n return jwt.verify(raw, publicKey, {\n algorithms: [\"RS256\"],\n audience,\n issuer,\n }) as JwtPayload;\n}\n","import type {NextFunction, Response} from \"express\";\nimport {verifyBackendJwtRS256} from \"./jwt\";\nimport type {AuthContext, AuthMiddlewareOptions} from \"./types\";\n\nfunction getBearerToken(req: any): string | null {\n const auth = String(req.headers?.authorization || \"\");\n if (!auth.startsWith(\"Bearer \")) return null;\n const token = auth.slice(7).trim();\n return token.length ? token : null;\n}\n\nfunction normalizeUid(v: any): string | null {\n const s = String(v ?? \"\").trim();\n return s.length ? s : null;\n}\n\n/**\n * ✅ Middleware estándar:\n * - Solo Authorization: Bearer\n * - Solo RS256\n * - Cero legacy\n * - Hidrata vía hook (OBLIGATORIO)\n */\nexport function createAuthMiddleware(opts: AuthMiddlewareOptions) {\n const {subject, allowFirebaseIdToken = false, requireSubject = true, hydrate} = opts;\n\n return async (req: any, res: Response, next: NextFunction) => {\n const token = getBearerToken(req);\n if (!token) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_MISSING_TOKEN\",\n message: \"Missing Authorization Bearer token\",\n });\n }\n\n // Contexto desde parseHeaders (SDK) -> req.context\n const headerCtx = (req as any).context || {};\n const company_uid = normalizeUid(headerCtx.company_uid);\n const branch_uid = normalizeUid(headerCtx.branch_uid);\n\n // 1) RS256 backend JWT\n try {\n const decoded: any = verifyBackendJwtRS256(token);\n\n const baseCtx: AuthContext = {\n tokenType: \"backend\",\n subject,\n company_uid: company_uid ?? undefined,\n branch_uid: branch_uid ?? undefined,\n roles: Array.isArray(decoded?.roles) ? decoded.roles : [],\n permissions: Array.isArray(decoded?.permissions) ? decoded.permissions : [],\n denied_permissions: Array.isArray(decoded?.denied_permissions) ? decoded.denied_permissions : [],\n session: {\n jti: decoded?.jti,\n device_id: decoded?.device_id,\n expires_at: decoded?.exp,\n },\n };\n\n // ✅ hydrate obligatorio\n const hydrated = await hydrate({decoded, req, subject, company_uid, branch_uid});\n Object.assign(baseCtx, hydrated);\n\n if (requireSubject) {\n if (subject === \"employee\" && !baseCtx.employee) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_EMPLOYEE_NOT_FOUND\",\n message: \"Employee not resolved by hydrator\",\n });\n }\n if (subject === \"customer\" && !baseCtx.customer) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_CUSTOMER_NOT_FOUND\",\n message: \"Customer not resolved by hydrator\",\n });\n }\n }\n\n (req as any).auth = baseCtx;\n return next();\n } catch {\n // 2) Firebase opcional\n if (!allowFirebaseIdToken) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_INVALID_TOKEN\",\n message: \"Invalid or expired token\",\n });\n }\n\n try {\n const {default: admin} = await import(\"firebase-admin\");\n const firebaseDecoded = await admin.auth().verifyIdToken(token);\n\n if (firebaseDecoded.email && firebaseDecoded.email_verified === false) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_EMAIL_NOT_VERIFIED\",\n message: \"Email not verified\",\n });\n }\n\n (req as any).auth = {\n tokenType: \"backend\",\n subject,\n firebase: firebaseDecoded,\n company_uid: company_uid ?? undefined,\n branch_uid: branch_uid ?? undefined,\n companies: [],\n roles: [],\n permissions: [],\n denied_permissions: [],\n } satisfies AuthContext;\n\n return next();\n } catch {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_INVALID_TOKEN\",\n message: \"Invalid or expired token\",\n });\n }\n }\n };\n}\n","// packages/sdk/src/auth/authentication.ts\nimport type {NextFunction, Response} from \"express\";\nimport admin from \"firebase-admin\";\nimport jwt, {JwtPayload} from \"jsonwebtoken\";\nimport fs from \"fs\";\n\ntype Subject = \"employee\" | \"customer\";\ntype TokenType = \"backend\";\n\nexport interface AuthContext {\n tokenType: TokenType;\n subject: Subject;\n\n // ✅ UID-first canonical\n employee_uid?: string;\n customer_uid?: string;\n\n // Opcional (puede venir embebido o ser ref mínimo)\n employee?: any;\n customer?: any;\n\n company_uid?: string;\n branch_uid?: string;\n\n company?: any;\n branch?: any;\n companies?: any[];\n\n roles?: any[];\n permissions?: any[];\n denied_permissions?: any[];\n\n session?: { jti?: string; device_id?: string; expires_at?: number };\n firebase?: admin.auth.DecodedIdToken;\n}\n\n/**\n * ✅ ÚNICO estándar:\n * - Authorization: Bearer <token>\n */\nfunction getBearerToken(req: any): string | null {\n const auth = String(req.headers?.authorization || \"\");\n if (!auth.startsWith(\"Bearer \")) return null;\n const token = auth.slice(7).trim();\n return token.length ? token : null;\n}\n\nfunction readPublicKey(): string {\n const publicKeyPath = process.env.JWT_PUBLIC_KEY_PATH;\n const publicKeyEnv = process.env.AUTH_JWT_PUBLIC_KEY || process.env.AUTH_RSA_PUBLIC_KEY || \"\";\n\n if (publicKeyPath) {\n const v = fs.readFileSync(publicKeyPath, \"utf8\").trim();\n if (v) return v;\n }\n\n const envKey = publicKeyEnv.replace(/\\\\n/g, \"\\n\").trim();\n if (envKey) return envKey;\n\n throw new Error(\"Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)\");\n}\n\nfunction verifyBackendJwtRS256(raw: string): JwtPayload {\n const publicKey = readPublicKey();\n const audience = process.env.JWT_AUDIENCE || process.env.AUTH_JWT_AUDIENCE || \"getmarket.api\";\n const issuer = process.env.JWT_ISSUER || process.env.AUTH_JWT_ISSUER || \"getmarket-auth\";\n\n return jwt.verify(raw, publicKey, {\n algorithms: [\"RS256\"],\n audience,\n issuer,\n }) as JwtPayload;\n}\n\nfunction normalizeUid(v: any): string | null {\n const s = String(v ?? \"\").trim();\n return s.length ? s : null;\n}\n\nfunction deriveCompanyBranch(decoded: any, companyUid: string | null, branchUid: string | null) {\n const companiesFromToken = Array.isArray(decoded?.companies) ? decoded.companies : [];\n\n const company =\n decoded?.company ??\n (companyUid ? companiesFromToken.find((c: any) => c?.uid === companyUid) : null) ??\n null;\n\n const branch =\n decoded?.branch ??\n (branchUid && company?.branches ? (company.branches || []).find((b: any) => b?.uid === branchUid) : null) ??\n null;\n\n return {companiesFromToken, company, branch};\n}\n\n/**\n * ✅ UID-first extractors\n * - decoded.employee_uid / decoded.customer_uid\n * - decoded.sub = \"emp:<uid>\" / \"cus:<uid>\"\n */\nfunction extractEmployeeUid(decoded: any): string | null {\n const direct = normalizeUid(decoded?.employee_uid);\n if (direct) return direct;\n\n const sub = normalizeUid(decoded?.sub);\n if (!sub) return null;\n\n const m = /^emp:(.+)$/i.exec(sub);\n return m?.[1] ? normalizeUid(m[1]) : null;\n}\n\nfunction extractCustomerUid(decoded: any): string | null {\n const direct = normalizeUid(decoded?.customer_uid);\n if (direct) return direct;\n\n const sub = normalizeUid(decoded?.sub);\n if (!sub) return null;\n\n const m = /^cus:(.+)$/i.exec(sub);\n return m?.[1] ? normalizeUid(m[1]) : null;\n}\n\nexport function createAuthMiddleware(opts: { subject: Subject; allowFirebaseIdToken?: boolean }) {\n const {subject, allowFirebaseIdToken = false} = opts;\n\n return async (req: any, res: Response, next: NextFunction) => {\n const token = getBearerToken(req);\n if (!token) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_MISSING_TOKEN\",\n message: \"Missing Authorization Bearer token\",\n });\n }\n\n // 1) Backend JWT RS256\n try {\n const decoded: any = verifyBackendJwtRS256(token);\n\n const headerCtx = (req as any).context || {};\n const companyUid = normalizeUid(headerCtx.company_uid);\n const branchUid = normalizeUid(headerCtx.branch_uid);\n\n const {companiesFromToken, company, branch} = deriveCompanyBranch(decoded, companyUid, branchUid);\n\n const ctx: AuthContext = {\n tokenType: \"backend\",\n subject,\n\n company_uid: companyUid ?? undefined,\n branch_uid: branchUid ?? undefined,\n\n companies: companiesFromToken,\n company,\n branch,\n\n roles: Array.isArray(decoded?.roles) ? decoded.roles : [],\n permissions: Array.isArray(decoded?.permissions) ? decoded.permissions : [],\n denied_permissions: Array.isArray(decoded?.denied_permissions) ? decoded.denied_permissions : [],\n\n session: {\n jti: decoded?.jti,\n device_id: decoded?.device_id,\n expires_at: decoded?.exp,\n },\n };\n\n if (subject === \"employee\") {\n const employee_uid = extractEmployeeUid(decoded);\n if (!employee_uid) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_EMPLOYEE_UID_MISSING\",\n message: \"employee_uid missing in token (expected employee_uid or sub=emp:<uid>)\",\n });\n }\n ctx.employee_uid = employee_uid;\n\n // ✅ employee embebido es opcional; si no viene, dejamos ref mínimo\n const embedded = decoded?.employee ?? decoded?.user ?? null;\n ctx.employee = embedded && typeof embedded === \"object\"\n ? embedded\n : {uid: employee_uid, email: decoded?.email ?? null};\n } else {\n const customer_uid = extractCustomerUid(decoded);\n if (!customer_uid) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_CUSTOMER_UID_MISSING\",\n message: \"customer_uid missing in token (expected customer_uid or sub=cus:<uid>)\",\n });\n }\n ctx.customer_uid = customer_uid;\n\n const embedded = decoded?.customer ?? null;\n ctx.customer = embedded && typeof embedded === \"object\"\n ? embedded\n : {uid: customer_uid};\n }\n\n req.auth = ctx;\n return next();\n } catch {\n // 2) Firebase opcional\n if (!allowFirebaseIdToken) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_INVALID_TOKEN\",\n message: \"Invalid or expired token\",\n });\n }\n\n try {\n const firebaseDecoded = await admin.auth().verifyIdToken(token);\n\n if (firebaseDecoded.email && firebaseDecoded.email_verified === false) {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_EMAIL_NOT_VERIFIED\",\n message: \"Email not verified\",\n });\n }\n\n const headerCtx = (req as any).context || {};\n const companyUid = normalizeUid(headerCtx.company_uid);\n const branchUid = normalizeUid(headerCtx.branch_uid);\n\n req.auth = {\n tokenType: \"backend\",\n subject,\n firebase: firebaseDecoded,\n company_uid: companyUid ?? undefined,\n branch_uid: branchUid ?? undefined,\n companies: [],\n roles: [],\n permissions: [],\n denied_permissions: [],\n };\n\n return next();\n } catch {\n return res.status(401).json({\n ok: false,\n code: \"AUTH_INVALID_TOKEN\",\n message: \"Invalid or expired token\",\n });\n }\n }\n };\n}\n\nexport const authEmployeeRequired = createAuthMiddleware({subject: \"employee\", allowFirebaseIdToken: false});\nexport const authCustomerRequired = createAuthMiddleware({subject: \"customer\", allowFirebaseIdToken: false});\nexport const authEmployeeAllowFirebase = createAuthMiddleware({subject: \"employee\", allowFirebaseIdToken: true});\nexport const authCustomerAllowFirebase = createAuthMiddleware({subject: \"customer\", allowFirebaseIdToken: true});\n","// packages/sdk/src/middlewares/guards.ts\nimport type {Request, Response, NextFunction, RequestHandler} from \"express\";\nimport parseHeaders from \"./parseHeaders\";\nimport {authEmployeeRequired} from \"../auth\";\nimport {sendError} from \"./respond\";\n\ntype RoleShape = string | { code?: string; name?: string };\ntype PermShape = string | { code?: string; name?: string };\n\nfunction normalizeRole(r: RoleShape): string | null {\n if (!r) return null;\n if (typeof r === \"string\") return r;\n return r.code || r.name || null;\n}\n\nfunction normalizePerm(p: PermShape): string | null {\n if (!p) return null;\n if (typeof p === \"string\") return p;\n return p.code || p.name || null;\n}\n\nfunction isSysAdmin(roles: RoleShape[] | undefined): boolean {\n if (!Array.isArray(roles)) return false;\n return roles.some((r) => normalizeRole(r) === \"SYS_ADMIN\");\n}\n\nfunction getAuth(req: Request) {\n return ((req as any).auth ?? {}) as {\n roles?: RoleShape[];\n permissions?: PermShape[];\n denied_permissions?: PermShape[];\n };\n}\n\nfunction permissionSets(auth: ReturnType<typeof getAuth>) {\n const allow = new Set<string>((auth.permissions ?? []).map(normalizePerm).filter(Boolean) as string[]);\n const deny = new Set<string>((auth.denied_permissions ?? []).map(normalizePerm).filter(Boolean) as string[]);\n return {allow, deny};\n}\n\nfunction roleSet(auth: ReturnType<typeof getAuth>) {\n return new Set<string>((auth.roles ?? []).map(normalizeRole).filter(Boolean) as string[]);\n}\n\n/**\n * ✅ SysAdmin bypass OR (ANY) permissions\n * - Si tiene alguno de los permisos => OK\n * - denied_permissions gana siempre\n */\nexport function allowSysAdminOrAnyPermission(...perms: string[]): RequestHandler[] {\n const required = (perms ?? []).filter(Boolean);\n\n return [\n parseHeaders,\n authEmployeeRequired,\n (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n if (isSysAdmin(auth.roles)) return next();\n\n const {allow, deny} = permissionSets(auth);\n\n for (const p of required) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied permission: ${p}`, {denied: p});\n }\n }\n\n const ok = required.some((p) => allow.has(p));\n if (!ok) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Missing permissions (ANY)\", {required});\n }\n\n return next();\n },\n ];\n}\n\n/**\n * ✅ SysAdmin bypass OR (ALL) permissions (AND)\n */\nexport function allowSysAdminOrPermissionsAll(...perms: string[]): RequestHandler[] {\n const required = (perms ?? []).filter(Boolean);\n\n return [\n parseHeaders,\n authEmployeeRequired,\n (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n if (isSysAdmin(auth.roles)) return next();\n\n const {allow, deny} = permissionSets(auth);\n\n for (const p of required) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied permission: ${p}`, {denied: p});\n }\n }\n\n const missing = required.filter((p) => !allow.has(p));\n if (missing.length) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Missing permissions (ALL)\", {required, missing});\n }\n\n return next();\n },\n ];\n}\n\n/**\n * ✅ SysAdmin bypass OR roles (ANY)\n */\nexport function allowSysAdminOrRoles(...roles: string[]): RequestHandler[] {\n const required = (roles ?? []).filter(Boolean);\n\n return [\n parseHeaders,\n authEmployeeRequired,\n (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n if (isSysAdmin(auth.roles)) return next();\n\n const have = roleSet(auth);\n\n const ok = required.some((r) => have.has(r));\n if (!ok) {\n return sendError(req, res, 403, \"FORBIDDEN\", \"Role not allowed\", {required});\n }\n\n return next();\n },\n ];\n}\n\n/**\n * ✅ SYS_ADMIN bypass OR (ANY) roles OR (ANY) permissions\n * - denied_permissions siempre gana\n */\nexport function allowSysAdminOrRolesOrAnyPermission(\n roles: string | string[],\n permissions: string | string[]\n): RequestHandler[] {\n const requiredRoles = (Array.isArray(roles) ? roles : [roles]).filter(Boolean);\n const requiredPerms = (Array.isArray(permissions) ? permissions : [permissions]).filter(Boolean);\n\n return [\n parseHeaders,\n authEmployeeRequired,\n (req: Request, res: Response, next: NextFunction) => {\n const auth = getAuth(req);\n if (isSysAdmin(auth.roles)) return next();\n\n const {allow, deny} = permissionSets(auth);\n for (const p of requiredPerms) {\n if (deny.has(p)) {\n return sendError(req, res, 403, \"FORBIDDEN\", `Denied: ${p}`, {permission: p});\n }\n }\n\n const haveRoles = roleSet(auth);\n if (requiredRoles.some((r) => haveRoles.has(r))) return next();\n\n if (requiredPerms.some((p) => allow.has(p))) return next();\n\n return sendError(req, res, 403, \"FORBIDDEN\", \"Permission denied\", {\n roles: requiredRoles,\n permissions: requiredPerms,\n mode: \"ROLES_OR_ANY_PERMISSION\",\n });\n },\n ];\n}\n\n/**\n * ✅ Helper específico Auth:\n * Rol AUTH_ADMIN o permiso fino (y SYS_ADMIN bypass)\n */\nexport function allowAuthAdminOrPerm(permission: string): RequestHandler[] {\n return allowSysAdminOrRolesOrAnyPermission([\"AUTH_ADMIN\"], [permission]);\n}\n"],"mappings":";;;;;;AAUe,SAAR,aAA8B,KAAc,MAAgB,MAAoB;AACnF,EAAC,IAAY,UA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,aAAa,qBAAqB;AAAA,QAC9D,OAAO;AAAA,QACP,aAAa;AAAA,QACb,MAAM;AAAA,MACV,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;AAMO,SAAS,qBAAqB,YAAsC;AACvE,SAAO,oCAAoC,CAAC,YAAY,GAAG,CAAC,UAAU,CAAC;AAC3E;","names":["fs","admin","jwt","fs","getBearerToken","verifyBackendJwtRS256","normalizeUid","createAuthMiddleware","isSysAdmin","getAuth"]}
|
package/dist/index.cjs
CHANGED
|
@@ -921,9 +921,7 @@ function readPublicKey() {
|
|
|
921
921
|
}
|
|
922
922
|
const envKey = publicKeyEnv.replace(/\\n/g, "\n").trim();
|
|
923
923
|
if (envKey) return envKey;
|
|
924
|
-
throw new Error(
|
|
925
|
-
"Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)"
|
|
926
|
-
);
|
|
924
|
+
throw new Error("Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)");
|
|
927
925
|
}
|
|
928
926
|
function verifyBackendJwtRS2562(raw) {
|
|
929
927
|
const publicKey = readPublicKey();
|
|
@@ -939,20 +937,11 @@ function normalizeUid2(v) {
|
|
|
939
937
|
const s = String(v ?? "").trim();
|
|
940
938
|
return s.length ? s : null;
|
|
941
939
|
}
|
|
942
|
-
function
|
|
943
|
-
|
|
944
|
-
const
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
if (typeof item === "string") {
|
|
948
|
-
const s2 = item.trim();
|
|
949
|
-
if (s2) out.push(s2);
|
|
950
|
-
continue;
|
|
951
|
-
}
|
|
952
|
-
const s = String(item.code || item.name || "").trim();
|
|
953
|
-
if (s) out.push(s);
|
|
954
|
-
}
|
|
955
|
-
return Array.from(new Set(out));
|
|
940
|
+
function deriveCompanyBranch(decoded, companyUid, branchUid) {
|
|
941
|
+
const companiesFromToken = Array.isArray(decoded?.companies) ? decoded.companies : [];
|
|
942
|
+
const company = decoded?.company ?? (companyUid ? companiesFromToken.find((c) => c?.uid === companyUid) : null) ?? null;
|
|
943
|
+
const branch = decoded?.branch ?? (branchUid && company?.branches ? (company.branches || []).find((b) => b?.uid === branchUid) : null) ?? null;
|
|
944
|
+
return { companiesFromToken, company, branch };
|
|
956
945
|
}
|
|
957
946
|
function extractEmployeeUid(decoded) {
|
|
958
947
|
const direct = normalizeUid2(decoded?.employee_uid);
|
|
@@ -970,12 +959,6 @@ function extractCustomerUid(decoded) {
|
|
|
970
959
|
const m = /^cus:(.+)$/i.exec(sub);
|
|
971
960
|
return m?.[1] ? normalizeUid2(m[1]) : null;
|
|
972
961
|
}
|
|
973
|
-
function deriveCompanyBranch(decoded, companyUid, branchUid) {
|
|
974
|
-
const companiesFromToken = Array.isArray(decoded?.companies) ? decoded.companies : [];
|
|
975
|
-
const company = decoded?.company ?? (companyUid ? companiesFromToken.find((c) => c?.uid === companyUid) : null) ?? null;
|
|
976
|
-
const branch = decoded?.branch ?? (branchUid && company?.branches ? (company.branches || []).find((b) => b?.uid === branchUid) : null) ?? null;
|
|
977
|
-
return { companiesFromToken, company, branch };
|
|
978
|
-
}
|
|
979
962
|
function createAuthMiddleware2(opts) {
|
|
980
963
|
const { subject, allowFirebaseIdToken = false } = opts;
|
|
981
964
|
return async (req, res, next) => {
|
|
@@ -1001,10 +984,9 @@ function createAuthMiddleware2(opts) {
|
|
|
1001
984
|
companies: companiesFromToken,
|
|
1002
985
|
company,
|
|
1003
986
|
branch,
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
denied_permissions: normalizeCodes(decoded?.denied_permissions, "perm"),
|
|
987
|
+
roles: Array.isArray(decoded?.roles) ? decoded.roles : [],
|
|
988
|
+
permissions: Array.isArray(decoded?.permissions) ? decoded.permissions : [],
|
|
989
|
+
denied_permissions: Array.isArray(decoded?.denied_permissions) ? decoded.denied_permissions : [],
|
|
1008
990
|
session: {
|
|
1009
991
|
jti: decoded?.jti,
|
|
1010
992
|
device_id: decoded?.device_id,
|
|
@@ -1012,35 +994,29 @@ function createAuthMiddleware2(opts) {
|
|
|
1012
994
|
}
|
|
1013
995
|
};
|
|
1014
996
|
if (subject === "employee") {
|
|
1015
|
-
const
|
|
1016
|
-
|
|
1017
|
-
if (employeeEmbedded) {
|
|
1018
|
-
ctx.employee = employeeUid ? { ...employeeEmbedded, uid: employeeEmbedded?.uid ?? employeeUid } : employeeEmbedded;
|
|
1019
|
-
} else if (employeeUid) {
|
|
1020
|
-
ctx.employee = { uid: employeeUid };
|
|
1021
|
-
} else {
|
|
997
|
+
const employee_uid = extractEmployeeUid(decoded);
|
|
998
|
+
if (!employee_uid) {
|
|
1022
999
|
return res.status(401).json({
|
|
1023
1000
|
ok: false,
|
|
1024
|
-
code: "
|
|
1025
|
-
message: "
|
|
1001
|
+
code: "AUTH_EMPLOYEE_UID_MISSING",
|
|
1002
|
+
message: "employee_uid missing in token (expected employee_uid or sub=emp:<uid>)"
|
|
1026
1003
|
});
|
|
1027
1004
|
}
|
|
1028
|
-
ctx.employee_uid =
|
|
1005
|
+
ctx.employee_uid = employee_uid;
|
|
1006
|
+
const embedded = decoded?.employee ?? decoded?.user ?? null;
|
|
1007
|
+
ctx.employee = embedded && typeof embedded === "object" ? embedded : { uid: employee_uid, email: decoded?.email ?? null };
|
|
1029
1008
|
} else {
|
|
1030
|
-
const
|
|
1031
|
-
|
|
1032
|
-
if (customerEmbedded) {
|
|
1033
|
-
ctx.customer = customerUid ? { ...customerEmbedded, uid: customerEmbedded?.uid ?? customerUid } : customerEmbedded;
|
|
1034
|
-
} else if (customerUid) {
|
|
1035
|
-
ctx.customer = { uid: customerUid };
|
|
1036
|
-
} else {
|
|
1009
|
+
const customer_uid = extractCustomerUid(decoded);
|
|
1010
|
+
if (!customer_uid) {
|
|
1037
1011
|
return res.status(401).json({
|
|
1038
1012
|
ok: false,
|
|
1039
|
-
code: "
|
|
1040
|
-
message: "
|
|
1013
|
+
code: "AUTH_CUSTOMER_UID_MISSING",
|
|
1014
|
+
message: "customer_uid missing in token (expected customer_uid or sub=cus:<uid>)"
|
|
1041
1015
|
});
|
|
1042
1016
|
}
|
|
1043
|
-
ctx.customer_uid =
|
|
1017
|
+
ctx.customer_uid = customer_uid;
|
|
1018
|
+
const embedded = decoded?.customer ?? null;
|
|
1019
|
+
ctx.customer = embedded && typeof embedded === "object" ? embedded : { uid: customer_uid };
|
|
1044
1020
|
}
|
|
1045
1021
|
req.auth = ctx;
|
|
1046
1022
|
return next();
|