@authhero/multi-tenancy 14.25.1 → 14.26.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.
@@ -32,21 +32,236 @@ function w(e) {
32
32
  } };
33
33
  }
34
34
  //#endregion
35
+ //#region src/operations/instance-id.ts
36
+ var T = 64;
37
+ function E(e) {
38
+ return e.replace(/[^a-zA-Z0-9_-]/g, "-");
39
+ }
40
+ function ee(e) {
41
+ let t = E(e.id), n = Math.max(0, T - (5 + t.length)), r = E(e.kind).slice(0, n), i = 3 + r.length + 2 + t.length, a = Math.max(0, T - i);
42
+ return `op-${r}-${E(e.tenant_id ?? "fleet").slice(0, a)}-${t}`.slice(0, T);
43
+ }
44
+ //#endregion
45
+ //#region src/operations/recorder.ts
46
+ var te = 2048;
47
+ function D(e) {
48
+ let t;
49
+ if (e instanceof Error) t = e.message;
50
+ else try {
51
+ t = String(e ?? "unknown error");
52
+ } catch {
53
+ t = Object.prototype.toString.call(e);
54
+ }
55
+ return t.slice(0, te);
56
+ }
57
+ function O(e) {
58
+ let { tenantOperations: t, tenantOperationEvents: n } = e;
59
+ return {
60
+ async markRunning(e, n) {
61
+ await t.update(e, {
62
+ status: "running",
63
+ ...n === void 0 ? {} : { current_step: n }
64
+ });
65
+ },
66
+ async setCurrentStep(e, n) {
67
+ await t.update(e, { current_step: n });
68
+ },
69
+ async appendEvent(e, t) {
70
+ await n.create({
71
+ operation_id: e,
72
+ step: t.step,
73
+ outcome: t.outcome,
74
+ detail: t.detail,
75
+ attempt: t.attempt ?? 1
76
+ });
77
+ },
78
+ async markSucceeded(e) {
79
+ await t.update(e, {
80
+ status: "succeeded",
81
+ error: null,
82
+ finished_at: (/* @__PURE__ */ new Date()).toISOString()
83
+ });
84
+ },
85
+ async markFailed(e, n) {
86
+ await t.update(e, {
87
+ status: "failed",
88
+ error: D(n),
89
+ finished_at: (/* @__PURE__ */ new Date()).toISOString()
90
+ });
91
+ }
92
+ };
93
+ }
94
+ function k(e) {
95
+ return e === "succeeded" || e === "failed" || e === "cancelled";
96
+ }
97
+ //#endregion
98
+ //#region src/operations/inline-executor.ts
99
+ var A = { async do(e, t, n) {
100
+ let r = typeof t == "function" ? t : n;
101
+ if (!r) throw Error("StepRunner.do called without a function");
102
+ return r();
103
+ } };
104
+ function ne(e) {
105
+ let t = O(e.stores);
106
+ return {
107
+ engine: "inline",
108
+ async start(n) {
109
+ let r = e.definitions[n.kind];
110
+ if (!r) {
111
+ let e = /* @__PURE__ */ Error(`No inline operation definition for kind "${n.kind}"`);
112
+ throw await t.markFailed(n.id, e), e;
113
+ }
114
+ let i = r(n);
115
+ await t.markRunning(n.id, i[0]?.name);
116
+ for (let e of i) {
117
+ await t.setCurrentStep(n.id, e.name), await t.appendEvent(n.id, {
118
+ step: e.name,
119
+ outcome: "started"
120
+ });
121
+ try {
122
+ let r = await e.run({
123
+ operation: n,
124
+ step: A
125
+ });
126
+ await t.appendEvent(n.id, {
127
+ step: e.name,
128
+ outcome: "succeeded",
129
+ detail: r ?? void 0
130
+ });
131
+ } catch (r) {
132
+ throw await t.appendEvent(n.id, {
133
+ step: e.name,
134
+ outcome: "failed",
135
+ detail: { message: D(r) }
136
+ }), await t.markFailed(n.id, r), r;
137
+ }
138
+ }
139
+ await t.markSucceeded(n.id);
140
+ }
141
+ };
142
+ }
143
+ //#endregion
144
+ //#region src/operations/enqueue.ts
145
+ async function re(e, t, n) {
146
+ let r = await e.tenantOperations.create({
147
+ tenant_id: t.tenant_id,
148
+ rollout_id: t.rollout_id,
149
+ kind: t.kind,
150
+ engine: n,
151
+ initiated_by: t.initiated_by,
152
+ target_worker_version: t.target_worker_version,
153
+ target_database_version: t.target_database_version
154
+ }), i = ee(r);
155
+ try {
156
+ await e.tenantOperations.update(r.id, { engine_instance_id: i });
157
+ } catch (t) {
158
+ try {
159
+ await O(e).markFailed(r.id, t);
160
+ } catch {}
161
+ throw t;
162
+ }
163
+ return {
164
+ ...r,
165
+ engine_instance_id: i
166
+ };
167
+ }
168
+ async function ie(e, t, n) {
169
+ let r = O(e), i = await re(e, n, t.engine);
170
+ try {
171
+ await t.start(i);
172
+ } catch (t) {
173
+ try {
174
+ let n = await e.tenantOperations.get(i.id);
175
+ n && !k(n.status) && await r.markFailed(i.id, t);
176
+ } catch (e) {
177
+ console.warn("Failed to record tenant operation failure:", e);
178
+ }
179
+ throw t;
180
+ }
181
+ try {
182
+ return await e.tenantOperations.get(i.id) ?? i;
183
+ } catch (e) {
184
+ return console.warn("Failed to re-fetch tenant operation after start:", e), i;
185
+ }
186
+ }
187
+ //#endregion
188
+ //#region src/operations/record-provision.ts
189
+ function ae(e) {
190
+ if (e.tenantOperations && e.tenantOperationEvents) return {
191
+ tenantOperations: e.tenantOperations,
192
+ tenantOperationEvents: e.tenantOperationEvents
193
+ };
194
+ }
195
+ async function oe(e, t, n) {
196
+ let r = ae(e);
197
+ if (!r) {
198
+ await n(void 0);
199
+ return;
200
+ }
201
+ let i = O(r), a = async (e) => {
202
+ try {
203
+ await e();
204
+ } catch (e) {
205
+ console.warn("Failed to record tenant operation progress:", e);
206
+ }
207
+ }, o;
208
+ if (await a(async () => {
209
+ let e = await re(r, t, "inline");
210
+ o = e.id, await i.markRunning(e.id);
211
+ }), !o) {
212
+ await n(void 0);
213
+ return;
214
+ }
215
+ let s = o, c = !1, l = async (e, t, n) => {
216
+ c = !0, await a(async () => {
217
+ t === "started" && await i.setCurrentStep(s, e), await i.appendEvent(s, {
218
+ step: e,
219
+ outcome: t,
220
+ detail: n
221
+ });
222
+ });
223
+ };
224
+ try {
225
+ await n(l);
226
+ } catch (e) {
227
+ throw await a(async () => {
228
+ c || await i.appendEvent(s, {
229
+ step: t.kind,
230
+ outcome: "failed",
231
+ detail: { message: D(e) }
232
+ }), await i.markFailed(s, e);
233
+ }), e;
234
+ }
235
+ await a(async () => {
236
+ c || await i.appendEvent(s, {
237
+ step: t.kind,
238
+ outcome: "succeeded"
239
+ }), await i.markSucceeded(s);
240
+ });
241
+ }
242
+ //#endregion
35
243
  //#region src/hooks/provisioning.ts
