@miguelmorales13/nestkit 0.25.0 → 0.28.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.
Files changed (281) hide show
  1. package/README.md +5 -0
  2. package/dist/alerts/alert-on-failure.decorator.d.ts +5 -0
  3. package/dist/alerts/alert-sinks.d.ts +29 -0
  4. package/dist/alerts/alerts.module.d.ts +19 -0
  5. package/dist/alerts/alerts.options.d.ts +1 -0
  6. package/dist/alerts/alerts.service.d.ts +28 -0
  7. package/dist/alerts/alerts.types.d.ts +66 -0
  8. package/dist/alerts/index.cjs +276 -0
  9. package/dist/alerts/index.d.ts +10 -0
  10. package/dist/alerts/index.js +276 -0
  11. package/dist/alerts/logger-with-alerts.d.ts +18 -0
  12. package/dist/alerts/process-guards.d.ts +21 -0
  13. package/dist/alerts/runtime.d.ts +4 -0
  14. package/dist/audit/index.cjs +13 -13
  15. package/dist/audit/index.js +2 -2
  16. package/dist/auth/index.cjs +21 -21
  17. package/dist/auth/index.js +3 -3
  18. package/dist/auth/oauth/index.cjs +123 -115
  19. package/dist/auth/oauth/index.js +25 -17
  20. package/dist/auth/oauth/oauth-provider.d.ts +9 -0
  21. package/dist/auth/oauth/providers/apple.d.ts +3 -1
  22. package/dist/bootstrap/apply-defaults.d.ts +9 -0
  23. package/dist/bootstrap/index.cjs +6 -5
  24. package/dist/bootstrap/index.js +5 -4
  25. package/dist/chunk-3TUMVLPJ.js +14 -0
  26. package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
  27. package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
  28. package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
  29. package/dist/{chunk-A2DGK4ZL.js → chunk-5LVGCTJ3.js} +1 -1
  30. package/dist/chunk-A6YGIZCQ.cjs +14 -0
  31. package/dist/chunk-A7FI6HXV.js +40 -0
  32. package/dist/chunk-CU4FUIVJ.cjs +8 -0
  33. package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
  34. package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
  35. package/dist/chunk-DVGPEBUL.js +8 -0
  36. package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
  37. package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
  38. package/dist/chunk-FBNV5X6C.js +61 -0
  39. package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
  40. package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
  41. package/dist/chunk-IVWPA6QH.cjs +90 -0
  42. package/dist/{chunk-MSTXS3MU.cjs → chunk-JJKGQNGD.cjs} +2 -2
  43. package/dist/{chunk-FNUZGYUF.cjs → chunk-JRFE7NSO.cjs} +12 -4
  44. package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
  45. package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
  46. package/dist/chunk-LGFHLAY3.cjs +61 -0
  47. package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
  48. package/dist/{chunk-4PFAKLT3.js → chunk-MUWHGBIB.js} +1 -1
  49. package/dist/{chunk-ZJMLEP5H.js → chunk-NJYLQDB3.js} +1 -1
  50. package/dist/{chunk-IFNYRZP2.js → chunk-OSRH6KYZ.js} +4 -4
  51. package/dist/{chunk-6RAPVLJM.js → chunk-OTE77ONL.js} +1 -1
  52. package/dist/chunk-UDACUMLO.cjs +40 -0
  53. package/dist/{chunk-UNEVXCFW.js → chunk-UGAAJRPO.js} +10 -2
  54. package/dist/{chunk-SPTDXUED.cjs → chunk-URLDTS2Q.cjs} +2 -2
  55. package/dist/{chunk-W2T2VFLC.cjs → chunk-VALDHJOO.cjs} +5 -5
  56. package/dist/chunk-WFCQDOSN.js +90 -0
  57. package/dist/consent/consent.interceptor.d.ts +20 -0
  58. package/dist/consent/consent.module.d.ts +25 -0
  59. package/dist/consent/consent.options.d.ts +30 -0
  60. package/dist/consent/consent.port.d.ts +17 -0
  61. package/dist/consent/consent.service.d.ts +44 -0
  62. package/dist/consent/guard/index.cjs +13 -0
  63. package/dist/consent/guard/index.d.ts +31 -0
  64. package/dist/consent/guard/index.js +13 -0
  65. package/dist/consent/index.cjs +271 -0
  66. package/dist/consent/index.d.ts +13 -0
  67. package/dist/consent/index.js +271 -0
  68. package/dist/consent/memory.store.d.ts +7 -0
  69. package/dist/consent/shared/index.cjs +11 -0
  70. package/dist/consent/shared/index.d.ts +19 -0
  71. package/dist/consent/shared/index.js +11 -0
  72. package/dist/consent/typeorm.store.d.ts +22 -0
  73. package/dist/crud/index.cjs +4 -4
  74. package/dist/crud/index.js +3 -3
  75. package/dist/database/postgres/index.cjs +3 -3
  76. package/dist/database/postgres/index.js +2 -2
  77. package/dist/database/supabase/index.cjs +3 -3
  78. package/dist/database/supabase/index.js +2 -2
  79. package/dist/database/typeorm/index.cjs +2 -2
  80. package/dist/database/typeorm/index.js +1 -1
  81. package/dist/devices/device-check.interceptor.d.ts +20 -0
  82. package/dist/devices/devices.module.d.ts +28 -0
  83. package/dist/devices/devices.options.d.ts +53 -0
  84. package/dist/devices/devices.port.d.ts +62 -0
  85. package/dist/devices/devices.service.d.ts +58 -0
  86. package/dist/devices/index.cjs +327 -0
  87. package/dist/devices/index.d.ts +8 -0
  88. package/dist/devices/index.js +327 -0
  89. package/dist/devices/memory.store.d.ts +12 -0
  90. package/dist/email/index.cjs +2 -2
  91. package/dist/email/index.js +1 -1
  92. package/dist/email/nodemailer/index.cjs +2 -2
  93. package/dist/email/nodemailer/index.js +1 -1
  94. package/dist/email/resend/index.cjs +2 -2
  95. package/dist/email/resend/index.js +1 -1
  96. package/dist/entities/index.cjs +1 -1
  97. package/dist/entities/index.js +1 -1
  98. package/dist/errors/index.cjs +7 -7
  99. package/dist/errors/index.js +7 -7
  100. package/dist/events/buses.d.ts +27 -0
  101. package/dist/events/events.controller.d.ts +15 -0
  102. package/dist/events/events.module.d.ts +29 -0
  103. package/dist/events/events.options.d.ts +50 -0
  104. package/dist/events/events.service.d.ts +49 -0
  105. package/dist/events/events.types.d.ts +77 -0
  106. package/dist/events/index.cjs +557 -0
  107. package/dist/events/index.d.ts +10 -0
  108. package/dist/events/index.js +557 -0
  109. package/dist/events/memory-ticket.store.d.ts +9 -0
  110. package/dist/google-business/google-business-http.d.ts +41 -0
  111. package/dist/google-business/google-business.errors.d.ts +75 -0
  112. package/dist/google-business/google-business.mappers.d.ts +52 -0
  113. package/dist/google-business/google-business.module.d.ts +26 -0
  114. package/dist/google-business/google-business.options.d.ts +40 -0
  115. package/dist/google-business/google-business.ports.d.ts +18 -0
  116. package/dist/google-business/google-business.service.d.ts +120 -0
  117. package/dist/google-business/google-business.types.d.ts +155 -0
  118. package/dist/google-business/index.cjs +1025 -0
  119. package/dist/google-business/index.d.ts +15 -0
  120. package/dist/google-business/index.js +1025 -0
  121. package/dist/google-business/testing/google-simulator.d.ts +61 -0
  122. package/dist/hardening/body-limits.d.ts +24 -0
  123. package/dist/hardening/http.types.d.ts +26 -0
  124. package/dist/hardening/index.cjs +179 -0
  125. package/dist/hardening/index.d.ts +19 -0
  126. package/dist/hardening/index.js +179 -0
  127. package/dist/hardening/memory-rate-limit.store.d.ts +10 -0
  128. package/dist/hardening/origin-secret.d.ts +29 -0
  129. package/dist/hardening/rate-limit.decorator.d.ts +8 -0
  130. package/dist/hardening/rate-limit.guard.d.ts +18 -0
  131. package/dist/hardening/rate-limit.module.d.ts +23 -0
  132. package/dist/hardening/rate-limit.options.d.ts +35 -0
  133. package/dist/hardening/rate-limit.port.d.ts +11 -0
  134. package/dist/hardening/redis-rate-limit.store.d.ts +23 -0
  135. package/dist/hardening/trust-proxy.d.ts +22 -0
  136. package/dist/health/health.controller.d.ts +32 -0
  137. package/dist/health/health.module.d.ts +15 -0
  138. package/dist/health/health.options.d.ts +24 -0
  139. package/dist/health/index.cjs +103 -0
  140. package/dist/health/index.d.ts +5 -0
  141. package/dist/health/index.js +103 -0
  142. package/dist/i18n/index.cjs +3 -3
  143. package/dist/i18n/index.js +2 -2
  144. package/dist/idempotency/idempotency.interceptor.d.ts +1 -0
  145. package/dist/idempotency/idempotency.options.d.ts +15 -0
  146. package/dist/idempotency/index.cjs +214 -7
  147. package/dist/idempotency/index.d.ts +5 -0
  148. package/dist/idempotency/index.js +210 -3
  149. package/dist/idempotency/no-idempotency.decorator.d.ts +8 -0
  150. package/dist/idempotency/postgres.store.d.ts +49 -0
  151. package/dist/idempotency/redis.store.d.ts +59 -0
  152. package/dist/index.cjs +21 -20
  153. package/dist/index.js +31 -30
  154. package/dist/invoicing/index.cjs +2 -2
  155. package/dist/invoicing/index.js +1 -1
  156. package/dist/jobs/defer-job.d.ts +10 -0
  157. package/dist/jobs/index.cjs +318 -0
  158. package/dist/jobs/index.d.ts +8 -0
  159. package/dist/jobs/index.js +318 -0
  160. package/dist/jobs/jobs-admin.controller.d.ts +18 -0
  161. package/dist/jobs/jobs.module.d.ts +33 -0
  162. package/dist/jobs/jobs.options.d.ts +62 -0
  163. package/dist/jobs/jobs.service.d.ts +53 -0
  164. package/dist/jobs/jobs.sql.d.ts +11 -0
  165. package/dist/media/index.cjs +14 -14
  166. package/dist/media/index.js +1 -1
  167. package/dist/meta/index.cjs +3 -3
  168. package/dist/meta/index.js +1 -1
  169. package/dist/notifications/index.cjs +375 -0
  170. package/dist/notifications/index.d.ts +8 -0
  171. package/dist/notifications/index.js +375 -0
  172. package/dist/notifications/memory.stores.d.ts +23 -0
  173. package/dist/notifications/notifications.controller.d.ts +11 -0
  174. package/dist/notifications/notifications.module.d.ts +31 -0
  175. package/dist/notifications/notifications.options.d.ts +33 -0
  176. package/dist/notifications/notifications.port.d.ts +97 -0
  177. package/dist/notifications/notifier.service.d.ts +31 -0
  178. package/dist/payments/index.cjs +7 -7
  179. package/dist/payments/index.js +1 -1
  180. package/dist/pinterest/index.cjs +3 -3
  181. package/dist/pinterest/index.js +1 -1
  182. package/dist/privacy/anonymizer.d.ts +14 -0
  183. package/dist/privacy/index.cjs +768 -0
  184. package/dist/privacy/index.d.ts +13 -0
  185. package/dist/privacy/index.js +768 -0
  186. package/dist/privacy/memory.store.d.ts +15 -0
  187. package/dist/privacy/privacy.module.d.ts +30 -0
  188. package/dist/privacy/privacy.options.d.ts +43 -0
  189. package/dist/privacy/privacy.port.d.ts +25 -0
  190. package/dist/privacy/privacy.service.d.ts +69 -0
  191. package/dist/privacy/privacy.types.d.ts +125 -0
  192. package/dist/privacy/sql.d.ts +7 -0
  193. package/dist/privacy/sql.store.d.ts +21 -0
  194. package/dist/privacy/zip.d.ts +23 -0
  195. package/dist/push/index.cjs +13 -13
  196. package/dist/push/index.js +5 -5
  197. package/dist/resilience/alert-channels.d.ts +39 -0
  198. package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
  199. package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
  200. package/dist/resilience/alert.service.d.ts +77 -0
  201. package/dist/resilience/index.cjs +863 -0
  202. package/dist/resilience/index.d.ts +18 -0
  203. package/dist/resilience/index.js +863 -0
  204. package/dist/resilience/memory-alert-store.d.ts +26 -0
  205. package/dist/resilience/provider-health.controller.d.ts +14 -0
  206. package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
  207. package/dist/resilience/resilience.module.d.ts +34 -0
  208. package/dist/resilience/resilience.options.d.ts +28 -0
  209. package/dist/resilience/resilience.types.d.ts +167 -0
  210. package/dist/resilience/resilient-fetch.d.ts +38 -0
  211. package/dist/resilience/runtime.d.ts +24 -0
  212. package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
  213. package/dist/resilience/typeorm/index.cjs +102 -0
  214. package/dist/resilience/typeorm/index.d.ts +3 -0
  215. package/dist/resilience/typeorm/index.js +102 -0
  216. package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
  217. package/dist/resilience/validate-destination.d.ts +63 -0
  218. package/dist/response/index.cjs +3 -3
  219. package/dist/response/index.js +2 -2
  220. package/dist/scheduling/cron-lock.service.d.ts +36 -0
  221. package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
  222. package/dist/scheduling/fallback.store.d.ts +34 -0
  223. package/dist/scheduling/index.cjs +392 -0
  224. package/dist/scheduling/index.d.ts +18 -0
  225. package/dist/scheduling/index.js +392 -0
  226. package/dist/scheduling/lock-store.port.d.ts +19 -0
  227. package/dist/scheduling/memory.store.d.ts +15 -0
  228. package/dist/scheduling/redis.module.d.ts +31 -0
  229. package/dist/scheduling/redis.store.d.ts +24 -0
  230. package/dist/scheduling/scheduling.module.d.ts +24 -0
  231. package/dist/scheduling/scheduling.options.d.ts +27 -0
  232. package/dist/scheduling/sql.store.d.ts +26 -0
  233. package/dist/secrets/index.cjs +274 -0
  234. package/dist/secrets/index.d.ts +8 -0
  235. package/dist/secrets/index.js +274 -0
  236. package/dist/secrets/secrets.errors.d.ts +6 -0
  237. package/dist/secrets/secrets.module.d.ts +21 -0
  238. package/dist/secrets/secrets.options.d.ts +32 -0
  239. package/dist/secrets/secrets.service.d.ts +54 -0
  240. package/dist/secrets/secrets.transformer.d.ts +33 -0
  241. package/dist/security/hash.d.ts +8 -0
  242. package/dist/security/index.cjs +119 -2
  243. package/dist/security/index.d.ts +5 -0
  244. package/dist/security/index.js +119 -2
  245. package/dist/security/mask.d.ts +22 -0
  246. package/dist/security/signed-grant.d.ts +30 -0
  247. package/dist/storage/index.cjs +2 -2
  248. package/dist/storage/index.js +1 -1
  249. package/dist/stripe/index.cjs +7 -7
  250. package/dist/stripe/index.js +1 -1
  251. package/dist/telegram/index.cjs +2 -2
  252. package/dist/telegram/index.js +1 -1
  253. package/dist/tenancy/app-role.d.ts +24 -0
  254. package/dist/tenancy/db-helpers.d.ts +12 -0
  255. package/dist/tenancy/index.cjs +205 -0
  256. package/dist/tenancy/index.d.ts +14 -0
  257. package/dist/tenancy/index.js +205 -0
  258. package/dist/tenancy/pg/index.cjs +34 -0
  259. package/dist/tenancy/pg/index.d.ts +2 -0
  260. package/dist/tenancy/pg/index.js +34 -0
  261. package/dist/tenancy/pg/with-tenant.d.ts +23 -0
  262. package/dist/tenancy/request-context.d.ts +18 -0
  263. package/dist/tenancy/rls-guardrail.d.ts +38 -0
  264. package/dist/tenancy/scope.d.ts +5 -0
  265. package/dist/tenancy/tenancy.errors.d.ts +5 -0
  266. package/dist/tenancy/tenancy.middleware.d.ts +8 -0
  267. package/dist/tenancy/tenancy.module.d.ts +37 -0
  268. package/dist/tenancy/tenancy.options.d.ts +34 -0
  269. package/dist/tenancy/typeorm/index.cjs +41 -0
  270. package/dist/tenancy/typeorm/index.d.ts +2 -0
  271. package/dist/tenancy/typeorm/index.js +41 -0
  272. package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
  273. package/dist/tiktok/index.cjs +3 -3
  274. package/dist/tiktok/index.js +1 -1
  275. package/dist/tracking/index.cjs +3 -3
  276. package/dist/tracking/index.js +2 -2
  277. package/dist/umami/index.cjs +4 -4
  278. package/dist/umami/index.js +1 -1
  279. package/dist/whatsapp/index.cjs +2 -2
  280. package/dist/whatsapp/index.js +1 -1
  281. package/package.json +107 -2
