@authhero/multi-tenancy 14.3.0 → 14.5.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.
@@ -1,30 +1,30 @@
1
- var W = Object.defineProperty;
2
- var Q = (t, e, n) => e in t ? W(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
3
- var $ = (t, e, n) => Q(t, typeof e != "symbol" ? e + "" : e, n);
4
- import { Hono as V } from "hono";
5
- import { MANAGEMENT_API_SCOPES as J, MANAGEMENT_API_AUDIENCE as L, fetchAll as I, auth0QuerySchema as X, tenantSchema as k, tenantInsertSchema as Y, connectionSchema as z, connectionOptionsSchema as R, init as Z } from "authhero";
6
- import { OpenAPIHono as x, createRoute as O, z as C } from "@hono/zod-openapi";
7
- function ee(t) {
1
+ var X = Object.defineProperty;
2
+ var Y = (t, e, n) => e in t ? X(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
3
+ var R = (t, e, n) => Y(t, typeof e != "symbol" ? e + "" : e, n);
4
+ import { Hono as Z } from "hono";
5
+ import { MANAGEMENT_API_SCOPES as x, MANAGEMENT_API_AUDIENCE as W, fetchAll as z, auth0QuerySchema as ee, tenantSchema as H, tenantInsertSchema as te, connectionSchema as F, connectionOptionsSchema as O, init as ne } from "authhero";
6
+ import { OpenAPIHono as re, createRoute as M, z as S } from "@hono/zod-openapi";
7
+ function se(t) {
8
8
  const { controlPlaneTenantId: e, requireOrganizationMatch: n = !0 } = t;
9
9
  return {
10
- async onTenantAccessValidation(s, a) {
11
- if (a === e)
10
+ async onTenantAccessValidation(r, s) {
11
+ if (s === e)
12
12
  return !0;
13
13
  if (n) {
14
- const i = s.var.org_name, o = s.var.organization_id, r = i || o;
15
- return r ? r.toLowerCase() === a.toLowerCase() : !1;
14
+ const c = r.var.org_name, o = r.var.organization_id, a = c || o;
15
+ return a ? a.toLowerCase() === s.toLowerCase() : !1;
16
16
  }
17
17
  return !0;
18
18
  }
19
19
  };
20
20
  }
21
- function te(t, e, n, s) {
21
+ function ae(t, e, n, r) {
22
22
  if (e === n)
23
23
  return !0;
24
- const a = s || t;
25
- return a ? a.toLowerCase() === e.toLowerCase() : !1;
24
+ const s = r || t;
25
+ return s ? s.toLowerCase() === e.toLowerCase() : !1;
26
26
  }
27
- function ne(t) {
27
+ function oe(t) {
28
28
  return {
29
29
  async resolveDataAdapters(e) {
30
30
  try {
@@ -39,248 +39,248 @@ function ne(t) {
39
39
  }
40
40
  };
41
41
  }
42
- function se(t) {
42
+ function ie(t) {
43
43
  return `urn:authhero:tenant:${t.toLowerCase()}`;
44
44
  }
45
- function re(t) {
45
+ function ce(t) {
46
46
  return {
47
47
  async beforeCreate(e, n) {
48
48
  return !n.audience && n.id ? {
49
49
  ...n,
50
- audience: se(n.id)
50
+ audience: ie(n.id)
51
51
  } : n;
52
52
  },
53
53
  async afterCreate(e, n) {
54
- const { accessControl: s, databaseIsolation: a } = t;
55
- s && e.ctx && await ae(e, n, s), a != null && a.onProvision && await a.onProvision(n.id);
54
+ const { accessControl: r, databaseIsolation: s } = t;
55
+ r && e.ctx && await le(e, n, r), s != null && s.onProvision && await s.onProvision(n.id);
56
56
  },
57
57
  async beforeDelete(e, n) {
58
- const { accessControl: s, databaseIsolation: a } = t;
59
- if (s)
58
+ const { accessControl: r, databaseIsolation: s } = t;
59
+ if (r)
60
60
  try {
61
61
  const o = (await e.adapters.organizations.list(
62
- s.controlPlaneTenantId
63
- )).organizations.find((r) => r.name === n);
62
+ r.controlPlaneTenantId
63
+ )).organizations.find((a) => a.name === n);
64
64
  o && await e.adapters.organizations.remove(
65
- s.controlPlaneTenantId,
65
+ r.controlPlaneTenantId,
66
66
  o.id
67
67
  );
68
- } catch (i) {
68
+ } catch (c) {
69
69
  console.warn(
70
70
  `Failed to remove organization for tenant ${n}:`,
71
- i
71
+ c
72
72
  );
73
73
  }
74
- if (a != null && a.onDeprovision)
74
+ if (s != null && s.onDeprovision)
75
75
  try {
76
- await a.onDeprovision(n);
77
- } catch (i) {
76
+ await s.onDeprovision(n);
77
+ } catch (c) {
78
78
  console.warn(
79
79
  `Failed to deprovision database for tenant ${n}:`,
80
- i
80
+ c
81
81
  );
82
82
  }
83
83
  }
84
84
  };
85
85
  }
86
- async function ae(t, e, n) {
86
+ async function le(t, e, n) {
87
87
  const {
88
- controlPlaneTenantId: s,
89
- defaultPermissions: a,
90
- defaultRoles: i,
88
+ controlPlaneTenantId: r,
89
+ defaultPermissions: s,
90
+ defaultRoles: c,
91
91
  issuer: o,
92
- adminRoleName: r = "Tenant Admin",
93
- adminRoleDescription: c = "Full access to all tenant management operations",
94
- addCreatorToOrganization: m = !0
95
- } = n, l = await t.adapters.organizations.create(
96
- s,
92
+ adminRoleName: a = "Tenant Admin",
93
+ adminRoleDescription: d = "Full access to all tenant management operations",
94
+ addCreatorToOrganization: u = !0
95
+ } = n, i = await t.adapters.organizations.create(
96
+ r,
97
97
  {
98
98
  name: e.id,
99
99
  display_name: e.friendly_name || e.id
100
100
  }
101
101
  );
102
102
  let f;
103
- if (o && (f = await ie(
103
+ if (o && (f = await ue(
104
104
  t,
105
- s,
106
105
  r,
107
- c
108
- )), m && t.ctx) {
109
- const d = t.ctx.var.user;
110
- if (d != null && d.sub && !await oe(
106
+ a,
107
+ d
108
+ )), u && t.ctx) {
109
+ const l = t.ctx.var.user;
110
+ if (l != null && l.sub && !await de(
111
111
  t,
112
- s,
113
- d.sub
112
+ r,
113
+ l.sub
114
114
  ))
115
115
  try {
116
- await t.adapters.userOrganizations.create(s, {
117
- user_id: d.sub,
118
- organization_id: l.id
116
+ await t.adapters.userOrganizations.create(r, {
117
+ user_id: l.sub,
118
+ organization_id: i.id
119
119
  }), f && await t.adapters.userRoles.create(
120
- s,
121
- d.sub,
120
+ r,
121
+ l.sub,
122
122
  f,
123
- l.id
123
+ i.id
124
124
  // organizationId
125
125
  );
126
- } catch (p) {
126
+ } catch (g) {
127
127
  console.warn(
128
- `Failed to add creator ${d.sub} to organization ${l.id}:`,
129
- p
128
+ `Failed to add creator ${l.sub} to organization ${i.id}:`,
129
+ g
130
130
  );
131
131
  }
132
132
  }
133
- i && i.length > 0 && console.log(
134
- `Would assign roles ${i.join(", ")} to organization ${l.id}`
135
- ), a && a.length > 0 && console.log(
136
- `Would grant permissions ${a.join(", ")} to organization ${l.id}`
133
+ c && c.length > 0 && console.log(
134
+ `Would assign roles ${c.join(", ")} to organization ${i.id}`
135
+ ), s && s.length > 0 && console.log(
136
+ `Would grant permissions ${s.join(", ")} to organization ${i.id}`
137
137
  );
138
138
  }
139
- async function oe(t, e, n) {
140
- const s = await t.adapters.userRoles.list(
139
+ async function de(t, e, n) {
140
+ const r = await t.adapters.userRoles.list(
141
141
  e,
142
142
  n,
143
143
  void 0,
144
144
  ""
145
145
  // Empty string for global roles
146
146
  );
147
- for (const a of s)
147
+ for (const s of r)
148
148
  if ((await t.adapters.rolePermissions.list(
149
149
  e,
150
- a.id,
150
+ s.id,
151
151
  { per_page: 1e3 }
152
152
  )).some(
153
- (r) => r.permission_name === "admin:organizations"
153
+ (a) => a.permission_name === "admin:organizations"
154
154
  ))
155
155
  return !0;
156
156
  return !1;
157
157
  }
158
- async function ie(t, e, n, s) {
159
- const i = (await t.adapters.roles.list(e, {})).roles.find((m) => m.name === n);
160
- if (i)
161
- return i.id;
158
+ async function ue(t, e, n, r) {
159
+ const c = (await t.adapters.roles.list(e, {})).roles.find((u) => u.name === n);
160
+ if (c)
161
+ return c.id;
162
162
  const o = await t.adapters.roles.create(e, {
163
163
  name: n,
164
- description: s
165
- }), r = L, c = J.map((m) => ({
164
+ description: r
165
+ }), a = W, d = x.map((u) => ({
166
166
  role_id: o.id,
167
- resource_server_identifier: r,
168
- permission_name: m.value
167
+ resource_server_identifier: a,
168
+ permission_name: u.value
169
169
  }));
170
170
  return await t.adapters.rolePermissions.assign(
171
171
  e,
172
172
  o.id,
173
- c
173
+ d
174
174
  ), o.id;
175
175
  }
176
- function E(t, e, n = () => !0) {
177
- const { controlPlaneTenantId: s, getChildTenantIds: a, getAdapters: i } = t, o = /* @__PURE__ */ new Map();
178
- async function r(l, f, d) {
179
- return (await e(l).list(f, {
180
- q: `name:${d}`,
176
+ function G(t, e, n = () => !0) {
177
+ const { controlPlaneTenantId: r, getChildTenantIds: s, getAdapters: c } = t, o = /* @__PURE__ */ new Map();
178
+ async function a(i, f, l) {
179
+ return (await e(i).list(f, {
180
+ q: `name:${l}`,
181
181
  per_page: 1
182
182
  }))[0] ?? null;
183
183
  }
184
- async function c(l) {
185
- const f = await a(), d = e(await i(s));
184
+ async function d(i) {
185
+ const f = await s(), l = e(await c(r));
186
186
  await Promise.all(
187
- f.map(async (u) => {
187
+ f.map(async (m) => {
188
188
  try {
189
- const p = await i(u), g = e(p), w = {
190
- ...d.transform(l),
189
+ const g = await c(m), p = e(g), w = {
190
+ ...l.transform(i),
191
191
  is_system: !0
192
- }, A = await r(p, u, l.name), v = A ? g.getId(A) : void 0;
193
- if (A && v) {
194
- const h = g.preserveOnUpdate ? g.preserveOnUpdate(A, w) : w;
195
- await g.update(u, v, h);
192
+ }, y = await a(g, m, i.name), T = y ? p.getId(y) : void 0;
193
+ if (y && T) {
194
+ const b = p.preserveOnUpdate ? p.preserveOnUpdate(y, w) : w;
195
+ await p.update(m, T, b);
196
196
  } else
197
- await g.create(u, w);
198
- } catch (p) {
197
+ await p.create(m, w);
198
+ } catch (g) {
199
199
  console.error(
200
- `Failed to sync ${d.listKey} "${l.name}" to tenant "${u}":`,
201
- p
200
+ `Failed to sync ${l.listKey} "${i.name}" to tenant "${m}":`,
201
+ g
202
202
  );
203
203
  }
204
204
  })
205
205
  );
206
206
  }
207
- async function m(l) {
208
- const f = await a();
207
+ async function u(i) {
208
+ const f = await s();
209
209
  await Promise.all(
210
- f.map(async (d) => {
210
+ f.map(async (l) => {
211
211
  try {
212
- const u = await i(d), p = e(u), g = await r(u, d, l), y = g ? p.getId(g) : void 0;
213
- g && y && await p.remove(d, y);
214
- } catch (u) {
212
+ const m = await c(l), g = e(m), p = await a(m, l, i), h = p ? g.getId(p) : void 0;
213
+ p && h && await g.remove(l, h);
214
+ } catch (m) {
215
215
  console.error(
216
- `Failed to delete entity "${l}" from tenant "${d}":`,
217
- u
216
+ `Failed to delete entity "${i}" from tenant "${l}":`,
217
+ m
218
218
  );
219
219
  }
220
220
  })
221
221
  );
222
222
  }
223
223
  return {
224
- afterCreate: async (l, f) => {
225
- l.tenantId === s && n(f) && await c(f);
224
+ afterCreate: async (i, f) => {
225
+ i.tenantId === r && n(f) && await d(f);
226
226
  },
227
- afterUpdate: async (l, f, d) => {
228
- l.tenantId === s && n(d) && await c(d);
227
+ afterUpdate: async (i, f, l) => {
228
+ i.tenantId === r && n(l) && await d(l);
229
229
  },
230
- beforeDelete: async (l, f) => {
231
- if (l.tenantId !== s) return;
232
- const u = await e(l.adapters).get(l.tenantId, f);
233
- u && n(u) && o.set(f, u);
230
+ beforeDelete: async (i, f) => {
231
+ if (i.tenantId !== r) return;
232
+ const m = await e(i.adapters).get(i.tenantId, f);
233
+ m && n(m) && o.set(f, m);
234
234
  },
235
- afterDelete: async (l, f) => {
236
- if (l.tenantId !== s) return;
237
- const d = o.get(f);
238
- d && (o.delete(f), await m(d.name));
235
+ afterDelete: async (i, f) => {
236
+ if (i.tenantId !== r) return;
237
+ const l = o.get(f);
238
+ l && (o.delete(f), await u(l.name));
239
239
  }
240
240
  };
241
241
  }
242
- function N(t, e, n = () => !0) {
243
- const { controlPlaneTenantId: s, getControlPlaneAdapters: a, getAdapters: i } = t;
242
+ function L(t, e, n = () => !0) {
243
+ const { controlPlaneTenantId: r, getControlPlaneAdapters: s, getAdapters: c } = t;
244
244
  return {
245
- async afterCreate(o, r) {
246
- if (r.id !== s)
245
+ async afterCreate(o, a) {
246
+ if (a.id !== r)
247
247
  try {
248
- const c = await a(), m = await i(r.id), l = e(c), f = e(m), d = await I(
249
- (u) => l.listPaginated(s, u),
250
- l.listKey,
248
+ const d = await s(), u = await c(a.id), i = e(d), f = e(u), l = await z(
249
+ (m) => i.listPaginated(r, m),
250
+ i.listKey,
251
251
  { cursorField: "id", pageSize: 100 }
252
252
  );
253
253
  await Promise.all(
254
- d.filter((u) => n(u)).map(async (u) => {
254
+ l.filter((m) => n(m)).map(async (m) => {
255
255
  try {
256
- const p = l.transform(u);
257
- await f.create(r.id, {
258
- ...p,
256
+ const g = i.transform(m);
257
+ await f.create(a.id, {
258
+ ...g,
259
259
  is_system: !0
260
260
  });
261
- } catch (p) {
261
+ } catch (g) {
262
262
  console.error(
263
- `Failed to sync entity to new tenant "${r.id}":`,
264
- p
263
+ `Failed to sync entity to new tenant "${a.id}":`,
264
+ g
265
265
  );
266
266
  }
267
267
  })
268
268
  );
269
- } catch (c) {
269
+ } catch (d) {
270
270
  console.error(
271
- `Failed to sync entities to new tenant "${r.id}":`,
272
- c
271
+ `Failed to sync entities to new tenant "${a.id}":`,
272
+ d
273
273
  );
274
274
  }
275
275
  }
276
276
  };
277
277
  }
278
- const H = (t) => ({
278
+ const U = (t) => ({
279
279
  list: async (e, n) => (await t.resourceServers.list(e, n)).resource_servers,
280
280
  listPaginated: (e, n) => t.resourceServers.list(e, n),
281
281
  get: (e, n) => t.resourceServers.get(e, n),
282
282
  create: (e, n) => t.resourceServers.create(e, n),
283
- update: (e, n, s) => t.resourceServers.update(e, n, s),
283
+ update: (e, n, r) => t.resourceServers.update(e, n, r),
284
284
  remove: (e, n) => t.resourceServers.remove(e, n),
285
285
  listKey: "resource_servers",
286
286
  getId: (e) => e.id,
@@ -293,12 +293,12 @@ const H = (t) => ({
293
293
  token_lifetime: e.token_lifetime,
294
294
  token_lifetime_for_web: e.token_lifetime_for_web
295
295
  })
296
- }), G = (t) => ({
296
+ }), B = (t) => ({
297
297
  list: async (e, n) => (await t.roles.list(e, n)).roles,
298
298
  listPaginated: (e, n) => t.roles.list(e, n),
299
299
  get: (e, n) => t.roles.get(e, n),
300
300
  create: (e, n) => t.roles.create(e, n),
301
- update: (e, n, s) => t.roles.update(e, n, s),
301
+ update: (e, n, r) => t.roles.update(e, n, r),
302
302
  remove: (e, n) => t.roles.remove(e, n),
303
303
  listKey: "roles",
304
304
  getId: (e) => e.id,
@@ -308,124 +308,128 @@ const H = (t) => ({
308
308
  description: e.description
309
309
  })
310
310
  });
311
- function ce(t) {
312
- const { sync: e = {}, filters: n = {} } = t, s = e.resourceServers ?? !0, a = e.roles ?? !0, i = s ? E(
311
+ function K(t) {
312
+ var e;
313
+ return ((e = t.metadata) == null ? void 0 : e.sync) !== !1;
314
+ }
315
+ function fe(t) {
316
+ const { sync: e = {}, filters: n = {} } = t, r = e.resourceServers ?? !0, s = e.roles ?? !0, c = (g) => K(g) ? n.resourceServers ? n.resourceServers(g) : !0 : !1, o = (g) => K(g) ? n.roles ? n.roles(g) : !0 : !1, a = r ? G(
313
317
  t,
314
- H,
315
- n.resourceServers
316
- ) : void 0, o = a ? E(
318
+ U,
319
+ c
320
+ ) : void 0, d = s ? G(
317
321
  t,
318
- G,
319
- n.roles
320
- ) : void 0, r = s ? N(
322
+ B,
323
+ o
324
+ ) : void 0, u = r ? L(
321
325
  t,
322
- H,
323
- n.resourceServers
324
- ) : void 0, c = a ? N(
326
+ U,
327
+ c
328
+ ) : void 0, i = s ? L(
325
329
  t,
326
- G,
327
- n.roles
328
- ) : void 0, m = a ? {
329
- async afterCreate(d, u) {
330
- var p;
331
- if (u.id !== t.controlPlaneTenantId) {
332
- await ((p = c == null ? void 0 : c.afterCreate) == null ? void 0 : p.call(c, d, u));
330
+ B,
331
+ o
332
+ ) : void 0, f = s ? {
333
+ async afterCreate(g, p) {
334
+ var h;
335
+ if (p.id !== t.controlPlaneTenantId) {
336
+ await ((h = i == null ? void 0 : i.afterCreate) == null ? void 0 : h.call(i, g, p));
333
337
  try {
334
- const g = await t.getControlPlaneAdapters(), y = await t.getAdapters(u.id), w = await I(
335
- (v) => g.roles.list(
338
+ const w = await t.getControlPlaneAdapters(), y = await t.getAdapters(p.id), T = await z(
339
+ (A) => w.roles.list(
336
340
  t.controlPlaneTenantId,
337
- v
341
+ A
338
342
  ),
339
343
  "roles",
340
344
  { cursorField: "id", pageSize: 100 }
341
- ), A = /* @__PURE__ */ new Map();
342
- for (const v of w.filter(
343
- (h) => {
344
- var T;
345
- return ((T = n.roles) == null ? void 0 : T.call(n, h)) ?? !0;
345
+ ), b = /* @__PURE__ */ new Map();
346
+ for (const A of T.filter(
347
+ (_) => {
348
+ var v;
349
+ return ((v = n.roles) == null ? void 0 : v.call(n, _)) ?? !0;
346
350
  }
347
351
  )) {
348
- const h = await l(
352
+ const _ = await l(
349
353
  y,
350
- u.id,
351
- v.name
354
+ p.id,
355
+ A.name
352
356
  );
353
- h && A.set(v.name, h.id);
357
+ _ && b.set(A.name, _.id);
354
358
  }
355
- for (const v of w.filter(
356
- (h) => {
357
- var T;
358
- return ((T = n.roles) == null ? void 0 : T.call(n, h)) ?? !0;
359
+ for (const A of T.filter(
360
+ (_) => {
361
+ var v;
362
+ return ((v = n.roles) == null ? void 0 : v.call(n, _)) ?? !0;
359
363
  }
360
364
  )) {
361
- const h = A.get(v.name);
362
- if (h)
365
+ const _ = b.get(A.name);
366
+ if (_)
363
367
  try {
364
- const T = await g.rolePermissions.list(
368
+ const v = await w.rolePermissions.list(
365
369
  t.controlPlaneTenantId,
366
- v.id,
370
+ A.id,
367
371
  {}
368
372
  );
369
- T.length > 0 && await y.rolePermissions.assign(
370
- u.id,
371
- h,
372
- T.map((_) => ({
373
- role_id: h,
374
- resource_server_identifier: _.resource_server_identifier,
375
- permission_name: _.permission_name
373
+ v.length > 0 && await y.rolePermissions.assign(
374
+ p.id,
375
+ _,
376
+ v.map((P) => ({
377
+ role_id: _,
378
+ resource_server_identifier: P.resource_server_identifier,
379
+ permission_name: P.permission_name
376
380
  }))
377
381
  );
378
- } catch (T) {
382
+ } catch (v) {
379
383
  console.error(
380
- `Failed to sync permissions for role "${v.name}" to tenant "${u.id}":`,
381
- T
384
+ `Failed to sync permissions for role "${A.name}" to tenant "${p.id}":`,
385
+ v
382
386
  );
383
387
  }
384
388
  }
385
- } catch (g) {
389
+ } catch (w) {
386
390
  console.error(
387
- `Failed to sync role permissions to tenant "${u.id}":`,
388
- g
391
+ `Failed to sync role permissions to tenant "${p.id}":`,
392
+ w
389
393
  );
390
394
  }
391
395
  }
392
396
  }
393
397
  } : void 0;
394
- async function l(d, u, p) {
395
- return (await d.roles.list(u, {
396
- q: `name:${p}`,
398
+ async function l(g, p, h) {
399
+ return (await g.roles.list(p, {
400
+ q: `name:${h}`,
397
401
  per_page: 1
398
402
  })).roles[0] ?? null;
399
403
  }
400
404
  return {
401
405
  entityHooks: {
402
- resourceServers: i,
403
- roles: o
406
+ resourceServers: a,
407
+ roles: d
404
408
  },
405
409
  tenantHooks: {
406
- async afterCreate(d, u) {
407
- const p = [
408
- r == null ? void 0 : r.afterCreate,
409
- (m == null ? void 0 : m.afterCreate) ?? (c == null ? void 0 : c.afterCreate)
410
- ], g = [];
411
- for (const y of p)
410
+ async afterCreate(g, p) {
411
+ const h = [
412
+ u == null ? void 0 : u.afterCreate,
413
+ (f == null ? void 0 : f.afterCreate) ?? (i == null ? void 0 : i.afterCreate)
414
+ ], w = [];
415
+ for (const y of h)
412
416
  if (y)
413
417
  try {
414
- await y(d, u);
415
- } catch (w) {
416
- g.push(w instanceof Error ? w : new Error(String(w)));
418
+ await y(g, p);
419
+ } catch (T) {
420
+ w.push(T instanceof Error ? T : new Error(String(T)));
417
421
  }
418
- if (g.length === 1) throw g[0];
419
- if (g.length > 1)
422
+ if (w.length === 1) throw w[0];
423
+ if (w.length > 1)
420
424
  throw new AggregateError(
421
- g,
422
- g.map((y) => y.message).join("; ")
425
+ w,
426
+ w.map((y) => y.message).join("; ")
423
427
  );
424
428
  }
425
429
  }
426
430
  };
427
431
  }
428
- var b = class extends Error {
432
+ var C = class extends Error {
429
433
  /**
430
434
  * Creates an instance of `HTTPException`.
431
435
  * @param status - HTTP status code for the exception. Defaults to 500.
@@ -433,8 +437,8 @@ var b = class extends Error {
433
437
  */
434
438
  constructor(e = 500, n) {
435
439
  super(n == null ? void 0 : n.message, { cause: n == null ? void 0 : n.cause });
436
- $(this, "res");
437
- $(this, "status");
440
+ R(this, "res");
441
+ R(this, "status");
438
442
  this.res = n == null ? void 0 : n.res, this.status = e;
439
443
  }
440
444
  /**
@@ -451,15 +455,15 @@ var b = class extends Error {
451
455
  });
452
456
  }
453
457
  };
454
- function M(t, e) {
455
- const n = new x();
458
+ function D(t, e) {
459
+ const n = new re();
456
460
  return n.openapi(
457
- O({
461
+ M({
458
462
  tags: ["tenants"],
459
463
  method: "get",
460
464
  path: "/",
461
465
  request: {
462
- query: X
466
+ query: ee
463
467
  },
464
468
  security: [
465
469
  {
@@ -470,11 +474,11 @@ function M(t, e) {
470
474
  200: {
471
475
  content: {
472
476
  "application/json": {
473
- schema: C.object({
474
- tenants: C.array(k),
475
- start: C.number().optional(),
476
- limit: C.number().optional(),
477
- length: C.number().optional()
477
+ schema: S.object({
478
+ tenants: S.array(H),
479
+ start: S.number().optional(),
480
+ limit: S.number().optional(),
481
+ length: S.number().optional()
478
482
  })
479
483
  }
480
484
  },
@@ -482,75 +486,76 @@ function M(t, e) {
482
486
  }
483
487
  }
484
488
  }),
485
- async (s) => {
486
- var u, p, g, y;
487
- const a = s.req.valid("query"), { page: i, per_page: o, include_totals: r, q: c } = a, m = s.var.user, l = (m == null ? void 0 : m.permissions) || [];
488
- if (l.includes("auth:read") || l.includes("admin:organizations")) {
489
- const w = await s.env.data.tenants.list({
490
- page: i,
489
+ async (r) => {
490
+ var g, p, h, w, y, T;
491
+ const s = r.req.valid("query"), { page: c, per_page: o, include_totals: a, q: d } = s, u = r.var.user, i = (u == null ? void 0 : u.permissions) || [];
492
+ if (i.includes("auth:read") || i.includes("admin:organizations")) {
493
+ const b = await r.env.data.tenants.list({
494
+ page: c,
491
495
  per_page: o,
492
- include_totals: r,
493
- q: c
496
+ include_totals: a,
497
+ q: d
494
498
  });
495
- return r ? s.json({
496
- tenants: w.tenants,
497
- start: ((u = w.totals) == null ? void 0 : u.start) ?? 0,
498
- limit: ((p = w.totals) == null ? void 0 : p.limit) ?? o,
499
- length: w.tenants.length
500
- }) : s.json({ tenants: w.tenants });
499
+ return a ? r.json({
500
+ tenants: b.tenants,
501
+ start: ((g = b.totals) == null ? void 0 : g.start) ?? 0,
502
+ limit: ((p = b.totals) == null ? void 0 : p.limit) ?? o,
503
+ length: b.tenants.length
504
+ }) : r.json({ tenants: b.tenants });
501
505
  }
502
- if (t.accessControl && (m != null && m.sub)) {
503
- const w = t.accessControl.controlPlaneTenantId, v = (await I(
504
- (P) => s.env.data.userOrganizations.listUserOrganizations(
505
- w,
506
- m.sub,
507
- P
506
+ const l = ((h = t.accessControl) == null ? void 0 : h.controlPlaneTenantId) ?? ((w = r.env.data.multiTenancyConfig) == null ? void 0 : w.controlPlaneTenantId);
507
+ if (l && (u != null && u.sub)) {
508
+ const A = (await z(
509
+ ($) => r.env.data.userOrganizations.listUserOrganizations(
510
+ l,
511
+ u.sub,
512
+ $
508
513
  ),
509
514
  "organizations"
510
- )).map((P) => P.name);
511
- if (v.length === 0)
512
- return r ? s.json({
515
+ )).map(($) => $.name);
516
+ if (A.length === 0)
517
+ return a ? r.json({
513
518
  tenants: [],
514
519
  start: 0,
515
520
  limit: o ?? 50,
516
521
  length: 0
517
- }) : s.json({ tenants: [] });
518
- const h = v.length, T = i ?? 0, _ = o ?? 50, S = T * _, D = v.slice(S, S + _);
519
- if (D.length === 0)
520
- return r ? s.json({
522
+ }) : r.json({ tenants: [] });
523
+ const _ = A.length, v = c ?? 0, P = o ?? 50, I = v * P, k = A.slice(I, I + P);
524
+ if (k.length === 0)
525
+ return a ? r.json({
521
526
  tenants: [],
522
- start: S,
523
- limit: _,
524
- length: h
525
- }) : s.json({ tenants: [] });
526
- const F = D.map((P) => `id:${P}`).join(" OR "), K = c ? `(${F}) AND (${c})` : F, j = await s.env.data.tenants.list({
527
- q: K,
528
- per_page: _,
527
+ start: I,
528
+ limit: P,
529
+ length: _
530
+ }) : r.json({ tenants: [] });
531
+ const E = k.map(($) => `id:${$}`).join(" OR "), J = d ? `(${E}) AND (${d})` : E, N = await r.env.data.tenants.list({
532
+ q: J,
533
+ per_page: P,
529
534
  include_totals: !1
530
535
  // We calculate totals from accessibleTenantIds
531
536
  });
532
- return r ? s.json({
533
- tenants: j.tenants,
534
- start: S,
535
- limit: _,
536
- length: h
537
- }) : s.json({ tenants: j.tenants });
537
+ return a ? r.json({
538
+ tenants: N.tenants,
539
+ start: I,
540
+ limit: P,
541
+ length: _
542
+ }) : r.json({ tenants: N.tenants });
538
543
  }
539
- const d = await s.env.data.tenants.list({
540
- page: i,
544
+ const m = await r.env.data.tenants.list({
545
+ page: c,
541
546
  per_page: o,
542
- include_totals: r,
543
- q: c
547
+ include_totals: a,
548
+ q: d
544
549
  });
545
- return r ? s.json({
546
- tenants: d.tenants,
547
- start: ((g = d.totals) == null ? void 0 : g.start) ?? 0,
548
- limit: ((y = d.totals) == null ? void 0 : y.limit) ?? o,
549
- length: d.tenants.length
550
- }) : s.json({ tenants: d.tenants });
550
+ return a ? r.json({
551
+ tenants: m.tenants,
552
+ start: ((y = m.totals) == null ? void 0 : y.start) ?? 0,
553
+ limit: ((T = m.totals) == null ? void 0 : T.limit) ?? o,
554
+ length: m.tenants.length
555
+ }) : r.json({ tenants: m.tenants });
551
556
  }
552
557
  ), n.openapi(
553
- O({
558
+ M({
554
559
  tags: ["tenants"],
555
560
  method: "post",
556
561
  path: "/",
@@ -558,7 +563,7 @@ function M(t, e) {
558
563
  body: {
559
564
  content: {
560
565
  "application/json": {
561
- schema: Y
566
+ schema: te
562
567
  }
563
568
  }
564
569
  }
@@ -572,7 +577,7 @@ function M(t, e) {
572
577
  201: {
573
578
  content: {
574
579
  "application/json": {
575
- schema: k
580
+ schema: H
576
581
  }
577
582
  },
578
583
  description: "Tenant created"
@@ -585,30 +590,30 @@ function M(t, e) {
585
590
  }
586
591
  }
587
592
  }),
588
- async (s) => {
589
- var c, m;
590
- const a = s.var.user;
591
- if (!(a != null && a.sub))
592
- throw new b(401, {
593
+ async (r) => {
594
+ var d, u;
595
+ const s = r.var.user;
596
+ if (!(s != null && s.sub))
597
+ throw new C(401, {
593
598
  message: "Authentication required to create tenants"
594
599
  });
595
- let i = s.req.valid("json");
600
+ let c = r.req.valid("json");
596
601
  const o = {
597
- adapters: s.env.data,
598
- ctx: s
602
+ adapters: r.env.data,
603
+ ctx: r
599
604
  };
600
- (c = e.tenants) != null && c.beforeCreate && (i = await e.tenants.beforeCreate(o, i));
601
- const r = await s.env.data.tenants.create(i);
602
- return (m = e.tenants) != null && m.afterCreate && await e.tenants.afterCreate(o, r), s.json(r, 201);
605
+ (d = e.tenants) != null && d.beforeCreate && (c = await e.tenants.beforeCreate(o, c));
606
+ const a = await r.env.data.tenants.create(c);
607
+ return (u = e.tenants) != null && u.afterCreate && await e.tenants.afterCreate(o, a), r.json(a, 201);
603
608
  }
604
609
  ), n.openapi(
605
- O({
610
+ M({
606
611
  tags: ["tenants"],
607
612
  method: "delete",
608
613
  path: "/{id}",
609
614
  request: {
610
- params: C.object({
611
- id: C.string()
615
+ params: S.object({
616
+ id: S.string()
612
617
  })
613
618
  },
614
619
  security: [
@@ -628,44 +633,44 @@ function M(t, e) {
628
633
  }
629
634
  }
630
635
  }),
631
- async (s) => {
632
- var r, c;
633
- const { id: a } = s.req.valid("param");
634
- if (t.accessControl) {
635
- const m = s.var.user, l = t.accessControl.controlPlaneTenantId;
636
- if (!(m != null && m.sub))
637
- throw new b(401, {
636
+ async (r) => {
637
+ var d, u, i, f;
638
+ const { id: s } = r.req.valid("param"), c = ((d = t.accessControl) == null ? void 0 : d.controlPlaneTenantId) ?? ((u = r.env.data.multiTenancyConfig) == null ? void 0 : u.controlPlaneTenantId);
639
+ if (c) {
640
+ const l = r.var.user;
641
+ if (!(l != null && l.sub))
642
+ throw new C(401, {
638
643
  message: "Authentication required"
639
644
  });
640
- if (a === l)
641
- throw new b(403, {
645
+ if (s === c)
646
+ throw new C(403, {
642
647
  message: "Cannot delete the control plane"
643
648
  });
644
- if (!(await I(
645
- (u) => s.env.data.userOrganizations.listUserOrganizations(
646
- l,
647
- m.sub,
648
- u
649
+ if (!(await z(
650
+ (p) => r.env.data.userOrganizations.listUserOrganizations(
651
+ c,
652
+ l.sub,
653
+ p
649
654
  ),
650
655
  "organizations"
651
- )).some((u) => u.name === a))
652
- throw new b(403, {
656
+ )).some((p) => p.name === s))
657
+ throw new C(403, {
653
658
  message: "Access denied to this tenant"
654
659
  });
655
660
  }
656
- if (!await s.env.data.tenants.get(a))
657
- throw new b(404, {
661
+ if (!await r.env.data.tenants.get(s))
662
+ throw new C(404, {
658
663
  message: "Tenant not found"
659
664
  });
660
- const o = {
661
- adapters: s.env.data,
662
- ctx: s
665
+ const a = {
666
+ adapters: r.env.data,
667
+ ctx: r
663
668
  };
664
- return (r = e.tenants) != null && r.beforeDelete && await e.tenants.beforeDelete(o, a), await s.env.data.tenants.remove(a), (c = e.tenants) != null && c.afterDelete && await e.tenants.afterDelete(o, a), s.body(null, 204);
669
+ return (i = e.tenants) != null && i.beforeDelete && await e.tenants.beforeDelete(a, s), await r.env.data.tenants.remove(s), (f = e.tenants) != null && f.afterDelete && await e.tenants.afterDelete(a, s), r.body(null, 204);
665
670
  }
666
671
  ), n;
667
672
  }
668
- function le(t) {
673
+ function me(t) {
669
674
  const e = [
670
675
  {
671
676
  pattern: /\/api\/v2\/resource-servers\/([^/]+)$/,
@@ -674,27 +679,27 @@ function le(t) {
674
679
  { pattern: /\/api\/v2\/roles\/([^/]+)$/, type: "role" },
675
680
  { pattern: /\/api\/v2\/connections\/([^/]+)$/, type: "connection" }
676
681
  ];
677
- for (const { pattern: n, type: s } of e) {
678
- const a = t.match(n);
679
- if (a && a[1])
680
- return { type: s, id: a[1] };
682
+ for (const { pattern: n, type: r } of e) {
683
+ const s = t.match(n);
684
+ if (s && s[1])
685
+ return { type: r, id: s[1] };
681
686
  }
682
687
  return null;
683
688
  }
684
- async function de(t, e, n) {
689
+ async function ge(t, e, n) {
685
690
  try {
686
691
  switch (n.type) {
687
692
  case "resource_server": {
688
- const s = await t.resourceServers.get(e, n.id);
689
- return (s == null ? void 0 : s.is_system) === !0;
693
+ const r = await t.resourceServers.get(e, n.id);
694
+ return (r == null ? void 0 : r.is_system) === !0;
690
695
  }
691
696
  case "role": {
692
- const s = await t.roles.get(e, n.id);
693
- return (s == null ? void 0 : s.is_system) === !0;
697
+ const r = await t.roles.get(e, n.id);
698
+ return (r == null ? void 0 : r.is_system) === !0;
694
699
  }
695
700
  case "connection": {
696
- const s = await t.connections.get(e, n.id);
697
- return (s == null ? void 0 : s.is_system) === !0;
701
+ const r = await t.connections.get(e, n.id);
702
+ return (r == null ? void 0 : r.is_system) === !0;
698
703
  }
699
704
  default:
700
705
  return !1;
@@ -703,128 +708,133 @@ async function de(t, e, n) {
703
708
  return !1;
704
709
  }
705
710
  }
706
- function ue(t) {
711
+ function pe(t) {
707
712
  return {
708
713
  resource_server: "resource server",
709
714
  role: "role",
710
715
  connection: "connection"
711
716
  }[t];
712
717
  }
713
- function me() {
718
+ function we() {
714
719
  return async (t, e) => {
715
720
  if (!["PATCH", "PUT", "DELETE"].includes(t.req.method))
716
721
  return e();
717
- const n = le(t.req.path);
722
+ const n = me(t.req.path);
718
723
  if (!n)
719
724
  return e();
720
- const s = t.var.tenant_id || t.req.header("x-tenant-id") || t.req.header("tenant-id");
721
- if (!s)
725
+ const r = t.var.tenant_id || t.req.header("x-tenant-id") || t.req.header("tenant-id");
726
+ if (!r)
722
727
  return e();
723
- if (await de(t.env.data, s, n))
724
- throw new b(403, {
725
- message: `This ${ue(n.type)} is a system resource and cannot be modified. Make changes in the control plane instead.`
728
+ if (await ge(t.env.data, r, n))
729
+ throw new C(403, {
730
+ message: `This ${pe(n.type)} is a system resource and cannot be modified. Make changes in the control plane instead.`
726
731
  });
727
732
  return e();
728
733
  };
729
734
  }
730
- function U(t, e) {
731
- const { controlPlaneTenantId: n, controlPlaneClientId: s } = e;
735
+ function Q(t, e) {
736
+ const { controlPlaneTenantId: n, controlPlaneClientId: r } = e;
732
737
  return {
733
738
  ...t,
739
+ // Store config for use by tenants route access control
740
+ multiTenancyConfig: {
741
+ controlPlaneTenantId: n,
742
+ controlPlaneClientId: r
743
+ },
734
744
  legacyClients: {
735
745
  ...t.legacyClients,
736
- get: async (a) => {
746
+ get: async (s) => {
737
747
  var f;
738
- const i = await t.legacyClients.get(a);
739
- if (!i)
748
+ const c = await t.legacyClients.get(s);
749
+ if (!c)
740
750
  return null;
741
- const o = s ? await t.legacyClients.get(s) : void 0, r = await t.connections.list(
742
- i.tenant.id
743
- ), c = n ? await t.connections.list(n) : { connections: [] }, m = r.connections.map((d) => {
744
- var g;
745
- const u = (g = c.connections) == null ? void 0 : g.find(
746
- (y) => y.strategy === d.strategy
751
+ const o = r ? await t.legacyClients.get(r) : void 0, a = await t.connections.list(
752
+ c.tenant.id
753
+ ), d = n ? await t.connections.list(n) : { connections: [] }, u = a.connections.map((l) => {
754
+ var p;
755
+ const m = (p = d.connections) == null ? void 0 : p.find(
756
+ (h) => h.strategy === l.strategy
747
757
  );
748
- if (!(u != null && u.options))
749
- return d;
750
- const p = z.parse({
751
- ...u || {},
752
- ...d
758
+ if (!(m != null && m.options))
759
+ return l;
760
+ const g = F.parse({
761
+ ...m || {},
762
+ ...l
753
763
  });
754
- return p.options = R.parse({
755
- ...u.options || {},
756
- ...d.options
757
- }), p;
758
- }).filter((d) => d), l = {
764
+ return g.options = O.parse({
765
+ ...m.options || {},
766
+ ...l.options
767
+ }), g;
768
+ }).filter((l) => l), i = {
759
769
  ...(o == null ? void 0 : o.tenant) || {},
760
- ...i.tenant
770
+ ...c.tenant
761
771
  };
762
- return !i.tenant.audience && ((f = o == null ? void 0 : o.tenant) != null && f.audience) && (l.audience = o.tenant.audience), {
763
- ...i,
772
+ return !c.tenant.audience && ((f = o == null ? void 0 : o.tenant) != null && f.audience) && (i.audience = o.tenant.audience), {
773
+ ...c,
764
774
  web_origins: [
765
775
  ...(o == null ? void 0 : o.web_origins) || [],
766
- ...i.web_origins || []
776
+ ...c.web_origins || []
767
777
  ],
768
778
  allowed_logout_urls: [
769
779
  ...(o == null ? void 0 : o.allowed_logout_urls) || [],
770
- ...i.allowed_logout_urls || []
780
+ ...c.allowed_logout_urls || []
771
781
  ],
772
782
  callbacks: [
773
783
  ...(o == null ? void 0 : o.callbacks) || [],
774
- ...i.callbacks || []
784
+ ...c.callbacks || []
775
785
  ],
776
- connections: m,
777
- tenant: l
786
+ connections: u,
787
+ tenant: i
778
788
  };
779
789
  }
780
790
  },
781
791
  connections: {
782
792
  ...t.connections,
783
- get: async (a, i) => {
784
- var l;
793
+ get: async (s, c) => {
794
+ var i;
785
795
  const o = await t.connections.get(
786
- a,
787
- i
796
+ s,
797
+ c
788
798
  );
789
- if (!o || !n || a === n)
799
+ if (!o || !n || s === n)
790
800
  return o;
791
- const c = (l = (await t.connections.list(n)).connections) == null ? void 0 : l.find(
801
+ const d = (i = (await t.connections.list(n)).connections) == null ? void 0 : i.find(
792
802
  (f) => f.strategy === o.strategy
793
803
  );
794
- if (!(c != null && c.options))
804
+ if (!(d != null && d.options))
795
805
  return o;
796
- const m = z.parse({
797
- ...c,
806
+ const u = F.parse({
807
+ ...d,
798
808
  ...o
799
809
  });
800
- return m.options = R.parse({
801
- ...c.options || {},
810
+ return u.options = O.parse({
811
+ ...d.options || {},
802
812
  ...o.options
803
- }), m;
813
+ }), u;
804
814
  },
805
- list: async (a, i) => {
806
- const o = await t.connections.list(a, i);
807
- if (!n || a === n)
815
+ list: async (s, c) => {
816
+ const o = await t.connections.list(s, c);
817
+ if (!n || s === n)
808
818
  return o;
809
- const r = await t.connections.list(n), c = o.connections.map((m) => {
810
- var d;
811
- const l = (d = r.connections) == null ? void 0 : d.find(
812
- (u) => u.strategy === m.strategy
819
+ const a = await t.connections.list(n), d = o.connections.map((u) => {
820
+ var l;
821
+ const i = (l = a.connections) == null ? void 0 : l.find(
822
+ (m) => m.strategy === u.strategy
813
823
  );
814
- if (!(l != null && l.options))
815
- return m;
816
- const f = z.parse({
817
- ...l,
818
- ...m
824
+ if (!(i != null && i.options))
825
+ return u;
826
+ const f = F.parse({
827
+ ...i,
828
+ ...u
819
829
  });
820
- return f.options = R.parse({
821
- ...l.options || {},
822
- ...m.options
830
+ return f.options = O.parse({
831
+ ...i.options || {},
832
+ ...u.options
823
833
  }), f;
824
834
  });
825
835
  return {
826
836
  ...o,
827
- connections: c
837
+ connections: d
828
838
  };
829
839
  }
830
840
  }
@@ -837,171 +847,174 @@ function U(t, e) {
837
847
  // They remain part of ...baseAdapters and can be properly wrapped by caching.
838
848
  };
839
849
  }
840
- function fe(t, e) {
841
- return U(t, e);
850
+ function q(t, e) {
851
+ return Q(t, e);
842
852
  }
843
- const Ae = U, Ce = fe;
844
- function ge(t) {
853
+ const Pe = Q, Se = q;
854
+ function ye(t) {
845
855
  return async (e, n) => {
846
- const s = e.var.user;
847
- return (s == null ? void 0 : s.tenant_id) === t && s.org_name && e.set("tenant_id", s.org_name), n();
856
+ const r = e.var.user;
857
+ return (r == null ? void 0 : r.tenant_id) === t && r.org_name && e.set("tenant_id", r.org_name), n();
848
858
  };
849
859
  }
850
- function pe(t) {
860
+ function he(t) {
851
861
  return async (e, n) => {
852
862
  if (!t.accessControl)
853
863
  return n();
854
- const { controlPlaneTenantId: s } = t.accessControl, a = e.var.org_name, i = e.var.organization_id, o = a || i;
855
- let r = e.var.tenant_id;
856
- const c = e.var.user, l = (c != null && c.aud ? Array.isArray(c.aud) ? c.aud : [c.aud] : []).includes(L);
857
- if (!r && o && l && (e.set("tenant_id", o), r = o), !r)
858
- throw new b(400, {
864
+ const { controlPlaneTenantId: r } = t.accessControl, s = e.var.org_name, c = e.var.organization_id, o = s || c;
865
+ let a = e.var.tenant_id;
866
+ const d = e.var.user, i = (d != null && d.aud ? Array.isArray(d.aud) ? d.aud : [d.aud] : []).includes(W);
867
+ if (!a && o && i && (e.set("tenant_id", o), a = o), !a)
868
+ throw new C(400, {
859
869
  message: "Tenant ID not found in request"
860
870
  });
861
- if (!te(
862
- i,
871
+ if (!ae(
872
+ c,
873
+ a,
863
874
  r,
864
- s,
865
- a
875
+ s
866
876
  ))
867
- throw new b(403, {
868
- message: `Access denied to tenant ${r}`
877
+ throw new C(403, {
878
+ message: `Access denied to tenant ${a}`
869
879
  });
870
880
  return n();
871
881
  };
872
882
  }
873
- function we(t) {
883
+ function ve(t) {
874
884
  return async (e, n) => {
875
885
  if (!t.subdomainRouting)
876
886
  return n();
877
887
  const {
878
- baseDomain: s,
879
- reservedSubdomains: a = [],
880
- resolveSubdomain: i
888
+ baseDomain: r,
889
+ reservedSubdomains: s = [],
890
+ resolveSubdomain: c
881
891
  } = t.subdomainRouting, o = e.req.header("host") || "";
882
- let r = null;
883
- if (o.endsWith(s)) {
884
- const m = o.slice(0, -(s.length + 1));
885
- m && !m.includes(".") && (r = m);
892
+ let a = null;
893
+ if (o.endsWith(r)) {
894
+ const u = o.slice(0, -(r.length + 1));
895
+ u && !u.includes(".") && (a = u);
886
896
  }
887
- if (r && a.includes(r) && (r = null), !r)
897
+ if (a && s.includes(a) && (a = null), !a)
888
898
  return t.accessControl && e.set("tenant_id", t.accessControl.controlPlaneTenantId), n();
889
- let c = null;
890
- if (i)
891
- c = await i(r);
899
+ let d = null;
900
+ if (c)
901
+ d = await c(a);
892
902
  else if (t.subdomainRouting.useOrganizations !== !1 && t.accessControl)
893
903
  try {
894
- const m = await e.env.data.organizations.get(
904
+ const u = await e.env.data.organizations.get(
895
905
  t.accessControl.controlPlaneTenantId,
896
- r
906
+ a
897
907
  );
898
- m && (c = m.id);
908
+ u && (d = u.id);
899
909
  } catch {
900
910
  }
901
- if (!c)
902
- throw new b(404, {
903
- message: `Tenant not found for subdomain: ${r}`
911
+ if (!d)
912
+ throw new C(404, {
913
+ message: `Tenant not found for subdomain: ${a}`
904
914
  });
905
- return e.set("tenant_id", c), n();
915
+ return e.set("tenant_id", d), n();
906
916
  };
907
917
  }
908
- function ye(t) {
918
+ function Te(t) {
909
919
  return async (e, n) => {
910
920
  if (!t.databaseIsolation)
911
921
  return n();
912
- const s = e.var.tenant_id;
913
- if (!s)
914
- throw new b(400, {
922
+ const r = e.var.tenant_id;
923
+ if (!r)
924
+ throw new C(400, {
915
925
  message: "Tenant ID not found in request"
916
926
  });
917
927
  try {
918
- const a = await t.databaseIsolation.getAdapters(s);
919
- e.env.data = a;
920
- } catch (a) {
928
+ const s = await t.databaseIsolation.getAdapters(r);
929
+ e.env.data = s;
930
+ } catch (s) {
921
931
  throw console.error(
922
- `Failed to resolve database for tenant ${s}:`,
923
- a
924
- ), new b(500, {
932
+ `Failed to resolve database for tenant ${r}:`,
933
+ s
934
+ ), new C(500, {
925
935
  message: "Failed to resolve tenant database"
926
936
  });
927
937
  }
928
938
  return n();
929
939
  };
930
940
  }
931
- function B(t) {
932
- const e = we(t), n = pe(t), s = ye(t);
933
- return async (a, i) => (await e(a, async () => {
934
- }), await n(a, async () => {
935
- }), await s(a, async () => {
936
- }), i());
941
+ function V(t) {
942
+ const e = ve(t), n = he(t), r = Te(t);
943
+ return async (s, c) => (await e(s, async () => {
944
+ }), await n(s, async () => {
945
+ }), await r(s, async () => {
946
+ }), c());
937
947
  }
938
- function Pe(t) {
948
+ function $e(t) {
939
949
  const {
940
950
  dataAdapter: e,
941
- controlPlaneTenantId: n = "control_plane",
942
- sync: s = { resourceServers: !0, roles: !0 },
943
- defaultPermissions: a = ["tenant:admin"],
944
- requireOrganizationMatch: i = !1,
951
+ controlPlane: n,
952
+ sync: r = { resourceServers: !0, roles: !0 },
953
+ defaultPermissions: s = ["tenant:admin"],
954
+ requireOrganizationMatch: c = !1,
945
955
  managementApiExtensions: o = [],
946
- entityHooks: r,
947
- getChildTenantIds: c,
948
- getAdapters: m,
949
- ...l
950
- } = t, f = s !== !1, d = f ? {
951
- resourceServers: s.resourceServers ?? !0,
952
- roles: s.roles ?? !0
953
- } : { resourceServers: !1, roles: !1 }, g = {
954
- controlPlaneTenantId: n,
955
- getChildTenantIds: c ?? (async () => (await I(
956
- (_) => e.tenants.list(_),
956
+ entityHooks: a,
957
+ getChildTenantIds: d,
958
+ getAdapters: u,
959
+ ...i
960
+ } = t, f = (n == null ? void 0 : n.tenantId) ?? "control_plane", l = n == null ? void 0 : n.clientId, m = n ? q(e, {
961
+ controlPlaneTenantId: f,
962
+ controlPlaneClientId: l
963
+ }) : e, g = r !== !1, p = g ? {
964
+ resourceServers: r.resourceServers ?? !0,
965
+ roles: r.roles ?? !0
966
+ } : { resourceServers: !1, roles: !1 }, y = {
967
+ controlPlaneTenantId: f,
968
+ getChildTenantIds: d ?? (async () => (await z(
969
+ (I) => m.tenants.list(I),
957
970
  "tenants",
958
971
  { cursorField: "id", pageSize: 100 }
959
- )).filter((_) => _.id !== n).map((_) => _.id)),
960
- getAdapters: m ?? (async () => e),
961
- getControlPlaneAdapters: async () => e,
962
- sync: d
963
- }, { entityHooks: y, tenantHooks: w } = ce(g), A = {
972
+ )).filter((I) => I.id !== f).map((I) => I.id)),
973
+ getAdapters: u ?? (async () => m),
974
+ getControlPlaneAdapters: async () => m,
975
+ sync: p
976
+ }, { entityHooks: T, tenantHooks: b } = fe(y), A = {
964
977
  resourceServers: [
965
- y.resourceServers,
966
- ...(r == null ? void 0 : r.resourceServers) ?? []
978
+ T.resourceServers,
979
+ ...(a == null ? void 0 : a.resourceServers) ?? []
967
980
  ],
968
- roles: [y.roles, ...(r == null ? void 0 : r.roles) ?? []],
969
- connections: (r == null ? void 0 : r.connections) ?? [],
970
- tenants: (r == null ? void 0 : r.tenants) ?? [],
971
- rolePermissions: (r == null ? void 0 : r.rolePermissions) ?? []
972
- }, v = M(
981
+ roles: [T.roles, ...(a == null ? void 0 : a.roles) ?? []],
982
+ connections: (a == null ? void 0 : a.connections) ?? [],
983
+ tenants: (a == null ? void 0 : a.tenants) ?? [],
984
+ rolePermissions: (a == null ? void 0 : a.rolePermissions) ?? []
985
+ }, _ = D(
973
986
  {
974
987
  accessControl: {
975
- controlPlaneTenantId: n,
976
- requireOrganizationMatch: i,
977
- defaultPermissions: a
988
+ controlPlaneTenantId: f,
989
+ requireOrganizationMatch: c,
990
+ defaultPermissions: s
978
991
  }
979
992
  },
980
- { tenants: w }
981
- ), { app: h } = Z({
982
- dataAdapter: e,
983
- ...l,
993
+ { tenants: b }
994
+ ), { app: v } = ne({
995
+ dataAdapter: m,
996
+ ...i,
984
997
  entityHooks: A,
985
998
  managementApiExtensions: [
986
999
  ...o,
987
- { path: "/tenants", router: v }
1000
+ { path: "/tenants", router: _ }
988
1001
  ]
989
1002
  });
990
- return h.use("/api/v2/*", ge(n)), f && h.use("/api/v2/*", me()), { app: h, controlPlaneTenantId: n };
1003
+ return v.use("/api/v2/*", ye(f)), g && v.use("/api/v2/*", we()), { app: v, controlPlaneTenantId: f };
991
1004
  }
992
- function Ie(t) {
993
- const e = q(t);
1005
+ function ze(t) {
1006
+ const e = j(t);
994
1007
  return {
995
1008
  name: "multi-tenancy",
996
1009
  // Apply multi-tenancy middleware for subdomain routing, database resolution, etc.
997
- middleware: B(t),
1010
+ middleware: V(t),
998
1011
  // Provide lifecycle hooks
999
1012
  hooks: e,
1000
1013
  // Mount tenant management routes
1001
1014
  routes: [
1002
1015
  {
1003
1016
  path: "/management",
1004
- handler: M(t, e)
1017
+ handler: D(t, e)
1005
1018
  }
1006
1019
  ],
1007
1020
  // Called when plugin is registered
@@ -1014,46 +1027,61 @@ function Ie(t) {
1014
1027
  }
1015
1028
  };
1016
1029
  }
1017
- function q(t) {
1018
- const e = t.accessControl ? ee(t.accessControl) : {}, n = t.databaseIsolation ? ne(t.databaseIsolation) : {}, s = re(t);
1030
+ function j(t) {
1031
+ const e = t.accessControl ? se(t.accessControl) : {}, n = t.databaseIsolation ? oe(t.databaseIsolation) : {}, r = ce(t);
1019
1032
  return {
1020
1033
  ...e,
1021
1034
  ...n,
1022
- tenants: s
1035
+ tenants: r
1023
1036
  };
1024
1037
  }
1025
- function he(t) {
1026
- const e = new V(), n = q(t);
1027
- return e.route("/tenants", M(t, n)), e;
1038
+ function _e(t) {
1039
+ const e = new Z(), n = j(t);
1040
+ return e.route("/tenants", D(t, n)), e;
1028
1041
  }
1029
- function Se(t) {
1042
+ function Re(t) {
1030
1043
  return {
1031
- hooks: q(t),
1032
- middleware: B(t),
1033
- app: he(t),
1034
- config: t
1044
+ hooks: j(t),
1045
+ middleware: V(t),
1046
+ app: _e(t),
1047
+ config: t,
1048
+ /**
1049
+ * Wraps data adapters with runtime fallback from the control plane.
1050
+ * Uses the controlPlaneTenantId from the multi-tenancy config.
1051
+ *
1052
+ * @param adapters - Base data adapters to wrap
1053
+ * @param additionalConfig - Additional config (controlPlaneClientId, etc.)
1054
+ * @returns Wrapped adapters with runtime fallback
1055
+ */
1056
+ wrapAdapters: (e, n) => {
1057
+ var r;
1058
+ return q(e, {
1059
+ controlPlaneTenantId: (r = t.accessControl) == null ? void 0 : r.controlPlaneTenantId,
1060
+ controlPlaneClientId: n == null ? void 0 : n.controlPlaneClientId
1061
+ });
1062
+ }
1035
1063
  };
1036
1064
  }
1037
1065
  export {
1038
- ee as createAccessControlHooks,
1039
- pe as createAccessControlMiddleware,
1040
- ge as createControlPlaneTenantMiddleware,
1041
- ne as createDatabaseHooks,
1042
- ye as createDatabaseMiddleware,
1043
- he as createMultiTenancy,
1044
- q as createMultiTenancyHooks,
1045
- B as createMultiTenancyMiddleware,
1046
- Ie as createMultiTenancyPlugin,
1047
- me as createProtectSyncedMiddleware,
1048
- re as createProvisioningHooks,
1049
- U as createRuntimeFallbackAdapter,
1050
- Ae as createSettingsInheritanceAdapter,
1051
- we as createSubdomainMiddleware,
1052
- ce as createSyncHooks,
1053
- M as createTenantsOpenAPIRouter,
1054
- Pe as initMultiTenant,
1055
- Se as setupMultiTenancy,
1056
- te as validateTenantAccess,
1057
- fe as withRuntimeFallback,
1058
- Ce as withSettingsInheritance
1066
+ se as createAccessControlHooks,
1067
+ he as createAccessControlMiddleware,
1068
+ ye as createControlPlaneTenantMiddleware,
1069
+ oe as createDatabaseHooks,
1070
+ Te as createDatabaseMiddleware,
1071
+ _e as createMultiTenancy,
1072
+ j as createMultiTenancyHooks,
1073
+ V as createMultiTenancyMiddleware,
1074
+ ze as createMultiTenancyPlugin,
1075
+ we as createProtectSyncedMiddleware,
1076
+ ce as createProvisioningHooks,
1077
+ Q as createRuntimeFallbackAdapter,
1078
+ Pe as createSettingsInheritanceAdapter,
1079
+ ve as createSubdomainMiddleware,
1080
+ fe as createSyncHooks,
1081
+ D as createTenantsOpenAPIRouter,
1082
+ $e as initMultiTenant,
1083
+ Re as setupMultiTenancy,
1084
+ ae as validateTenantAccess,
1085
+ q as withRuntimeFallback,
1086
+ Se as withSettingsInheritance
1059
1087
  };