36
- function T(e) {
244
+ function se(e) {
37
245
  return `urn:authhero:tenant:${e.toLowerCase()}`;
38
246
  }
39
- function E(e) {
247
+ function j(e) {
40
248
  return {
41
249
  async beforeCreate(e, t) {
42
250
  return !t.audience && t.id ? {
43
251
  ...t,
44
- audience: T(t.id)
252
+ audience: se(t.id)
45
253
  } : t;
46
254
  },
47
255
  async afterCreate(t, n) {
48
256
  let { accessControl: r, databaseIsolation: i } = e;
49
- r && t.ctx && await ee(t, n, r), i?.onProvision && await i.onProvision(n.id);
257
+ if (r && t.ctx && await ce(t, n, r), i?.onProvision) {
258
+ let e = i.onProvision;
259
+ i.recordProvisionOperations === !1 ? await e(n.id) : await oe(t.adapters, {
260
+ kind: "provision",
261
+ tenant_id: n.id,
262
+ initiated_by: t.ctx?.var.user?.sub
263
+ }, (t) => e(n.id, t));
264
+ }
50
265
  },
51
266
  async beforeDelete(t, n) {
52
267
  let { accessControl: r, databaseIsolation: i } = e;
@@ -64,14 +279,14 @@ function E(e) {
64
279
  }
65
280
  };
66
281
  }
67
- async function ee(e, t, n) {
282
+ async function ce(e, t, n) {
68
283
  let { controlPlaneTenantId: r, defaultPermissions: i, defaultRoles: a, issuer: o, adminRoleName: s = "Tenant Admin", adminRoleDescription: c = "Full access to all tenant management operations", addCreatorToOrganization: l = !0 } = n, u = await e.adapters.organizations.create(r, {
69
284
  name: t.id,
70
285
  display_name: t.friendly_name || t.id
71
286
  }), d;
72
- if (o && (d = await ne(e, r, s, c)), l && e.ctx) {
287
+ if (o && (d = await ue(e, r, s, c)), l && e.ctx) {
73
288
  let t = e.ctx.var.user;
74
- if (t?.sub && !await te(e, r, t.sub)) try {
289
+ if (t?.sub && !await le(e, r, t.sub)) try {
75
290
  await e.adapters.userOrganizations.create(r, {
76
291
  user_id: t.sub,
77
292
  organization_id: u.id
@@ -82,12 +297,12 @@ async function ee(e, t, n) {
82
297
  }
83
298
  a && a.length > 0 && console.log(`Would assign roles ${a.join(", ")} to organization ${u.id}`), i && i.length > 0 && console.log(`Would grant permissions ${i.join(", ")} to organization ${u.id}`);
84
299
  }
85
- async function te(e, t, n) {
300
+ async function le(e, t, n) {
86
301
  let r = await e.adapters.userRoles.list(t, n, void 0, "");
87
302
  for (let n of r) if ((await e.adapters.rolePermissions.list(t, n.id, { per_page: 1e3 })).some((e) => e.permission_name === "admin:organizations")) return !0;
88
303
  return !1;
89
304
  }
90
- async function ne(e, r, i, a) {
305
+ async function ue(e, r, i, a) {
91
306
  let o = (await e.adapters.roles.list(r, {})).roles.find((e) => e.name === i);
92
307
  if (o) return o.id;
93
308
  let s = await e.adapters.roles.create(r, {
@@ -102,7 +317,7 @@ async function ne(e, r, i, a) {
102
317
  }
103
318
  //#endregion
104
319
  //#region src/hooks/sync.ts
105
- function D(e, t, n = () => !0) {
320
+ function M(e, t, n = () => !0) {
106
321
  let { controlPlaneTenantId: r, getChildTenantIds: i, getAdapters: a } = e, o = /* @__PURE__ */ new Map();
107
322
  async function s(e, n, r) {
108
323
  return (await t(e).list(n, {
@@ -157,7 +372,7 @@ function D(e, t, n = () => !0) {
157
372
  }
158
373
  };
159
374
  }
160
- function O(e, t, n = () => !0) {
375
+ function N(e, t, n = () => !0) {
161
376
  let { controlPlaneTenantId: r, getControlPlaneAdapters: i, getAdapters: a } = e;
162
377
  return { async afterCreate(e, o) {
163
378
  if (o.id !== r) try {
@@ -181,7 +396,7 @@ function O(e, t, n = () => !0) {
181
396
  }
182
397
  } };
183
398
  }
184
- var k = (e) => ({
399
+ var P = (e) => ({
185
400
  list: async (t, n) => (await e.resourceServers.list(t, n)).resource_servers,
186
401
  listPaginated: (t, n) => e.resourceServers.list(t, n),
187
402
  get: (t, n) => e.resourceServers.get(t, n),
@@ -199,7 +414,7 @@ var k = (e) => ({
199
414
  token_lifetime: e.token_lifetime,
200
415
  token_lifetime_for_web: e.token_lifetime_for_web
201
416
  })
202
- }), A = (e) => ({
417
+ }), F = (e) => ({
203
418
  list: async (t, n) => (await e.roles.list(t, n)).roles,
204
419
  listPaginated: (t, n) => e.roles.list(t, n),
205
420
  get: (t, n) => e.roles.get(t, n),
@@ -214,11 +429,11 @@ var k = (e) => ({
214
429
  description: e.description
215
430
  })
216
431
  });
217
- function j(e) {
432
+ function I(e) {
218
433
  return e.metadata?.sync !== !1;
219
434
  }
220
- function re(e) {
221
- let { sync: t = {}, filters: n = {} } = e, r = t.resourceServers ?? !0, i = t.roles ?? !0, a = (e) => j(e) ? n.resourceServers ? n.resourceServers(e) : !0 : !1, o = (e) => j(e) ? n.roles ? n.roles(e) : !0 : !1, s = r ? D(e, k, a) : void 0, c = i ? D(e, A, o) : void 0, l = r ? O(e, k, a) : void 0, d = i ? O(e, A, o) : void 0, f = i ? { async afterCreate(t, r) {
435
+ function L(e) {
436
+ let { sync: t = {}, filters: n = {} } = e, r = t.resourceServers ?? !0, i = t.roles ?? !0, a = (e) => I(e) ? n.resourceServers ? n.resourceServers(e) : !0 : !1, o = (e) => I(e) ? n.roles ? n.roles(e) : !0 : !1, s = r ? M(e, P, a) : void 0, c = i ? M(e, F, o) : void 0, l = r ? N(e, P, a) : void 0, d = i ? N(e, F, o) : void 0, f = i ? { async afterCreate(t, r) {
222
437
  if (r.id !== e.controlPlaneTenantId) {
223
438
  await d?.afterCreate?.(t, r);
224
439
  try {
@@ -273,22 +488,22 @@ function re(e) {
273
488
  }
274
489
  //#endregion
275
490
  //#region src/routes/tenants.ts
276
- var ie = b.object({
491
+ var de = b.object({
277
492
  sub: b.string(),
278
493
  tenant_id: b.string().optional(),
279
494
  org_id: b.string().optional(),
280
495
  scope: b.string().optional(),
281
496
  permissions: b.array(b.string()).optional()
282
497
  }).passthrough();
283
- function ae(e) {
284
- let t = ie.safeParse(e);
498
+ function fe(e) {
499
+ let t = de.safeParse(e);
285
500
  return t.success ? t.data : void 0;
286
501
  }
287
- function oe(e) {
288
- let t = e.permissions ?? [], n = e.scope ? e.scope.split(" ").filter(Boolean) : [], r = new Set([...t, ...n]);
502
+ function pe(e) {
503
+ let t = e.permissions ?? [], n = e.scope ? e.scope.split(" ").filter(Boolean) : [], r = /* @__PURE__ */ new Set([...t, ...n]);
289
504
  return r.has("delete:tenants") || r.has("admin:organizations");
290
505
  }
291
- function M(e, t) {
506
+ function R(e, t) {
292
507
  let n = new v();
293
508
  return n.openapi(y({
294
509
  tags: ["tenants"],
@@ -399,13 +614,13 @@ function M(e, t) {
399
614
  }), async (n) => {
400
615
  let { id: r } = n.req.valid("param"), i = e.accessControl?.controlPlaneTenantId ?? n.env.data.multiTenancyConfig?.controlPlaneTenantId;
401
616
  if (i) {
402
- let e = ae(n.var.user);
617
+ let e = fe(n.var.user);
403
618
  if (!e?.sub) throw new x(401, { message: "Authentication required" });
404
619
  if (r === i) throw new x(403, { message: "Cannot delete the control plane" });
405
620
  let t = n.var.org_name, a = r.toLowerCase(), o = !!t && t.toLowerCase() === a;
406
621
  if (!o) {
407
622
  let r = !!(e.org_id ?? n.var.organization_id ?? t), a = !e.tenant_id || e.tenant_id === i;
408
- !r && a && oe(e) && (o = !0);
623
+ !r && a && pe(e) && (o = !0);
409
624
  }
410
625
  if (o ||= (await u((t) => n.env.data.userOrganizations.listUserOrganizations(i, e.sub, t), "organizations")).some((e) => e.name?.toLowerCase() === a), !o) throw new x(403, { message: "Access denied to this tenant" });
411
626
  }
@@ -454,7 +669,7 @@ function M(e, t) {
454
669
  }
455
670
  //#endregion
456
671
  //#region src/middleware/protect-synced.ts
457
- function se(e) {
672
+ function me(e) {
458
673
  for (let { pattern: t, type: n } of [
459
674
  {
460
675
  pattern: /\/api\/v2\/resource-servers\/([^/]+)$/,
@@ -477,7 +692,7 @@ function se(e) {
477
692
  }
478
693
  return null;
479
694
  }
480
- async function ce(e, t, n) {
695
+ async function he(e, t, n) {
481
696
  try {
482
697
  switch (n.type) {
483
698
  case "resource_server": return (await e.resourceServers.get(t, n.id))?.is_system === !0;
@@ -489,31 +704,31 @@ async function ce(e, t, n) {
489
704
  return !1;
490
705
  }
491
706
  }
492
- function le(e) {
707
+ function ge(e) {
493
708
  return {
494
709
  resource_server: "resource server",
495
710
  role: "role",
496
711
  connection: "connection"
497
712
  }[e];
498
713
  }
499
- function N() {
714
+ function z() {
500
715
  return async (e, t) => {
501
716
  if (![
502
717
  "PATCH",
503
718
  "PUT",
504
719
  "DELETE"
505
720
  ].includes(e.req.method)) return t();
506
- let n = se(e.req.path);
721
+ let n = me(e.req.path);
507
722
  if (!n) return t();
508
723
  let r = e.var.tenant_id || e.req.header("x-tenant-id") || e.req.header("tenant-id");
509
724
  if (!r) return t();
510
- if (await ce(e.env.data, r, n)) throw new x(403, { message: `This ${le(n.type)} is a system resource and cannot be modified. Make changes in the control plane instead.` });
725
+ if (await he(e.env.data, r, n)) throw new x(403, { message: `This ${ge(n.type)} is a system resource and cannot be modified. Make changes in the control plane instead.` });
511
726
  return t();
512
727
  };
513
728
  }
514
729
  //#endregion
515
730
  //#region src/middleware/settings-inheritance.ts
516
- function P(e, t) {
731
+ function B(e, t) {
517
732
  let n = t.find((t) => t.strategy === e.strategy);
518
733
  if (!n?.options) return e;
519
734
  let r = s.passthrough().parse({
@@ -525,11 +740,11 @@ function P(e, t) {
525
740
  ...e.options
526
741
  }), r;
527
742
  }
528
- function F(e, t) {
743
+ function V(e, t) {
529
744
  let n = [...t || [], ...e || []];
530
745
  return [...new Set(n)];
531
746
  }
532
- function ue(e, t) {
747
+ function _e(e, t) {
533
748
  if (!t?.length) return e || [];
534
749
  if (!e?.length) return t;
535
750
  let n = /* @__PURE__ */ new Map();
@@ -537,22 +752,22 @@ function ue(e, t) {
537
752
  for (let t of e) n.set(t.value, t);
538
753
  return Array.from(n.values());
539
754
  }
540
- function I(e, t) {
755
+ function H(e, t) {
541
756
  return t ? {
542
757
  ...e,
543
- scopes: ue(e.scopes, t.scopes)
758
+ scopes: _e(e.scopes, t.scopes)
544
759
  } : e;
545
760
  }
546
- function de(e, t) {
761
+ function ve(e, t) {
547
762
  return t ? {
548
763
  ...e,
549
- callbacks: F(e.callbacks, t.callbacks),
550
- web_origins: F(e.web_origins, t.web_origins),
551
- allowed_logout_urls: F(e.allowed_logout_urls, t.allowed_logout_urls),
552
- allowed_origins: F(e.allowed_origins, t.allowed_origins)
764
+ callbacks: V(e.callbacks, t.callbacks),
765
+ web_origins: V(e.web_origins, t.web_origins),
766
+ allowed_logout_urls: V(e.allowed_logout_urls, t.allowed_logout_urls),
767
+ allowed_origins: V(e.allowed_origins, t.allowed_origins)
553
768
  } : e;
554
769
  }
555
- function L(e) {
770
+ function U(e) {
556
771
  let { controlPlaneTenantId: t, controlPlaneClientId: n, resolveControlPlane: r } = e;
557
772
  if (r) return async (e) => r({ tenant_id: e });
558
773
  if (!t) return async () => void 0;
@@ -562,14 +777,14 @@ function L(e) {
562
777
  };
563
778
  return async () => i;
564
779
  }
565
- function R(e, t) {
780
+ function W(e, t) {
566
781
  return {
567
782
  ...e.resourceServers,
568
783
  get: async (n, r) => {
569
784
  let i = await e.resourceServers.get(n, r);
570
785
  if (!i) return i;
571
786
  let a = await t(n);
572
- return !a || n === a.tenantId || !i.is_system ? i : I(i, await e.resourceServers.get(a.tenantId, r));
787
+ return !a || n === a.tenantId || !i.is_system ? i : H(i, await e.resourceServers.get(a.tenantId, r));
573
788
  },
574
789
  list: async (n, r) => {
575
790
  let i = await e.resourceServers.list(n, r), a = await t(n);
@@ -581,7 +796,7 @@ function R(e, t) {
581
796
  let n = await e.resourceServers.get(o, t);
582
797
  n && c.set(t, n);
583
798
  }));
584
- let l = i.resource_servers.map((e) => e.is_system && e.id ? I(e, c.get(e.id) ?? null) : e);
799
+ let l = i.resource_servers.map((e) => e.is_system && e.id ? H(e, c.get(e.id) ?? null) : e);
585
800
  return {
586
801
  ...i,
587
802
  resource_servers: l
@@ -589,18 +804,18 @@ function R(e, t) {
589
804
  }
590
805
  };
591
806
  }
592
- function z(e, t) {
593
- let n = L({
807
+ function ye(e, t) {
808
+ let n = U({
594
809
  controlPlaneTenantId: t.controlPlaneTenantId,
595
810
  resolveControlPlane: t.resolveControlPlane
596
811
  });
597
812
  return {
598
813
  ...e,
599
- resourceServers: R(e, n)
814
+ resourceServers: W(e, n)
600
815
  };
601
816
  }
602
- function B(e, t) {
603
- let { controlPlaneTenantId: n, controlPlaneClientId: r, resolveControlPlane: i } = t, a = L({
817
+ function be(e, t) {
818
+ let { controlPlaneTenantId: n, controlPlaneClientId: r, resolveControlPlane: i } = t, a = U({
604
819
  controlPlaneTenantId: n,
605
820
  controlPlaneClientId: r,
606
821
  resolveControlPlane: i
@@ -618,12 +833,12 @@ function B(e, t) {
618
833
  let r = await e.connections.get(t, n);
619
834
  if (!r) return r;
620
835
  let i = await a(t);
621
- return !i || t === i.tenantId ? r : P(r, (await e.connections.list(i.tenantId)).connections || []);
836
+ return !i || t === i.tenantId ? r : B(r, (await e.connections.list(i.tenantId)).connections || []);
622
837
  },
623
838
  list: async (t, n) => {
624
839
  let r = await e.connections.list(t, n), i = await a(t);
625
840
  if (!i || t === i.tenantId) return r;
626
- let o = await e.connections.list(i.tenantId), s = r.connections.map((e) => P(e, o.connections || []));
841
+ let o = await e.connections.list(i.tenantId), s = r.connections.map((e) => B(e, o.connections || []));
627
842
  return {
628
843
  ...r,
629
844
  connections: s
@@ -638,7 +853,7 @@ function B(e, t) {
638
853
  let i = await a(t);
639
854
  if (!i || t === i.tenantId) return r;
640
855
  let o = await e.connections.list(i.tenantId);
641
- return r.map((e) => P(e, o.connections || []));
856
+ return r.map((e) => B(e, o.connections || []));
642
857
  }
643
858
  },
644
859
  emailProviders: {
@@ -650,22 +865,22 @@ function B(e, t) {
650
865
  return !r || t === r.tenantId ? null : e.emailProviders.get(r.tenantId);
651
866
  }
652
867
  },
653
- resourceServers: R(e, a),
654
- hooks: fe(e, a)
868
+ resourceServers: W(e, a),
869
+ hooks: Se(e, a)
655
870
  };
656
871
  }
657
- function V(e) {
872
+ function xe(e) {
658
873
  if (!e || typeof e != "object") return !1;
659
874
  let t = e.metadata;
660
875
  return !t || typeof t != "object" ? !1 : t.inheritable === !0;
661
876
  }
662
- function fe(e, t) {
877
+ function Se(e, t) {
663
878
  return {
664
879
  ...e.hooks,
665
880
  list: async (n, r) => {
666
881
  let i = await e.hooks.list(n, r), a = await t(n);
667
882
  if (!a || n === a.tenantId) return i;
668
- let o = ((await e.hooks.list(a.tenantId, r)).hooks || []).filter(V);
883
+ let o = ((await e.hooks.list(a.tenantId, r)).hooks || []).filter(xe);
669
884
  if (o.length === 0) return i;
670
885
  let s = new Set((i.hooks || []).map((e) => e.hook_id)), c = o.filter((e) => !s.has(e.hook_id));
671
886
  return {
@@ -680,22 +895,22 @@ function fe(e, t) {
680
895
  let a = await t(n);
681
896
  if (!a || n === a.tenantId) return i;
682
897
  let o = await e.hooks.get(a.tenantId, r);
683
- return o && V(o) ? o : null;
898
+ return o && xe(o) ? o : null;
684
899
  }
685
900
  };
686
901
  }
687
- function H(e, t) {
688
- return B(e, t);
902
+ function G(e, t) {
903
+ return be(e, t);
689
904
  }
690
905
  //#endregion
691
906
  //#region src/middleware/index.ts
692
- function U(e) {
907
+ function Ce(e) {
693
908
  return async (t, n) => {
694
909
  let r = t.var.user;
695
910
  return r?.tenant_id === e && r.org_name && t.set("tenant_id", r.org_name), n();
696
911
  };
697
912
  }
698
- function W(e) {
913
+ function we(e) {
699
914
  return async (n, r) => {
700
915
  if (!e.accessControl) return r();
701
916
  let { controlPlaneTenantId: i } = e.accessControl, a = n.var.org_name, o = n.var.organization_id, s = a || o, c = n.var.tenant_id, l = n.var.user, u = (l?.aud ? Array.isArray(l.aud) ? l.aud : [l.aud] : []).includes(t);
@@ -704,7 +919,7 @@ function W(e) {
704
919
  return r();
705
920
  };
706
921
  }
707
- function G(e) {
922
+ function Te(e) {
708
923
  return async (t, n) => {
709
924
  if (!e.subdomainRouting) return n();
710
925
  let { baseDomain: r, reservedSubdomains: i = [], resolveSubdomain: a } = e.subdomainRouting, o = t.req.header("x-forwarded-host") || t.req.header("host") || "", s = null;
@@ -723,7 +938,7 @@ function G(e) {
723
938
  return t.set("tenant_id", c), n();
724
939
  };
725
940
  }
726
- function K(e) {
941
+ function Ee(e) {
727
942
  return async (t, n) => {
728
943
  if (!e.databaseIsolation) return n();
729
944
  let r = t.var.tenant_id;
@@ -737,25 +952,25 @@ function K(e) {
737
952
  return n();
738
953
  };
739
954
  }
740
- function q(e) {
741
- let t = G(e), n = W(e), r = K(e);
955
+ function K(e) {
956
+ let t = Te(e), n = we(e), r = Ee(e);
742
957
  return async (e, i) => (await t(e, async () => {}), await n(e, async () => {}), await r(e, async () => {}), i());
743
958
  }
744
959
  //#endregion
745
960
  //#region src/init.ts
746
- function pe(e) {
961
+ function De(e) {
747
962
  let { dataAdapter: t, controlPlane: n, controlPlane: { tenantId: r = "control_plane", clientId: i } = {}, resolveControlPlane: a, sync: o = {
748
963
  resourceServers: !0,
749
964
  roles: !0
750
965
  }, defaultPermissions: s = ["tenant:admin"], requireOrganizationMatch: c = !1, managementApiExtensions: l = [], entityHooks: d, getChildTenantIds: p, getAdapters: m, ...h } = e;
751
966
  if (a && !n) throw Error("initMultiTenant: `resolveControlPlane` requires `controlPlane` to be set. The static `controlPlane.tenantId` is used for access control, sync direction, and tenant management routing; the resolver only overrides per-tenant runtime inheritance lookups on top of it.");
752
967
  let g = t, _ = t;
753
- n && (g = H(t, {
968
+ n && (g = G(t, {
754
969
  controlPlaneTenantId: r,
755
970
  controlPlaneClientId: i,
756
971
  resolveControlPlane: a
757
972
  }), _ = {
758
- ...z(t, {
973
+ ...ye(t, {
759
974
  controlPlaneTenantId: r,
760
975
  resolveControlPlane: a
761
976
  }),
@@ -765,13 +980,36 @@ function pe(e) {
765
980
  resolveControlPlane: a
766
981
  }
767
982
  });
768
- let v = o !== !1, y = v ? {
983
+ let v = h.tenantOperationExecutor;
984
+ if (!v && t.tenantOperations && t.tenantOperationEvents && h.tenantUpgrade) {
985
+ let e = {
986
+ tenantOperations: t.tenantOperations,
987
+ tenantOperationEvents: t.tenantOperationEvents
988
+ }, n = h.tenantUpgrade, r = ne({
989
+ stores: e,
990
+ definitions: { upgrade: (e) => [{
991
+ name: "upgrade",
992
+ async run() {
993
+ if (!e.tenant_id) throw Error("upgrade operations require a tenant_id");
994
+ await n(e.tenant_id);
995
+ }
996
+ }] }
997
+ });
998
+ v = {
999
+ engine: r.engine,
1000
+ enqueue: (t) => ie(e, r, {
1001
+ ...t,
1002
+ tenant_id: t.tenant_id
1003
+ })
1004
+ };
1005
+ }
1006
+ let y = o !== !1, b = y ? {
769
1007
  resourceServers: o.resourceServers ?? !0,
770
1008
  roles: o.roles ?? !0
771
1009
  } : {
772
1010
  resourceServers: !1,
773
1011
  roles: !1
774
- }, { entityHooks: b, tenantHooks: x } = re({
1012
+ }, { entityHooks: x, tenantHooks: S } = L({
775
1013
  controlPlaneTenantId: r,
776
1014
  getChildTenantIds: p ?? (async () => (await u((e) => g.tenants.list(e), "tenants", {
777
1015
  cursorField: "id",
@@ -779,49 +1017,50 @@ function pe(e) {
779
1017
  })).filter((e) => e.id !== r).map((e) => e.id)),
780
1018
  getAdapters: m ?? (async () => g),
781
1019
  getControlPlaneAdapters: async () => g,
782
- sync: y
783
- }), S = {
784
- resourceServers: [b.resourceServers, ...d?.resourceServers ?? []],
785
- roles: [b.roles, ...d?.roles ?? []],
1020
+ sync: b
1021
+ }), C = {
1022
+ resourceServers: [x.resourceServers, ...d?.resourceServers ?? []],
1023
+ roles: [x.roles, ...d?.roles ?? []],
786
1024
  connections: d?.connections ?? [],
787
1025
  tenants: d?.tenants ?? [],
788
1026
  rolePermissions: d?.rolePermissions ?? []
789
- }, C = E({ accessControl: {
1027
+ }, w = j({ accessControl: {
790
1028
  controlPlaneTenantId: r,
791
1029
  requireOrganizationMatch: c,
792
1030
  defaultPermissions: s
793
- } }), w = M({ accessControl: {
1031
+ } }), T = R({ accessControl: {
794
1032
  controlPlaneTenantId: r,
795
1033
  requireOrganizationMatch: c,
796
1034
  defaultPermissions: s
797
1035
  } }, { tenants: {
798
1036
  async beforeCreate(e, t) {
799
- return C.beforeCreate && (t = await C.beforeCreate(e, t)), x.beforeCreate && (t = await x.beforeCreate(e, t)), t;
1037
+ return w.beforeCreate && (t = await w.beforeCreate(e, t)), S.beforeCreate && (t = await S.beforeCreate(e, t)), t;
800
1038
  },
801
1039
  async afterCreate(e, t) {
802
- await C.afterCreate?.(e, t), await x.afterCreate?.(e, t);
1040
+ await w.afterCreate?.(e, t), await S.afterCreate?.(e, t);
803
1041
  },
804
1042
  async beforeDelete(e, t) {
805
- await C.beforeDelete?.(e, t), await x.beforeDelete?.(e, t);
1043
+ await w.beforeDelete?.(e, t), await S.beforeDelete?.(e, t);
806
1044
  }
807
- } }), { app: T } = f({
1045
+ } }), { app: E } = f({
808
1046
  dataAdapter: g,
809
1047
  managementDataAdapter: _,
810
1048
  ...h,
811
- entityHooks: S,
1049
+ tenantOperationExecutor: v,
1050
+ entityHooks: C,
812
1051
  managementApiExtensions: [...l, {
813
1052
  path: "/tenants",
814
- router: w
1053
+ router: T
815
1054
  }]
816
1055
  });
817
- return T.use("/api/v2/*", U(r)), v && T.use("/api/v2/*", N()), {
818
- app: T,
1056
+ return E.use("/api/v2/*", Ce(r)), y && E.use("/api/v2/*", z()), {
1057
+ app: E,
819
1058
  controlPlaneTenantId: r
820
1059
  };
821
1060
  }
822
1061
  //#endregion
823
1062
  //#region src/rollout/defaults-projection.ts
824
- function J(e = {}) {
1063
+ function q(e = {}) {
825
1064
  return {
826
1065
  connections: e.connections ?? !0,
827
1066
  resourceServers: e.resourceServers ?? !0,
@@ -831,24 +1070,24 @@ function J(e = {}) {
831
1070
  promptSettings: e.promptSettings ?? !0
832
1071
  };
833
1072
  }
834
- function Y() {
1073
+ function J() {
835
1074
  return {
836
1075
  upserted: 0,
837
1076
  errors: []
838
1077
  };
839
1078
  }
840
- function me(e) {
1079
+ function Y(e) {
841
1080
  return {
842
1081
  tenantId: e,
843
- connections: Y(),
844
- resourceServers: Y(),
845
- hooks: Y(),
846
- emailProvider: Y(),
847
- branding: Y(),
848
- promptSettings: Y()
1082
+ connections: J(),
1083
+ resourceServers: J(),
1084
+ hooks: J(),
1085
+ emailProvider: J(),
1086
+ branding: J(),
1087
+ promptSettings: J()
849
1088
  };
850
1089
  }
851
- function he(e) {
1090
+ function Oe(e) {
852
1091
  let t = e.metadata;
853
1092
  return !!(t && t.inheritable === !0);
854
1093
  }
@@ -861,7 +1100,7 @@ async function X(e, t, n, r) {
861
1100
  e.errors.push(i);
862
1101
  }
863
1102
  }
864
- async function ge(e, t, n) {
1103
+ async function ke(e, t, n) {
865
1104
  return {
866
1105
  connections: n.connections ? await u((n) => e.connections.list(t, n), "connections", {
867
1106
  cursorField: "id",
@@ -880,7 +1119,7 @@ async function ge(e, t, n) {
880
1119
  promptSettings: n.promptSettings ? await e.promptSettings.get(t) ?? null : null
881
1120
  };
882
1121
  }
883
- async function _e(e, t, n, r, i, o) {
1122
+ async function Ae(e, t, n, r, i, o) {
884
1123
  if (r.connections) for (let r of e.connections) {
885
1124
  let e = r.id;
886
1125
  e && await X(o.connections, `connection ${e}`, i, async () => {
@@ -892,7 +1131,7 @@ async function _e(e, t, n, r, i, o) {
892
1131
  let e = h.parse(r);
893
1132
  await t.resourceServers.get(n, r.id) ? await t.resourceServers.update(n, r.id, e) : await t.resourceServers.create(n, e), o.resourceServers.upserted += 1;
894
1133
  });
895
- if (r.hooks) for (let r of e.hooks) !he(r) || !r.hook_id || await X(o.hooks, `hook ${r.hook_id}`, i, async () => {
1134
+ if (r.hooks) for (let r of e.hooks) !Oe(r) || !r.hook_id || await X(o.hooks, `hook ${r.hook_id}`, i, async () => {
896
1135
  let e = d.parse(r);
897
1136
  await t.hooks.get(n, r.hook_id) ? await t.hooks.update(n, r.hook_id, e) : await t.hooks.create(n, e), o.hooks.upserted += 1;
898
1137
  });
@@ -906,21 +1145,21 @@ async function _e(e, t, n, r, i, o) {
906
1145
  });
907
1146
  }
908
1147
  async function Z(e, t) {
909
- let { controlPlaneTenantId: n, getControlPlaneAdapters: r, getAdapters: i, entities: a, continueOnError: o = !1 } = e, s = J(a), c = await ge(await r(), n, s), l = await i(t), u = me(t);
910
- return await _e(c, l, n, s, o, u), u;
1148
+ let { controlPlaneTenantId: n, getControlPlaneAdapters: r, getAdapters: i, entities: a, continueOnError: o = !1 } = e, s = q(a), c = await ke(await r(), n, s), l = await i(t), u = Y(t);
1149
+ return await Ae(c, l, n, s, o, u), u;
911
1150
  }
912
1151
  //#endregion
913
1152
  //#region src/rollout/payload.ts
914
- function ve(e) {
1153
+ function je(e) {
915
1154
  let { pkcs7: t, tenant_id: n, ...r } = e;
916
1155
  return r;
917
1156
  }
918
- async function ye(e, t, n = {}, r) {
919
- let i = J(n), a = n.signingKeys ?? !0, o = n.tenants ?? !0, s = await ge(e, t, i), c = a ? (await p(e.keys)).map(ve) : [], l = o ? await be(e, t, r) : [];
1157
+ async function Me(e, t, n = {}, r) {
1158
+ let i = q(n), a = n.signingKeys ?? !0, o = n.tenants ?? !0, s = await ke(e, t, i), c = a ? (await p(e.keys)).map(je) : [], l = o ? await Ne(e, t, r) : [];
920
1159
  return {
921
1160
  connections: s.connections,
922
1161
  resourceServers: s.resourceServers.filter((e) => e.is_system),
923
- hooks: s.hooks.filter(he),
1162
+ hooks: s.hooks.filter(Oe),
924
1163
  emailProvider: s.emailProvider,
925
1164
  branding: s.branding,
926
1165
  promptSettings: s.promptSettings,
@@ -928,7 +1167,7 @@ async function ye(e, t, n = {}, r) {
928
1167
  tenants: l
929
1168
  };
930
1169
  }
931
- async function be(e, t, n) {
1170
+ async function Ne(e, t, n) {
932
1171
  let r = n && n !== t ? [t, n] : [t], i = [];
933
1172
  for (let t of r) {
934
1173
  let n = await e.tenants.get(t);
@@ -939,18 +1178,18 @@ async function be(e, t, n) {
939
1178
  }
940
1179
  return i;
941
1180
  }
942
- async function xe(e, t, n) {
943
- let r = Y();
1181
+ async function Pe(e, t, n) {
1182
+ let r = J();
944
1183
  if (e.length === 0) return r;
945
1184
  let i = await p(t.keys), a = new Set(i.map((e) => e.kid));
946
1185
  for (let i of e) await X(r, `signing_key ${i.kid}`, n, async () => {
947
- let e = ve(i);
1186
+ let e = je(i);
948
1187
  a.has(e.kid) || (await t.keys.create(e), a.add(e.kid), r.upserted += 1);
949
1188
  });
950
1189
  return r;
951
1190
  }
952
- async function Se(e, t, n) {
953
- let r = Y();
1191
+ async function Fe(e, t, n) {
1192
+ let r = J();
954
1193
  for (let i of e) await X(r, `tenant ${i.id}`, n, async () => {
955
1194
  await t.tenants.get(i.id) || (await t.tenants.create({
956
1195
  id: i.id,
@@ -959,17 +1198,17 @@ async function Se(e, t, n) {
959
1198
  });
960
1199
  return r;
961
1200
  }
962
- async function Ce(e, t, n, r = {}) {
963
- let a = r.continueOnError ?? !1, o = J(r.entities), s = r.entities?.signingKeys ?? !0, c = r.entities?.tenants ?? !0, u = {
1201
+ async function Ie(e, t, n, r = {}) {
1202
+ let a = r.continueOnError ?? !1, o = q(r.entities), s = r.entities?.signingKeys ?? !0, c = r.entities?.tenants ?? !0, u = {
964
1203
  connections: e.connections,
965
1204
  resourceServers: e.resourceServers,
966
1205
  hooks: e.hooks,
967
1206
  emailProvider: e.emailProvider ? l.parse(e.emailProvider) : null,
968
1207
  branding: e.branding ? i.parse(e.branding) : null,
969
1208
  promptSettings: e.promptSettings ? m.parse(e.promptSettings) : null
970
- }, d = c ? await Se(e.tenants ?? [], t, a) : Y(), f = me(n);
971
- await _e(u, t, n, o, a, f);
972
- let p = s ? await xe(e.signingKeys, t, a) : Y();
1209
+ }, d = c ? await Fe(e.tenants ?? [], t, a) : J(), f = Y(n);
1210
+ await Ae(u, t, n, o, a, f);
1211
+ let p = s ? await Pe(e.signingKeys, t, a) : J();
973
1212
  return {
974
1213
  ...f,
975
1214
  signingKeys: p,
@@ -978,7 +1217,7 @@ async function Ce(e, t, n, r = {}) {
978
1217
  }
979
1218
  //#endregion
980
1219
  //#region src/rollout/index.ts
981
- function we(e) {
1220
+ function Le(e) {
982
1221
  return {
983
1222
  syncDefaults: (t) => Z(e, t),
984
1223
  syncDefaultsToTenants: async (t) => {
@@ -990,15 +1229,15 @@ function we(e) {
990
1229
  }
991
1230
  //#endregion
992
1231
  //#region src/plugin.ts
993
- function Te(e) {
1232
+ function Re(e) {
994
1233
  let t = Q(e);
995
1234
  return {
996
1235
  name: "multi-tenancy",
997
- middleware: q(e),
1236
+ middleware: K(e),
998
1237
  hooks: t,
999
1238
  routes: [{
1000
1239
  path: "/management",
1001
- handler: M(e, t)
1240
+ handler: R(e, t)
1002
1241
  }],
1003
1242
  onRegister: async () => {
1004
1243
  console.log("Multi-tenancy plugin registered"), e.accessControl && console.log(` - Access control enabled (control plane: ${e.accessControl.controlPlaneTenantId})`), e.subdomainRouting && console.log(` - Subdomain routing enabled (base domain: ${e.subdomainRouting.baseDomain})`), e.databaseIsolation && console.log(" - Database isolation enabled");
@@ -1008,7 +1247,7 @@ function Te(e) {
1008
1247
  //#endregion
1009
1248
  //#region src/index.ts
1010
1249
  function Q(e) {
1011
- let t = e.accessControl ? S(e.accessControl) : {}, n = e.databaseIsolation ? w(e.databaseIsolation) : {}, r = E(e);
1250
+ let t = e.accessControl ? S(e.accessControl) : {}, n = e.databaseIsolation ? w(e.databaseIsolation) : {}, r = j(e);
1012
1251
  return {
1013
1252
  ...t,
1014
1253
  ...n,
@@ -1017,19 +1256,19 @@ function Q(e) {
1017
1256
  }
1018
1257
  function $(t) {
1019
1258
  let n = new e(), r = Q(t);
1020
- return n.route("/tenants", M(t, r)), n;
1259
+ return n.route("/tenants", R(t, r)), n;
1021
1260
  }
1022
- function Ee(e) {
1261
+ function ze(e) {
1023
1262
  return {
1024
1263
  hooks: Q(e),
1025
- middleware: q(e),
1264
+ middleware: K(e),
1026
1265
  app: $(e),
1027
1266
  config: e,
1028
- wrapAdapters: (t, n) => H(t, {
1267
+ wrapAdapters: (t, n) => G(t, {
1029
1268
  controlPlaneTenantId: e.accessControl?.controlPlaneTenantId,
1030
1269
  controlPlaneClientId: n?.controlPlaneClientId
1031
1270
  })
1032
1271
  };
1033
1272
  }
1034
1273
  //#endregion
1035
- export { Ce as applyControlPlaneDefaultsPayload, ye as buildControlPlaneDefaultsPayload, S as createAccessControlHooks, W as createAccessControlMiddleware, U as createControlPlaneTenantMiddleware, w as createDatabaseHooks, K as createDatabaseMiddleware, we as createDirectRolloutAdapter, $ as createMultiTenancy, Q as createMultiTenancyHooks, q as createMultiTenancyMiddleware, Te as createMultiTenancyPlugin, N as createProtectSyncedMiddleware, E as createProvisioningHooks, B as createRuntimeFallbackAdapter, G as createSubdomainMiddleware, re as createSyncHooks, M as createTenantsOpenAPIRouter, pe as initMultiTenant, de as mergeClientWithFallback, Z as projectControlPlaneDefaults, Ee as setupMultiTenancy, C as validateTenantAccess, H as withRuntimeFallback, z as withSystemResourceServerInheritance };
1274
+ export { Ie as applyControlPlaneDefaultsPayload, Me as buildControlPlaneDefaultsPayload, ee as buildEngineInstanceId, S as createAccessControlHooks, we as createAccessControlMiddleware, Ce as createControlPlaneTenantMiddleware, w as createDatabaseHooks, Ee as createDatabaseMiddleware, Le as createDirectRolloutAdapter, ne as createInlineExecutor, $ as createMultiTenancy, Q as createMultiTenancyHooks, K as createMultiTenancyMiddleware, Re as createMultiTenancyPlugin, O as createOperationRecorder, z as createProtectSyncedMiddleware, j as createProvisioningHooks, be as createRuntimeFallbackAdapter, Te as createSubdomainMiddleware, L as createSyncHooks, R as createTenantsOpenAPIRouter, ie as enqueueTenantOperation, D as errorToMessage, De as initMultiTenant, A as inlineStepRunner, k as isTerminalStatus, ve as mergeClientWithFallback, Z as projectControlPlaneDefaults, oe as runRecordedTenantOperation, ze as setupMultiTenancy, C as validateTenantAccess, G as withRuntimeFallback, ye as withSystemResourceServerInheritance };