@@ -0,0 +1,205 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+ var _chunkLGFHLAY3cjs = require('../chunk-LGFHLAY3.cjs');
8
+
9
+
10
+
11
+ var _chunkLRX7AMSScjs = require('../chunk-LRX7AMSS.cjs');
12
+
13
+ // src/tenancy/tenancy.module.ts
14
+
15
+
16
+
17
+
18
+ var _common = require('@nestjs/common');
19
+
20
+ // src/tenancy/rls-guardrail.ts
21
+
22
+ var RLS_GUARDRAIL_OPTIONS = /* @__PURE__ */ Symbol("RLS_GUARDRAIL_OPTIONS");
23
+ var RLS_GUARDRAIL_DB = /* @__PURE__ */ Symbol("RLS_GUARDRAIL_DB");
24
+ async function checkAppRole(db) {
25
+ const { rows } = await db.query(
26
+ `select current_user as usuario,
27
+ coalesce((select rolbypassrls from pg_roles where rolname = current_user), false) as bypassrls,
28
+ coalesce((select rolsuper from pg_roles where rolname = current_user), false) as superusuario`
29
+ );
30
+ const r = _nullishCoalesce(rows[0], () => ( {}));
31
+ return {
32
+ user: String(_nullishCoalesce(r.usuario, () => ( ""))),
33
+ bypassRls: r.bypassrls === true,
34
+ superuser: r.superusuario === true
35
+ };
36
+ }
37
+ var RlsGuardrail = class {
38
+ constructor(db, options = {}) {
39
+ this.db = db;
40
+ this.options = options;
41
+ this.log = new (0, _common.Logger)(RlsGuardrail.name);
42
+ }
43
+ async onApplicationBootstrap() {
44
+ let role;
45
+ try {
46
+ role = await checkAppRole(this.db);
47
+ } catch (error) {
48
+ this.log.warn(`Could not verify the database role: ${String(error)}`);
49
+ return;
50
+ }
51
+ if (!role.bypassRls && !role.superuser) {
52
+ this.log.log(`RLS active: the app connects as "${role.user}" (does not skip RLS).`);
53
+ return;
54
+ }
55
+ const message = `The app connects as "${role.user}", a role that IGNORES Row-Level Security (${role.superuser ? "superuser" : "BYPASSRLS"}). Tenant isolation is OFF: every tenant can read every other tenant's data.${this.options.hint ? ` ${this.options.hint}` : ""}`;
56
+ const env = _nullishCoalesce(this.options.env, () => ( process.env.NODE_ENV));
57
+ const enforce = !(_nullishCoalesce(this.options.productionOnly, () => ( true))) || env === "production";
58
+ if (enforce && (_nullishCoalesce(this.options.onBypass, () => ( "abort"))) === "abort") {
59
+ throw new Error(`BOOT ABORTED - ${message}`);
60
+ }
61
+ this.log.error(message);
62
+ }
63
+ };
64
+ RlsGuardrail = exports.RlsGuardrail = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
65
+ _common.Injectable.call(void 0, ),
66
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, RLS_GUARDRAIL_DB)),
67
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, RLS_GUARDRAIL_OPTIONS))
68
+ ], RlsGuardrail);
69
+
70
+ // src/tenancy/tenancy.middleware.ts
71
+
72
+ var TenancyMiddleware = class {
73
+ constructor(options) {
74
+ this.options = options;
75
+ }
76
+ use(req, _res, next) {
77
+ let tenantId;
78
+ let actorId;
79
+ try {
80
+ tenantId = _optionalChain([this, 'access', _ => _.options, 'access', _2 => _2.resolveTenant, 'optionalCall', _3 => _3(req)]);
81
+ actorId = _optionalChain([this, 'access', _4 => _4.options, 'access', _5 => _5.resolveActor, 'optionalCall', _6 => _6(req)]);
82
+ } catch (e2) {
83
+ }
84
+ _chunkLGFHLAY3cjs.TenancyContext.run(() => next(), { tenantId, actorId });
85
+ }
86
+ };
87
+ TenancyMiddleware = exports.TenancyMiddleware = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
88
+ _common.Injectable.call(void 0, ),
89
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, _chunkLGFHLAY3cjs.TENANCY_OPTIONS))
90
+ ], TenancyMiddleware);
91
+
92
+ // src/tenancy/tenancy.module.ts
93
+ function providers(options) {
94
+ return [options, TenancyMiddleware];
95
+ }
96
+ var TenancyModule = class {
97
+ constructor(options) {
98
+ this.options = options;
99
+ }
100
+ configure(consumer) {
101
+ if (this.options.middleware !== false) consumer.apply(TenancyMiddleware).forRoutes("*");
102
+ }
103
+ static forRoot(options) {
104
+ const { guardrail, ...core } = options;
105
+ const list = providers({ provide: _chunkLGFHLAY3cjs.TENANCY_OPTIONS, useValue: core });
106
+ if (guardrail) {
107
+ const { db, ...rest } = guardrail;
108
+ list.push(
109
+ { provide: RLS_GUARDRAIL_DB, useValue: db },
110
+ { provide: RLS_GUARDRAIL_OPTIONS, useValue: rest },
111
+ RlsGuardrail
112
+ );
113
+ }
114
+ return { module: TenancyModule, providers: list, exports: [_chunkLGFHLAY3cjs.TENANCY_OPTIONS] };
115
+ }
116
+ static forRootAsync(config) {
117
+ const raw = { provide: "TENANCY_RAW", useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) };
118
+ const list = [
119
+ raw,
120
+ { provide: _chunkLGFHLAY3cjs.TENANCY_OPTIONS, useFactory: (o) => {
121
+ const { guardrail: _g, ...core } = o;
122
+ return core;
123
+ }, inject: ["TENANCY_RAW"] },
124
+ TenancyMiddleware,
125
+ { provide: RLS_GUARDRAIL_DB, useFactory: (o) => _optionalChain([o, 'access', _7 => _7.guardrail, 'optionalAccess', _8 => _8.db]), inject: ["TENANCY_RAW"] },
126
+ {
127
+ provide: RLS_GUARDRAIL_OPTIONS,
128
+ useFactory: (o) => {
129
+ const { db: _d, ...rest } = _nullishCoalesce(o.guardrail, () => ( { db: void 0 }));
130
+ return rest;
131
+ },
132
+ inject: ["TENANCY_RAW"]
133
+ },
134
+ {
135
+ provide: RlsGuardrail,
136
+ useFactory: (o, db, opts) => o.guardrail ? new RlsGuardrail(db, opts) : { onApplicationBootstrap: async () => {
137
+ } },
138
+ inject: ["TENANCY_RAW", RLS_GUARDRAIL_DB, RLS_GUARDRAIL_OPTIONS]
139
+ }
140
+ ];
141
+ return { module: TenancyModule, imports: _nullishCoalesce(config.imports, () => ( [])), providers: list, exports: [_chunkLGFHLAY3cjs.TENANCY_OPTIONS] };
142
+ }
143
+ };
144
+ TenancyModule = exports.TenancyModule = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
145
+ _common.Global.call(void 0, ),
146
+ _common.Module.call(void 0, {}),
147
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, _chunkLGFHLAY3cjs.TENANCY_OPTIONS))
148
+ ], TenancyModule);
149
+
150
+ // src/tenancy/app-role.ts
151
+ var IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
152
+ async function ensureAppRole(admin, options) {
153
+ const { role, password, db, bypassRls = false, schema = "public" } = options;
154
+ if (!IDENT.test(role) || !IDENT.test(db) || !IDENT.test(schema)) {
155
+ throw new Error("Invalid role, database or schema name.");
156
+ }
157
+ const pass = `'${password.replace(/'/g, "''")}'`;
158
+ const exists = await admin.query("SELECT 1 FROM pg_roles WHERE rolname = $1", [role]);
159
+ if (!exists.rowCount) {
160
+ await admin.query(
161
+ `CREATE ROLE ${role} LOGIN PASSWORD ${pass} NOSUPERUSER ${bypassRls ? "BYPASSRLS" : "NOBYPASSRLS"} NOCREATEDB NOCREATEROLE`
162
+ );
163
+ }
164
+ await admin.query(`GRANT CONNECT ON DATABASE ${db} TO ${role}`);
165
+ await admin.query(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`);
166
+ await admin.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`);
167
+ await admin.query(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${role}`);
168
+ await admin.query(
169
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${role}`
170
+ );
171
+ await admin.query(
172
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT USAGE, SELECT ON SEQUENCES TO ${role}`
173
+ );
174
+ }
175
+
176
+ // src/tenancy/db-helpers.ts
177
+ function pgSqlState(error) {
178
+ const e = error;
179
+ const code = _nullishCoalesce(_optionalChain([e, 'optionalAccess', _9 => _9.code]), () => ( _optionalChain([e, 'optionalAccess', _10 => _10.driverError, 'optionalAccess', _11 => _11.code])));
180
+ return typeof code === "string" ? code : void 0;
181
+ }
182
+ function updatedRows(result) {
183
+ if (result && !Array.isArray(result) && Array.isArray(result.rows)) {
184
+ return result.rows;
185
+ }
186
+ if (!Array.isArray(result)) return [];
187
+ const isTuple = result.length === 2 && Array.isArray(result[0]) && typeof result[1] === "number";
188
+ return isTuple ? result[0] : result;
189
+ }
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+ exports.DEFAULT_GUCS = _chunkLGFHLAY3cjs.DEFAULT_GUCS; exports.RLS_GUARDRAIL_DB = RLS_GUARDRAIL_DB; exports.RLS_GUARDRAIL_OPTIONS = RLS_GUARDRAIL_OPTIONS; exports.RlsGuardrail = RlsGuardrail; exports.TENANCY_OPTIONS = _chunkLGFHLAY3cjs.TENANCY_OPTIONS; exports.TenancyContext = _chunkLGFHLAY3cjs.TenancyContext; exports.TenancyMiddleware = TenancyMiddleware; exports.TenancyModule = TenancyModule; exports.TenantRequiredError = _chunkLGFHLAY3cjs.TenantRequiredError; exports.applyScope = _chunkLGFHLAY3cjs.applyScope; exports.checkAppRole = checkAppRole; exports.ensureAppRole = ensureAppRole; exports.pgSqlState = pgSqlState; exports.updatedRows = updatedRows;
@@ -0,0 +1,14 @@
1
+ export { TenancyModule } from './tenancy.module.js';
2
+ export type { TenancyModuleOptions } from './tenancy.module.js';
3
+ export { TENANCY_OPTIONS, DEFAULT_GUCS } from './tenancy.options.js';
4
+ export type { TenancyOptions, TenancyGucs, ScopeOptions, TenantScope } from './tenancy.options.js';
5
+ export { TenancyContext } from './request-context.js';
6
+ export { TenancyMiddleware } from './tenancy.middleware.js';
7
+ export { TenantRequiredError } from './tenancy.errors.js';
8
+ export { applyScope } from './scope.js';
9
+ export type { QueryFn } from './scope.js';
10
+ export { RlsGuardrail, checkAppRole, RLS_GUARDRAIL_DB, RLS_GUARDRAIL_OPTIONS } from './rls-guardrail.js';
11
+ export type { RlsGuardrailOptions, RlsDb, RoleCheck } from './rls-guardrail.js';
12
+ export { ensureAppRole } from './app-role.js';
13
+ export type { EnsureAppRoleOptions, AdminLike } from './app-role.js';
14
+ export { pgSqlState, updatedRows } from './db-helpers.js';
@@ -0,0 +1,205 @@
1
+ import {
2
+ DEFAULT_GUCS,
3
+ TENANCY_OPTIONS,
4
+ TenancyContext,
5
+ TenantRequiredError,
6
+ applyScope
7
+ } from "../chunk-FBNV5X6C.js";
8
+ import {
9
+ __decorateClass,
10
+ __decorateParam
11
+ } from "../chunk-D3DDJWUD.js";
12
+
13
+ // src/tenancy/tenancy.module.ts
14
+ import {
15
+ Global,
16
+ Inject as Inject3,
17
+ Module
18
+ } from "@nestjs/common";
19
+
20
+ // src/tenancy/rls-guardrail.ts
21
+ import { Inject, Injectable, Logger } from "@nestjs/common";
22
+ var RLS_GUARDRAIL_OPTIONS = /* @__PURE__ */ Symbol("RLS_GUARDRAIL_OPTIONS");
23
+ var RLS_GUARDRAIL_DB = /* @__PURE__ */ Symbol("RLS_GUARDRAIL_DB");
24
+ async function checkAppRole(db) {
25
+ const { rows } = await db.query(
26
+ `select current_user as usuario,
27
+ coalesce((select rolbypassrls from pg_roles where rolname = current_user), false) as bypassrls,
28
+ coalesce((select rolsuper from pg_roles where rolname = current_user), false) as superusuario`
29
+ );
30
+ const r = rows[0] ?? {};
31
+ return {
32
+ user: String(r.usuario ?? ""),
33
+ bypassRls: r.bypassrls === true,
34
+ superuser: r.superusuario === true
35
+ };
36
+ }
37
+ var RlsGuardrail = class {
38
+ constructor(db, options = {}) {
39
+ this.db = db;
40
+ this.options = options;
41
+ this.log = new Logger(RlsGuardrail.name);
42
+ }
43
+ async onApplicationBootstrap() {
44
+ let role;
45
+ try {
46
+ role = await checkAppRole(this.db);
47
+ } catch (error) {
48
+ this.log.warn(`Could not verify the database role: ${String(error)}`);
49
+ return;
50
+ }
51
+ if (!role.bypassRls && !role.superuser) {
52
+ this.log.log(`RLS active: the app connects as "${role.user}" (does not skip RLS).`);
53
+ return;
54
+ }
55
+ const message = `The app connects as "${role.user}", a role that IGNORES Row-Level Security (${role.superuser ? "superuser" : "BYPASSRLS"}). Tenant isolation is OFF: every tenant can read every other tenant's data.${this.options.hint ? ` ${this.options.hint}` : ""}`;
56
+ const env = this.options.env ?? process.env.NODE_ENV;
57
+ const enforce = !(this.options.productionOnly ?? true) || env === "production";
58
+ if (enforce && (this.options.onBypass ?? "abort") === "abort") {
59
+ throw new Error(`BOOT ABORTED - ${message}`);
60
+ }
61
+ this.log.error(message);
62
+ }
63
+ };
64
+ RlsGuardrail = __decorateClass([
65
+ Injectable(),
66
+ __decorateParam(0, Inject(RLS_GUARDRAIL_DB)),
67
+ __decorateParam(1, Inject(RLS_GUARDRAIL_OPTIONS))
68
+ ], RlsGuardrail);
69
+
70
+ // src/tenancy/tenancy.middleware.ts
71
+ import { Inject as Inject2, Injectable as Injectable2 } from "@nestjs/common";
72
+ var TenancyMiddleware = class {
73
+ constructor(options) {
74
+ this.options = options;
75
+ }
76
+ use(req, _res, next) {
77
+ let tenantId;
78
+ let actorId;
79
+ try {
80
+ tenantId = this.options.resolveTenant?.(req);
81
+ actorId = this.options.resolveActor?.(req);
82
+ } catch {
83
+ }
84
+ TenancyContext.run(() => next(), { tenantId, actorId });
85
+ }
86
+ };
87
+ TenancyMiddleware = __decorateClass([
88
+ Injectable2(),
89
+ __decorateParam(0, Inject2(TENANCY_OPTIONS))
90
+ ], TenancyMiddleware);
91
+
92
+ // src/tenancy/tenancy.module.ts
93
+ function providers(options) {
94
+ return [options, TenancyMiddleware];
95
+ }
96
+ var TenancyModule = class {
97
+ constructor(options) {
98
+ this.options = options;
99
+ }
100
+ configure(consumer) {
101
+ if (this.options.middleware !== false) consumer.apply(TenancyMiddleware).forRoutes("*");
102
+ }
103
+ static forRoot(options) {
104
+ const { guardrail, ...core } = options;
105
+ const list = providers({ provide: TENANCY_OPTIONS, useValue: core });
106
+ if (guardrail) {
107
+ const { db, ...rest } = guardrail;
108
+ list.push(
109
+ { provide: RLS_GUARDRAIL_DB, useValue: db },
110
+ { provide: RLS_GUARDRAIL_OPTIONS, useValue: rest },
111
+ RlsGuardrail
112
+ );
113
+ }
114
+ return { module: TenancyModule, providers: list, exports: [TENANCY_OPTIONS] };
115
+ }
116
+ static forRootAsync(config) {
117
+ const raw = { provide: "TENANCY_RAW", useFactory: config.useFactory, inject: config.inject ?? [] };
118
+ const list = [
119
+ raw,
120
+ { provide: TENANCY_OPTIONS, useFactory: (o) => {
121
+ const { guardrail: _g, ...core } = o;
122
+ return core;
123
+ }, inject: ["TENANCY_RAW"] },
124
+ TenancyMiddleware,
125
+ { provide: RLS_GUARDRAIL_DB, useFactory: (o) => o.guardrail?.db, inject: ["TENANCY_RAW"] },
126
+ {
127
+ provide: RLS_GUARDRAIL_OPTIONS,
128
+ useFactory: (o) => {
129
+ const { db: _d, ...rest } = o.guardrail ?? { db: void 0 };
130
+ return rest;
131
+ },
132
+ inject: ["TENANCY_RAW"]
133
+ },
134
+ {
135
+ provide: RlsGuardrail,
136
+ useFactory: (o, db, opts) => o.guardrail ? new RlsGuardrail(db, opts) : { onApplicationBootstrap: async () => {
137
+ } },
138
+ inject: ["TENANCY_RAW", RLS_GUARDRAIL_DB, RLS_GUARDRAIL_OPTIONS]
139
+ }
140
+ ];
141
+ return { module: TenancyModule, imports: config.imports ?? [], providers: list, exports: [TENANCY_OPTIONS] };
142
+ }
143
+ };
144
+ TenancyModule = __decorateClass([
145
+ Global(),
146
+ Module({}),
147
+ __decorateParam(0, Inject3(TENANCY_OPTIONS))
148
+ ], TenancyModule);
149
+
150
+ // src/tenancy/app-role.ts
151
+ var IDENT = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
152
+ async function ensureAppRole(admin, options) {
153
+ const { role, password, db, bypassRls = false, schema = "public" } = options;
154
+ if (!IDENT.test(role) || !IDENT.test(db) || !IDENT.test(schema)) {
155
+ throw new Error("Invalid role, database or schema name.");
156
+ }
157
+ const pass = `'${password.replace(/'/g, "''")}'`;
158
+ const exists = await admin.query("SELECT 1 FROM pg_roles WHERE rolname = $1", [role]);
159
+ if (!exists.rowCount) {
160
+ await admin.query(
161
+ `CREATE ROLE ${role} LOGIN PASSWORD ${pass} NOSUPERUSER ${bypassRls ? "BYPASSRLS" : "NOBYPASSRLS"} NOCREATEDB NOCREATEROLE`
162
+ );
163
+ }
164
+ await admin.query(`GRANT CONNECT ON DATABASE ${db} TO ${role}`);
165
+ await admin.query(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`);
166
+ await admin.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`);
167
+ await admin.query(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${role}`);
168
+ await admin.query(
169
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${role}`
170
+ );
171
+ await admin.query(
172
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA ${schema} GRANT USAGE, SELECT ON SEQUENCES TO ${role}`
173
+ );
174
+ }
175
+
176
+ // src/tenancy/db-helpers.ts
177
+ function pgSqlState(error) {
178
+ const e = error;
179
+ const code = e?.code ?? e?.driverError?.code;
180
+ return typeof code === "string" ? code : void 0;
181
+ }
182
+ function updatedRows(result) {
183
+ if (result && !Array.isArray(result) && Array.isArray(result.rows)) {
184
+ return result.rows;
185
+ }
186
+ if (!Array.isArray(result)) return [];
187
+ const isTuple = result.length === 2 && Array.isArray(result[0]) && typeof result[1] === "number";
188
+ return isTuple ? result[0] : result;
189
+ }
190
+ export {
191
+ DEFAULT_GUCS,
192
+ RLS_GUARDRAIL_DB,
193
+ RLS_GUARDRAIL_OPTIONS,
194
+ RlsGuardrail,
195
+ TENANCY_OPTIONS,
196
+ TenancyContext,
197
+ TenancyMiddleware,
198
+ TenancyModule,
199
+ TenantRequiredError,
200
+ applyScope,
201
+ checkAppRole,
202
+ ensureAppRole,
203
+ pgSqlState,
204
+ updatedRows
205
+ };
@@ -0,0 +1,34 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkLGFHLAY3cjs = require('../../chunk-LGFHLAY3.cjs');
4
+ require('../../chunk-LRX7AMSS.cjs');
5
+
6
+ // src/tenancy/pg/with-tenant.ts
7
+ async function run(pool, begin, scope, fn, options) {
8
+ const client = await pool.connect();
9
+ try {
10
+ await client.query(begin);
11
+ await _chunkLGFHLAY3cjs.applyScope.call(void 0, (sql, params) => client.query(sql, params), scope, options);
12
+ const result = await fn(client);
13
+ await client.query("COMMIT");
14
+ return result;
15
+ } catch (error) {
16
+ try {
17
+ await client.query("ROLLBACK");
18
+ } catch (e) {
19
+ }
20
+ throw error;
21
+ } finally {
22
+ client.release();
23
+ }
24
+ }
25
+ function withTenant(pool, scope, fn, options) {
26
+ return run(pool, "BEGIN", scope, fn, options);
27
+ }
28
+ function withTenantSnapshot(pool, scope, fn, options) {
29
+ return run(pool, "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY", scope, fn, options);
30
+ }
31
+
32
+
33
+
34
+ exports.withTenant = withTenant; exports.withTenantSnapshot = withTenantSnapshot;
@@ -0,0 +1,2 @@
1
+ export { withTenant, withTenantSnapshot } from './with-tenant.js';
2
+ export type { PgClientLike, PgPoolLike } from './with-tenant.js';
@@ -0,0 +1,34 @@
1
+ import {
2
+ applyScope
3
+ } from "../../chunk-FBNV5X6C.js";
4
+ import "../../chunk-D3DDJWUD.js";
5
+
6
+ // src/tenancy/pg/with-tenant.ts
7
+ async function run(pool, begin, scope, fn, options) {
8
+ const client = await pool.connect();
9
+ try {
10
+ await client.query(begin);
11
+ await applyScope((sql, params) => client.query(sql, params), scope, options);
12
+ const result = await fn(client);
13
+ await client.query("COMMIT");
14
+ return result;
15
+ } catch (error) {
16
+ try {
17
+ await client.query("ROLLBACK");
18
+ } catch {
19
+ }
20
+ throw error;
21
+ } finally {
22
+ client.release();
23
+ }
24
+ }
25
+ function withTenant(pool, scope, fn, options) {
26
+ return run(pool, "BEGIN", scope, fn, options);
27
+ }
28
+ function withTenantSnapshot(pool, scope, fn, options) {
29
+ return run(pool, "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY", scope, fn, options);
30
+ }
31
+ export {
32
+ withTenant,
33
+ withTenantSnapshot
34
+ };
@@ -0,0 +1,23 @@
1
+ import type { ScopeOptions, TenantScope } from '../tenancy.options.js';
2
+ /** Structural `pg` client: nothing is imported from `pg`. */
3
+ export interface PgClientLike {
4
+ query(sql: string, params?: any[]): Promise<unknown>;
5
+ release(error?: Error | boolean): void;
6
+ }
7
+ /** Structural `pg.Pool`. */
8
+ export interface PgPoolLike {
9
+ connect(): Promise<PgClientLike>;
10
+ }
11
+ /**
12
+ * `pg` flavour. BEGIN, `set_config(guc, value, true)` for tenant and actor, `fn`, COMMIT / ROLLBACK,
13
+ * and the client is always released. Generalizes `database/postgres#withTenantScope` (which only
14
+ * sets `request.jwt.claim.sub`); that one stays for existing users, this one takes the GUC names.
15
+ * Tenant/actor not given fall back to `TenancyContext`.
16
+ */
17
+ export declare function withTenant<T>(pool: PgPoolLike, scope: TenantScope, fn: (client: PgClientLike) => Promise<T>, options?: ScopeOptions): Promise<T>;
18
+ /**
19
+ * Read-only, ONE snapshot (`REPEATABLE READ`): every query in `fn` sees the database as it was when
20
+ * the first one ran, even with concurrent writes. For reports that split one figure across several
21
+ * queries and must add up.
22
+ */
23
+ export declare function withTenantSnapshot<T>(pool: PgPoolLike, scope: TenantScope, fn: (client: PgClientLike) => Promise<T>, options?: ScopeOptions): Promise<T>;
@@ -0,0 +1,18 @@
1
+ interface Store {
2
+ tenantId?: string;
3
+ actorId?: string;
4
+ }
5
+ /**
6
+ * Per-request tenant/actor, so repositories do not need them in every signature.
7
+ * Same technique as `RequestContext` (tracking) uses for the request id. The middleware opens the
8
+ * store; a resolver or a guard fills it once it knows who is calling. Outside a request (worker,
9
+ * boot) everything reads `undefined`, which with `failClosed` means "pass the tenant explicitly".
10
+ */
11
+ export declare const TenancyContext: {
12
+ run<T>(fn: () => T, initial?: Store): T;
13
+ setTenant(tenantId: string | undefined): void;
14
+ setActor(actorId: string | undefined): void;
15
+ tenantId(): string | undefined;
16
+ actorId(): string | undefined;
17
+ };
18
+ export {};
@@ -0,0 +1,38 @@
1
+ import { type OnApplicationBootstrap } from '@nestjs/common';
2
+ export declare const RLS_GUARDRAIL_OPTIONS: unique symbol;
3
+ /** Provide something with `query(sql)` returning `{ rows }` (a pg Pool, or a TypeORM DataSource via an adapter). */
4
+ export declare const RLS_GUARDRAIL_DB: unique symbol;
5
+ export interface RlsGuardrailOptions {
6
+ /** `abort` throws at boot (default); `warn` logs loudly. */
7
+ onBypass?: 'abort' | 'warn';
8
+ /** Only enforce `onBypass` when NODE_ENV is production; elsewhere it warns. Default true. */
9
+ productionOnly?: boolean;
10
+ /** Mentioned in the message so whoever reads the log knows what to change. */
11
+ hint?: string;
12
+ /** Environment, for tests. Defaults to `process.env.NODE_ENV`. */
13
+ env?: string;
14
+ }
15
+ export interface RlsDb {
16
+ query(sql: string): Promise<{
17
+ rows: Array<Record<string, unknown>>;
18
+ }>;
19
+ }
20
+ export interface RoleCheck {
21
+ user: string;
22
+ bypassRls: boolean;
23
+ superuser: boolean;
24
+ }
25
+ /** Asks Postgres with which role the app connects and whether it skips RLS. */
26
+ export declare function checkAppRole(db: RlsDb): Promise<RoleCheck>;
27
+ /**
28
+ * A role with BYPASSRLS or superuser ignores RLS ALWAYS (even with FORCE) and says nothing: the app
29
+ * keeps "working" while every tenant sees every other tenant's data. Catch it at boot.
30
+ * If the role cannot even be queried, boot is not blocked (it warns).
31
+ */
32
+ export declare class RlsGuardrail implements OnApplicationBootstrap {
33
+ private readonly db;
34
+ private readonly options;
35
+ private readonly log;
36
+ constructor(db: RlsDb, options?: RlsGuardrailOptions);
37
+ onApplicationBootstrap(): Promise<void>;
38
+ }
@@ -0,0 +1,5 @@
1
+ import { type ScopeOptions, type TenantScope } from './tenancy.options.js';
2
+ /** The only thing the scope needs from a connection: run SQL. Satisfied by pg and TypeORM runners. */
3
+ export type QueryFn = (sql: string, params?: unknown[]) => Promise<unknown>;
4
+ /** Applies the tenant (and actor) GUCs with `set_config(name, value, true)`: transaction-local. */
5
+ export declare function applyScope(query: QueryFn, scope: TenantScope, options?: ScopeOptions): Promise<void>;
@@ -0,0 +1,5 @@
1
+ /** Thrown (fail-closed) when a scoped transaction is requested with no tenant. */
2
+ export declare class TenantRequiredError extends Error {
3
+ readonly code = "TENANT_REQUIRED";
4
+ constructor(message?: string);
5
+ }
@@ -0,0 +1,8 @@
1
+ import { type NestMiddleware } from '@nestjs/common';
2
+ import { type TenancyOptions } from './tenancy.options.js';
3
+ /** Opens the tenancy store for the request and applies `resolveTenant` / `resolveActor`. */
4
+ export declare class TenancyMiddleware implements NestMiddleware {
5
+ private readonly options;
6
+ constructor(options: TenancyOptions);
7
+ use(req: unknown, _res: unknown, next: () => void): void;
8
+ }
@@ -0,0 +1,37 @@
1
+ import { type DynamicModule, type MiddlewareConsumer, type NestModule } from '@nestjs/common';
2
+ import { type RlsDb, type RlsGuardrailOptions } from './rls-guardrail.js';
3
+ import { type TenancyOptions } from './tenancy.options.js';
4
+ export interface TenancyModuleOptions extends TenancyOptions {
5
+ /** Enables the boot-time role check. Needs `db` (anything with `query(sql) => {rows}`). */
6
+ guardrail?: RlsGuardrailOptions & {
7
+ db: RlsDb;
8
+ };
9
+ }
10
+ /**
11
+ * Tenant context + (optional) RLS guardrail.
12
+ *
13
+ * ```ts
14
+ * TenancyModule.forRoot({
15
+ * gucs: { tenant: 'app.tienda_id', actor: 'app.usuario_id' },
16
+ * failClosed: true,
17
+ * resolveTenant: (req) => req.user?.tiendaId,
18
+ * guardrail: { db: pool, onBypass: 'abort' },
19
+ * })
20
+ * // data access: import { withTenant } from '@miguelmorales13/nestkit/tenancy/pg' (or /typeorm)
21
+ * ```
22
+ *
23
+ * Relation to `database/*`: `database/postgres` and `database/typeorm` keep their
24
+ * `withTenantScope` (hard-wired / free-form GUC map). This module adds the configurable names, the
25
+ * request context, fail-closed and the snapshot; it does not touch them.
26
+ */
27
+ export declare class TenancyModule implements NestModule {
28
+ private readonly options;
29
+ constructor(options: TenancyOptions);
30
+ configure(consumer: MiddlewareConsumer): void;
31
+ static forRoot(options: TenancyModuleOptions): DynamicModule;
32
+ static forRootAsync(config: {
33
+ imports?: any[];
34
+ inject?: any[];
35
+ useFactory: (...args: any[]) => TenancyModuleOptions | Promise<TenancyModuleOptions>;
36
+ }): DynamicModule;
37
+ }
@@ -0,0 +1,34 @@
1
+ export declare const TENANCY_OPTIONS: unique symbol;
2
+ /** Names of the Postgres session variables (GUC) that the RLS policies read. */
3
+ export interface TenancyGucs {
4
+ /** e.g. `app.tienda_id` (Cajón) or `request.jwt.claim.tenant` (Fogón). Must contain a dot. */
5
+ tenant: string;
6
+ /** e.g. `app.usuario_id` or `request.jwt.claim.sub`. Optional: omitted when there is no actor GUC. */
7
+ actor?: string;
8
+ }
9
+ export interface TenancyOptions {
10
+ /** GUC names. They are options, not constants, so existing RLS policies do not change. */
11
+ gucs: TenancyGucs;
12
+ /**
13
+ * When true (default) a scope without tenant throws `TenantRequiredError` instead of running
14
+ * with no tenant set. Without it the RLS would return no rows silently; with it the bug is loud.
15
+ */
16
+ failClosed?: boolean;
17
+ /** Resolves the tenant at the start of the request (header, subdomain, token…). Optional: a guard can call `TenancyContext.setTenant` later. */
18
+ resolveTenant?: (request: any) => string | undefined;
19
+ /** Same for the actor (user id). */
20
+ resolveActor?: (request: any) => string | undefined;
21
+ /** Mount the context middleware on every route. Defaults to true. */
22
+ middleware?: boolean;
23
+ }
24
+ export declare const DEFAULT_GUCS: TenancyGucs;
25
+ /** Options accepted by the standalone `withTenant` functions. */
26
+ export interface ScopeOptions {
27
+ gucs?: TenancyGucs;
28
+ failClosed?: boolean;
29
+ }
30
+ /** Who the transaction runs as. Both fall back to the request context when omitted. */
31
+ export interface TenantScope {
32
+ tenantId?: string;
33
+ actorId?: string;
34
+ }