@innvoid/getmarket-sdk 0.1.2 → 0.1.4

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,87 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { JwtPayload } from 'jsonwebtoken';
3
+
4
+ type AuthSubject = "employee" | "customer";
5
+ type TokenType = "backend";
6
+ type AuthSession = {
7
+ jti?: string;
8
+ device_id?: string;
9
+ expires_at?: number;
10
+ };
11
+ type AuthContext = {
12
+ tokenType: TokenType;
13
+ subject: AuthSubject;
14
+ employee?: any;
15
+ customer?: any;
16
+ company_uid?: string;
17
+ branch_uid?: string;
18
+ companies?: any[];
19
+ company?: any;
20
+ branch?: any;
21
+ roles?: string[];
22
+ permissions?: string[];
23
+ denied_permissions?: string[];
24
+ session?: AuthSession;
25
+ firebase?: any;
26
+ };
27
+ type HydrateInput = {
28
+ decoded: any;
29
+ req: Request;
30
+ subject: AuthSubject;
31
+ company_uid: string | null;
32
+ branch_uid: string | null;
33
+ };
34
+ type HydrateResult = Partial<Pick<AuthContext, "employee" | "customer" | "companies" | "company" | "branch" | "roles" | "permissions" | "denied_permissions">>;
35
+ type Hydrator = (input: HydrateInput) => Promise<HydrateResult> | HydrateResult;
36
+ type AuthMiddlewareOptions = {
37
+ subject: AuthSubject;
38
+ /**
39
+ * ✅ Si true, exige que el sujeto (employee/customer) exista tras hydrate.
40
+ * Default: true
41
+ */
42
+ requireSubject?: boolean;
43
+ /**
44
+ * Si true, permite fallback a Firebase idToken.
45
+ * Default: false
46
+ */
47
+ allowFirebaseIdToken?: boolean;
48
+ /**
49
+ * ✅ OBLIGATORIO para evitar "legacy" o acoplamientos:
50
+ * el micro decide cómo hidratar (DB local / AuthClient / etc).
51
+ */
52
+ hydrate: Hydrator;
53
+ };
54
+
55
+ /**
56
+ * ✅ Keys viven en getmarket-stack:
57
+ * - JWT_PUBLIC_KEY_PATH=/run/secrets/jwtRS256.key.pub (recomendado)
58
+ * - fallback env AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY
59
+ */
60
+ declare function readRs256PublicKey(): string;
61
+ declare function verifyBackendJwtRS256(raw: string): JwtPayload;
62
+
63
+ /**
64
+ * ✅ Middleware estándar:
65
+ * - Solo Authorization: Bearer
66
+ * - Solo RS256
67
+ * - Cero legacy
68
+ * - Hidrata vía hook (OBLIGATORIO) para que cada micro no replique lógica
69
+ */
70
+ declare function createAuthMiddleware(opts: AuthMiddlewareOptions): (req: any, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
71
+
72
+ type index_AuthContext = AuthContext;
73
+ type index_AuthMiddlewareOptions = AuthMiddlewareOptions;
74
+ type index_AuthSession = AuthSession;
75
+ type index_AuthSubject = AuthSubject;
76
+ type index_HydrateInput = HydrateInput;
77
+ type index_HydrateResult = HydrateResult;
78
+ type index_Hydrator = Hydrator;
79
+ type index_TokenType = TokenType;
80
+ declare const index_createAuthMiddleware: typeof createAuthMiddleware;
81
+ declare const index_readRs256PublicKey: typeof readRs256PublicKey;
82
+ declare const index_verifyBackendJwtRS256: typeof verifyBackendJwtRS256;
83
+ declare namespace index {
84
+ export { type index_AuthContext as AuthContext, type index_AuthMiddlewareOptions as AuthMiddlewareOptions, type index_AuthSession as AuthSession, type index_AuthSubject as AuthSubject, type index_HydrateInput as HydrateInput, type index_HydrateResult as HydrateResult, type index_Hydrator as Hydrator, type index_TokenType as TokenType, index_createAuthMiddleware as createAuthMiddleware, index_readRs256PublicKey as readRs256PublicKey, index_verifyBackendJwtRS256 as verifyBackendJwtRS256 };
85
+ }
86
+
87
+ export { type AuthContext as A, type HydrateInput as H, type TokenType as T, type AuthMiddlewareOptions as a, type AuthSession as b, type AuthSubject as c, type HydrateResult as d, type Hydrator as e, createAuthMiddleware as f, index as i, readRs256PublicKey as r, verifyBackendJwtRS256 as v };
@@ -0,0 +1,87 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { JwtPayload } from 'jsonwebtoken';
3
+
4
+ type AuthSubject = "employee" | "customer";
5
+ type TokenType = "backend";
6
+ type AuthSession = {
7
+ jti?: string;
8
+ device_id?: string;
9
+ expires_at?: number;
10
+ };
11
+ type AuthContext = {
12
+ tokenType: TokenType;
13
+ subject: AuthSubject;
14
+ employee?: any;
15
+ customer?: any;
16
+ company_uid?: string;
17
+ branch_uid?: string;
18
+ companies?: any[];
19
+ company?: any;
20
+ branch?: any;
21
+ roles?: string[];
22
+ permissions?: string[];
23
+ denied_permissions?: string[];
24
+ session?: AuthSession;
25
+ firebase?: any;
26
+ };
27
+ type HydrateInput = {
28
+ decoded: any;
29
+ req: Request;
30
+ subject: AuthSubject;
31
+ company_uid: string | null;
32
+ branch_uid: string | null;
33
+ };
34
+ type HydrateResult = Partial<Pick<AuthContext, "employee" | "customer" | "companies" | "company" | "branch" | "roles" | "permissions" | "denied_permissions">>;
35
+ type Hydrator = (input: HydrateInput) => Promise<HydrateResult> | HydrateResult;
36
+ type AuthMiddlewareOptions = {
37
+ subject: AuthSubject;
38
+ /**
39
+ * ✅ Si true, exige que el sujeto (employee/customer) exista tras hydrate.
40
+ * Default: true
41
+ */
42
+ requireSubject?: boolean;
43
+ /**
44
+ * Si true, permite fallback a Firebase idToken.
45
+ * Default: false
46
+ */
47
+ allowFirebaseIdToken?: boolean;
48
+ /**
49
+ * ✅ OBLIGATORIO para evitar "legacy" o acoplamientos:
50
+ * el micro decide cómo hidratar (DB local / AuthClient / etc).
51
+ */
52
+ hydrate: Hydrator;
53
+ };
54
+
55
+ /**
56
+ * ✅ Keys viven en getmarket-stack:
57
+ * - JWT_PUBLIC_KEY_PATH=/run/secrets/jwtRS256.key.pub (recomendado)
58
+ * - fallback env AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY
59
+ */
60
+ declare function readRs256PublicKey(): string;
61
+ declare function verifyBackendJwtRS256(raw: string): JwtPayload;
62
+
63
+ /**
64
+ * ✅ Middleware estándar:
65
+ * - Solo Authorization: Bearer
66
+ * - Solo RS256
67
+ * - Cero legacy
68
+ * - Hidrata vía hook (OBLIGATORIO) para que cada micro no replique lógica
69
+ */
70
+ declare function createAuthMiddleware(opts: AuthMiddlewareOptions): (req: any, res: Response, next: NextFunction) => Promise<void | Response<any, Record<string, any>>>;
71
+
72
+ type index_AuthContext = AuthContext;
73
+ type index_AuthMiddlewareOptions = AuthMiddlewareOptions;
74
+ type index_AuthSession = AuthSession;
75
+ type index_AuthSubject = AuthSubject;
76
+ type index_HydrateInput = HydrateInput;
77
+ type index_HydrateResult = HydrateResult;
78
+ type index_Hydrator = Hydrator;
79
+ type index_TokenType = TokenType;
80
+ declare const index_createAuthMiddleware: typeof createAuthMiddleware;
81
+ declare const index_readRs256PublicKey: typeof readRs256PublicKey;
82
+ declare const index_verifyBackendJwtRS256: typeof verifyBackendJwtRS256;
83
+ declare namespace index {
84
+ export { type index_AuthContext as AuthContext, type index_AuthMiddlewareOptions as AuthMiddlewareOptions, type index_AuthSession as AuthSession, type index_AuthSubject as AuthSubject, type index_HydrateInput as HydrateInput, type index_HydrateResult as HydrateResult, type index_Hydrator as Hydrator, type index_TokenType as TokenType, index_createAuthMiddleware as createAuthMiddleware, index_readRs256PublicKey as readRs256PublicKey, index_verifyBackendJwtRS256 as verifyBackendJwtRS256 };
85
+ }
86
+
87
+ export { type AuthContext as A, type HydrateInput as H, type TokenType as T, type AuthMiddlewareOptions as a, type AuthSession as b, type AuthSubject as c, type HydrateResult as d, type Hydrator as e, createAuthMiddleware as f, index as i, readRs256PublicKey as r, verifyBackendJwtRS256 as v };
package/dist/index.cjs CHANGED
@@ -40,7 +40,9 @@ __export(src_exports, {
40
40
  REQUEST_ID_HEADER: () => REQUEST_ID_HEADER,
41
41
  TwoLevelCache: () => TwoLevelCache,
42
42
  UpstreamError: () => UpstreamError,
43
+ auth: () => auth_exports,
43
44
  closeCache: () => closeCache,
45
+ createAuthMiddleware: () => createAuthMiddleware,
44
46
  createHttpClient: () => createHttpClient,
45
47
  getOrSet: () => getOrSet,
46
48
  getRequestContextFromHeaders: () => getRequestContextFromHeaders,
@@ -48,9 +50,14 @@ __export(src_exports, {
48
50
  internalAuth: () => internalAuth,
49
51
  mapAxiosToUpstreamError: () => mapAxiosToUpstreamError,
50
52
  parseHeaders: () => parseHeaders,
53
+ readRs256PublicKey: () => readRs256PublicKey,
51
54
  requestId: () => requestId,
55
+ requireAuthContext: () => requireAuthContext,
56
+ requirePermissions: () => requirePermissions,
57
+ requireRoles: () => requireRoles,
52
58
  sendError: () => sendError,
53
59
  sendOk: () => sendOk,
60
+ verifyBackendJwtRS256: () => verifyBackendJwtRS256,
54
61
  withRequestId: () => withRequestId,
55
62
  withRequestIdConfig: () => withRequestIdConfig
56
63
  });
@@ -617,6 +624,191 @@ function internalAuth(req, res, next) {
617
624
  }
618
625
  return next();
619
626
  }
627
+
628
+ // src/middlewares/autorization.ts
629
+ function getAuth(req) {
630
+ return req.auth ?? {};
631
+ }
632
+ function requireAuthContext() {
633
+ return (req, res, next) => {
634
+ if (!req.auth) {
635
+ return sendError(req, res, 401, "UNAUTHORIZED", "Missing auth context");
636
+ }
637
+ return next();
638
+ };
639
+ }
640
+ function requirePermissions(...perms) {
641
+ return (req, res, next) => {
642
+ const auth = getAuth(req);
643
+ const allow = new Set(auth.permissions ?? []);
644
+ const deny = new Set(auth.denied_permissions ?? []);
645
+ for (const p of perms) {
646
+ if (deny.has(p)) {
647
+ return sendError(req, res, 403, "FORBIDDEN", `Denied: ${p}`);
648
+ }
649
+ }
650
+ const missing = perms.filter((p) => !allow.has(p));
651
+ if (missing.length) {
652
+ return sendError(req, res, 403, "FORBIDDEN", "Missing permissions", { missing });
653
+ }
654
+ return next();
655
+ };
656
+ }
657
+ function requireRoles(...roles) {
658
+ return (req, res, next) => {
659
+ const auth = getAuth(req);
660
+ const have = new Set(auth.roles ?? []);
661
+ if (!roles.some((r) => have.has(r))) {
662
+ return sendError(req, res, 403, "FORBIDDEN", "Role not allowed", { required: roles });
663
+ }
664
+ return next();
665
+ };
666
+ }
667
+
668
+ // src/auth/index.ts
669
+ var auth_exports = {};
670
+ __export(auth_exports, {
671
+ createAuthMiddleware: () => createAuthMiddleware,
672
+ readRs256PublicKey: () => readRs256PublicKey,
673
+ verifyBackendJwtRS256: () => verifyBackendJwtRS256
674
+ });
675
+
676
+ // src/auth/jwt.ts
677
+ var import_fs2 = __toESM(require("fs"), 1);
678
+ var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
679
+ function readFileIfExists(path) {
680
+ if (!path) return null;
681
+ try {
682
+ const v = import_fs2.default.readFileSync(path, "utf8").trim();
683
+ return v.length ? v : null;
684
+ } catch {
685
+ return null;
686
+ }
687
+ }
688
+ function readRs256PublicKey() {
689
+ const fromFile = readFileIfExists(process.env.JWT_PUBLIC_KEY_PATH);
690
+ if (fromFile) return fromFile;
691
+ const fromEnv = String(process.env.AUTH_JWT_PUBLIC_KEY || process.env.AUTH_RSA_PUBLIC_KEY || "").replace(/\\n/g, "\n").trim();
692
+ if (fromEnv) return fromEnv;
693
+ throw new Error("Missing RS256 public key (JWT_PUBLIC_KEY_PATH / AUTH_JWT_PUBLIC_KEY / AUTH_RSA_PUBLIC_KEY)");
694
+ }
695
+ function verifyBackendJwtRS256(raw) {
696
+ const publicKey = readRs256PublicKey();
697
+ const audience = process.env.JWT_AUDIENCE || process.env.AUTH_JWT_AUDIENCE || "getmarket.api";
698
+ const issuer = process.env.JWT_ISSUER || process.env.AUTH_JWT_ISSUER || "getmarket-auth";
699
+ return import_jsonwebtoken.default.verify(raw, publicKey, {
700
+ algorithms: ["RS256"],
701
+ audience,
702
+ issuer
703
+ });
704
+ }
705
+
706
+ // src/auth/middleware.ts
707
+ function getBearerToken(req) {
708
+ const auth = String(req.headers?.authorization || "");
709
+ if (!auth.startsWith("Bearer ")) return null;
710
+ const token = auth.slice(7).trim();
711
+ return token.length ? token : null;
712
+ }
713
+ function normalizeUid(v) {
714
+ const s = String(v ?? "").trim();
715
+ return s.length ? s : null;
716
+ }
717
+ function createAuthMiddleware(opts) {
718
+ const {
719
+ subject,
720
+ allowFirebaseIdToken = false,
721
+ requireSubject = true,
722
+ hydrate
723
+ } = opts;
724
+ return async (req, res, next) => {
725
+ const token = getBearerToken(req);
726
+ if (!token) {
727
+ return res.status(401).json({
728
+ ok: false,
729
+ code: "AUTH_MISSING_TOKEN",
730
+ message: "Missing Authorization Bearer token"
731
+ });
732
+ }
733
+ const headerCtx = req.context || {};
734
+ const company_uid = normalizeUid(headerCtx.company_uid);
735
+ const branch_uid = normalizeUid(headerCtx.branch_uid);
736
+ try {
737
+ const decoded = verifyBackendJwtRS256(token);
738
+ const baseCtx = {
739
+ tokenType: "backend",
740
+ subject,
741
+ company_uid: company_uid ?? void 0,
742
+ branch_uid: branch_uid ?? void 0,
743
+ roles: Array.isArray(decoded?.roles) ? decoded.roles : [],
744
+ permissions: Array.isArray(decoded?.permissions) ? decoded.permissions : [],
745
+ denied_permissions: Array.isArray(decoded?.denied_permissions) ? decoded.denied_permissions : [],
746
+ session: {
747
+ jti: decoded?.jti,
748
+ device_id: decoded?.device_id,
749
+ expires_at: decoded?.exp
750
+ }
751
+ };
752
+ const hydrated = await hydrate({ decoded, req, subject, company_uid, branch_uid });
753
+ Object.assign(baseCtx, hydrated);
754
+ if (requireSubject) {
755
+ if (subject === "employee" && !baseCtx.employee) {
756
+ return res.status(401).json({
757
+ ok: false,
758
+ code: "AUTH_EMPLOYEE_NOT_FOUND",
759
+ message: "Employee not resolved by hydrator"
760
+ });
761
+ }
762
+ if (subject === "customer" && !baseCtx.customer) {
763
+ return res.status(401).json({
764
+ ok: false,
765
+ code: "AUTH_CUSTOMER_NOT_FOUND",
766
+ message: "Customer not resolved by hydrator"
767
+ });
768
+ }
769
+ }
770
+ req.auth = baseCtx;
771
+ return next();
772
+ } catch (errJwt) {
773
+ if (!allowFirebaseIdToken) {
774
+ return res.status(401).json({
775
+ ok: false,
776
+ code: "AUTH_INVALID_TOKEN",
777
+ message: "Invalid or expired token"
778
+ });
779
+ }
780
+ try {
781
+ const { default: admin } = await import("firebase-admin");
782
+ const firebaseDecoded = await admin.auth().verifyIdToken(token);
783
+ if (firebaseDecoded.email && firebaseDecoded.email_verified === false) {
784
+ return res.status(401).json({
785
+ ok: false,
786
+ code: "AUTH_EMAIL_NOT_VERIFIED",
787
+ message: "Email not verified"
788
+ });
789
+ }
790
+ req.auth = {
791
+ tokenType: "backend",
792
+ subject,
793
+ firebase: firebaseDecoded,
794
+ company_uid: company_uid ?? void 0,
795
+ branch_uid: branch_uid ?? void 0,
796
+ companies: [],
797
+ roles: [],
798
+ permissions: [],
799
+ denied_permissions: []
800
+ };
801
+ return next();
802
+ } catch {
803
+ return res.status(401).json({
804
+ ok: false,
805
+ code: "AUTH_INVALID_TOKEN",
806
+ message: "Invalid or expired token"
807
+ });
808
+ }
809
+ }
810
+ };
811
+ }
620
812
  // Annotate the CommonJS export names for ESM import in node:
621
813
  0 && (module.exports = {
622
814
  HEADER_AUTHORIZATION,
@@ -629,7 +821,9 @@ function internalAuth(req, res, next) {
629
821
  REQUEST_ID_HEADER,
630
822
  TwoLevelCache,
631
823
  UpstreamError,
824
+ auth,
632
825
  closeCache,
826
+ createAuthMiddleware,
633
827
  createHttpClient,
634
828
  getOrSet,
635
829
  getRequestContextFromHeaders,
@@ -637,9 +831,14 @@ function internalAuth(req, res, next) {
637
831
  internalAuth,
638
832
  mapAxiosToUpstreamError,
639
833
  parseHeaders,
834
+ readRs256PublicKey,
640
835
  requestId,
836
+ requireAuthContext,
837
+ requirePermissions,
838
+ requireRoles,
641
839
  sendError,
642
840
  sendOk,
841
+ verifyBackendJwtRS256,
643
842
  withRequestId,
644
843
  withRequestIdConfig
645
844
  });