@happyvertical/smrt-users 0.37.1 → 0.37.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,326 @@
1
+ import { SmrtClassOptions } from '@happyvertical/smrt-core';
2
+ import { AccessRequestCollection } from '../collections/AccessRequestCollection.js';
3
+ import { AccessRequest } from '../models/AccessRequest.js';
4
+ import { Membership } from '../models/Membership.js';
5
+ import { Tenant } from '../models/Tenant.js';
6
+ import { User } from '../models/User.js';
7
+ import { AccessRequestStatus, TenantStatus, UserStatus } from '../types/index.js';
8
+ /**
9
+ * Capabilities that gate the operator-facing methods of
10
+ * {@link AccessRequestService}.
11
+ */
12
+ export declare const ACCESS_REQUEST_CAPABILITIES: {
13
+ /** Read the access-request queue (`list` / `get`). */
14
+ readonly READ: "access-requests:read";
15
+ /** Decide requests (`approve` / `decline` / `cancel` / `graduate`). */
16
+ readonly MANAGE: "access-requests:manage";
17
+ };
18
+ /**
19
+ * One of the capability slugs in {@link ACCESS_REQUEST_CAPABILITIES}.
20
+ */
21
+ export type AccessRequestCapability = (typeof ACCESS_REQUEST_CAPABILITIES)[keyof typeof ACCESS_REQUEST_CAPABILITIES];
22
+ /**
23
+ * Context passed to an {@link AccessRequestAuthorizer} before an operator method
24
+ * runs.
25
+ */
26
+ export interface AccessRequestAuthorizationContext {
27
+ /** The capability the operation requires. */
28
+ capability: AccessRequestCapability;
29
+ /** The operator user id supplied to the method (`by`), if any. */
30
+ by?: string | null;
31
+ /** The target access-request id, when the operation targets a specific row. */
32
+ accessRequestId?: string;
33
+ }
34
+ /**
35
+ * Hook that authorizes an operator action. Throw (or reject) to deny — the
36
+ * thrown error propagates to the caller unchanged. Resolve/return to allow.
37
+ *
38
+ * Wire this to your permission system, e.g. resolve the operator's permissions
39
+ * and assert the required capability:
40
+ *
41
+ * ```typescript
42
+ * const service = await AccessRequestService.create({
43
+ * db,
44
+ * authorize: async ({ capability, by }) => {
45
+ * if (!by || !(await isPlatformOperator(by, capability))) {
46
+ * throw new Error(`Missing capability: ${capability}`);
47
+ * }
48
+ * },
49
+ * });
50
+ * ```
51
+ */
52
+ export type AccessRequestAuthorizer = (context: AccessRequestAuthorizationContext) => void | Promise<void>;
53
+ /**
54
+ * Lifecycle event types emitted by {@link AccessRequestService}.
55
+ */
56
+ export type AccessRequestEventType = 'access-request.created' | 'access-request.approved' | 'access-request.declined' | 'access-request.canceled' | 'access-request.graduated';
57
+ /**
58
+ * Payload delivered to an {@link AccessRequestEventHandler}.
59
+ */
60
+ export interface AccessRequestEvent {
61
+ /** Which lifecycle transition fired. */
62
+ type: AccessRequestEventType;
63
+ /** The access request after the transition. */
64
+ accessRequest: AccessRequest;
65
+ /** When the event was emitted. */
66
+ at: Date;
67
+ /** Operator user id responsible, for operator-driven transitions. */
68
+ by?: string | null;
69
+ /** Graduated user (only on `access-request.graduated`). */
70
+ user?: User;
71
+ /** Membership created/linked on graduation, when a tenant was attached. */
72
+ membership?: Membership;
73
+ /** Tenant created/linked on graduation, when a tenant was attached. */
74
+ tenant?: Tenant;
75
+ }
76
+ /**
77
+ * Event hook apps provide to react to access-request lifecycle changes.
78
+ * Delivery is best-effort: a throwing handler is logged and swallowed so it
79
+ * never rolls back an already-persisted transition. Do not rely on it for
80
+ * critical-path work that must share the request's transaction.
81
+ */
82
+ export type AccessRequestEventHandler = (event: AccessRequestEvent) => void | Promise<void>;
83
+ /**
84
+ * Options for {@link AccessRequestService}.
85
+ */
86
+ export interface AccessRequestServiceOptions extends SmrtClassOptions {
87
+ /** Optional capability gate for operator methods (see {@link AccessRequestAuthorizer}). */
88
+ authorize?: AccessRequestAuthorizer;
89
+ /** Optional lifecycle event hook (see {@link AccessRequestEventHandler}). */
90
+ onEvent?: AccessRequestEventHandler;
91
+ }
92
+ /**
93
+ * Input for {@link AccessRequestService.createAccessRequest}. Only `email` is
94
+ * required.
95
+ */
96
+ export interface CreateAccessRequestInput {
97
+ /** Requester email (validated + normalized to lowercase). */
98
+ email: string;
99
+ /** Requester display name. */
100
+ name?: string | null;
101
+ /** Where the request came from, e.g. `www`, `sdk`. */
102
+ source?: string;
103
+ /** Free-form metadata (intended use, company, message, referrer, …). */
104
+ context?: Record<string, unknown>;
105
+ /** Optional requested org/tenant hint (advisory). */
106
+ tenantHint?: Record<string, unknown> | null;
107
+ /** Optional initial note. */
108
+ note?: string | null;
109
+ }
110
+ /**
111
+ * Filter for {@link AccessRequestService.listAccessRequests}.
112
+ */
113
+ export interface ListAccessRequestsFilter {
114
+ /** Restrict to one status or any of several. */
115
+ status?: AccessRequestStatus | AccessRequestStatus[];
116
+ /** Restrict to a single (normalized) email. */
117
+ email?: string;
118
+ /** Restrict to a single source. */
119
+ source?: string;
120
+ /** Operator user id, forwarded to the authorizer as `by`. */
121
+ by?: string | null;
122
+ /** Max rows to return. */
123
+ limit?: number;
124
+ /** Rows to skip. */
125
+ offset?: number;
126
+ /** Order-by clause (defaults to `created_at DESC`). */
127
+ orderBy?: string;
128
+ }
129
+ /**
130
+ * Options shared by the operator decision methods.
131
+ */
132
+ export interface DecideAccessRequestOptions {
133
+ /** Operator user id recorded as `decidedBy` and forwarded to the authorizer. */
134
+ by?: string | null;
135
+ }
136
+ /**
137
+ * Options for {@link AccessRequestService.approveAccessRequest}.
138
+ */
139
+ export interface ApproveAccessRequestOptions extends DecideAccessRequestOptions {
140
+ /** Operator note stored on the request. */
141
+ note?: string | null;
142
+ }
143
+ /**
144
+ * Options for {@link AccessRequestService.declineAccessRequest}.
145
+ */
146
+ export interface DeclineAccessRequestOptions extends DecideAccessRequestOptions {
147
+ /** Decision reason stored as the request's note. */
148
+ reason?: string | null;
149
+ }
150
+ /**
151
+ * Options for {@link AccessRequestService.cancelAccessRequest}.
152
+ */
153
+ export interface CancelAccessRequestOptions extends DecideAccessRequestOptions {
154
+ /** Cancellation reason stored as the request's note. */
155
+ reason?: string | null;
156
+ }
157
+ /**
158
+ * Graduate into a **new** tenant, enrolling the requester (owner by default).
159
+ */
160
+ export interface GraduateNewTenantOption {
161
+ /** New tenant attributes — `name` is required. */
162
+ create: {
163
+ name: string;
164
+ slug?: string;
165
+ description?: string;
166
+ status?: TenantStatus;
167
+ };
168
+ /** Role slug for the requester's membership (default `owner`). */
169
+ role?: string;
170
+ }
171
+ /**
172
+ * Graduate into an **existing** tenant, enrolling the requester.
173
+ */
174
+ export interface GraduateExistingTenantOption {
175
+ /** Target tenant id. */
176
+ tenantId: string;
177
+ /** Role slug for the requester's membership (default `member`). */
178
+ role?: string;
179
+ }
180
+ /**
181
+ * Tenant handling at graduation: create a new tenant, attach to an existing
182
+ * one, or `'none'` (user only, no membership).
183
+ */
184
+ export type GraduateTenantOption = GraduateNewTenantOption | GraduateExistingTenantOption | 'none';
185
+ /**
186
+ * Options for {@link AccessRequestService.graduateAccessRequest}.
187
+ */
188
+ export interface GraduateAccessRequestOptions extends DecideAccessRequestOptions {
189
+ /** Tenant handling (default `'none'`). */
190
+ tenant?: GraduateTenantOption;
191
+ /** Status applied to the user produced/linked by graduation (default `ACTIVE`). */
192
+ activate?: UserStatus;
193
+ /**
194
+ * Convenience: allow graduating directly from `REQUESTED` (skipping the
195
+ * `APPROVED` step). Defaults to `false`.
196
+ */
197
+ allowFromRequested?: boolean;
198
+ /** Operator note stored on the request. */
199
+ note?: string | null;
200
+ }
201
+ /**
202
+ * Result of {@link AccessRequestService.graduateAccessRequest}.
203
+ */
204
+ export interface GraduateAccessRequestResult {
205
+ /** The graduated (created or linked) user. */
206
+ user: User;
207
+ /** The membership, when a tenant was attached. */
208
+ membership?: Membership;
209
+ /** The tenant, when one was created or attached. */
210
+ tenant?: Tenant;
211
+ /** The access request, now `GRADUATED`. */
212
+ accessRequest: AccessRequest;
213
+ /** Whether a brand-new user was created (`false` when an existing one was linked). */
214
+ created: boolean;
215
+ }
216
+ /**
217
+ * Error codes raised by {@link AccessRequestError}.
218
+ */
219
+ export type AccessRequestErrorCode = 'INVALID_EMAIL' | 'NOT_FOUND' | 'INVALID_TRANSITION' | 'TENANT_NOT_FOUND' | 'ROLE_NOT_FOUND';
220
+ /**
221
+ * Error thrown for access-request domain failures the caller is expected to
222
+ * surface (invalid email, unknown id, illegal state transition, …). Authorizer
223
+ * denials are not wrapped — those propagate from the supplied authorizer
224
+ * unchanged.
225
+ */
226
+ export declare class AccessRequestError extends Error {
227
+ readonly code: AccessRequestErrorCode;
228
+ constructor(message: string, code: AccessRequestErrorCode);
229
+ }
230
+ /**
231
+ * High-level orchestration for the access-request lifecycle and graduation.
232
+ */
233
+ export declare class AccessRequestService {
234
+ #private;
235
+ constructor(options: AccessRequestServiceOptions);
236
+ /**
237
+ * Initialize the backing collections (creates/verifies their tables).
238
+ */
239
+ initialize(): Promise<void>;
240
+ /**
241
+ * Static factory — construct and initialize in one call.
242
+ */
243
+ static create(options: AccessRequestServiceOptions): Promise<AccessRequestService>;
244
+ /**
245
+ * The underlying collection, for advanced read scenarios. Prefer the service
246
+ * methods, which apply normalization, the state machine, capability gating,
247
+ * and events.
248
+ */
249
+ get collection(): AccessRequestCollection;
250
+ /**
251
+ * Create an access request. **Public-safe**: no capability check — meant to be
252
+ * callable unauthenticated by apps (which add their own rate-limiting).
253
+ *
254
+ * Validates and normalizes the email, then de-duplicates: if an open
255
+ * (`REQUESTED`) request already exists for the email, this merges any newly
256
+ * supplied context/name/source/hint into it and returns it instead of
257
+ * creating a duplicate (no second `created` event).
258
+ *
259
+ * @remarks
260
+ * De-duplication is **best-effort, not atomic**: it is a read-then-write
261
+ * (`findOpenByEmail` → `create`) with no DB-level partial-unique constraint
262
+ * (the table is append-style, keyed on `id`, because the same email may
263
+ * accumulate many requests over its lifetime). Two requests for the same
264
+ * email racing concurrently can therefore both create an open row. This is by
265
+ * design — the spec makes dedup configurable and pushes abuse control to the
266
+ * app (rate-limiting on the public endpoint). Operators triaging two open rows
267
+ * for one email is benign; apps needing a hard single-open-request guarantee
268
+ * should add a partial unique index (`UNIQUE(email) WHERE status='requested'`)
269
+ * in their migration.
270
+ *
271
+ * @throws {@link AccessRequestError} (`INVALID_EMAIL`) when the email is invalid.
272
+ */
273
+ createAccessRequest(input: CreateAccessRequestInput): Promise<AccessRequest>;
274
+ /**
275
+ * List access requests (operator-facing). Requires the `access-requests:read`
276
+ * capability when an authorizer is configured.
277
+ */
278
+ listAccessRequests(filter?: ListAccessRequestsFilter): Promise<AccessRequest[]>;
279
+ /**
280
+ * Get a single access request by id (operator-facing). Requires the
281
+ * `access-requests:read` capability when an authorizer is configured.
282
+ */
283
+ getAccessRequest(id: string, options?: {
284
+ by?: string | null;
285
+ }): Promise<AccessRequest | null>;
286
+ /**
287
+ * Approve a request: `REQUESTED → APPROVED`. Idempotent (re-approving an
288
+ * already-`APPROVED` request is a no-op returning it). Requires
289
+ * `access-requests:manage`.
290
+ *
291
+ * @throws {@link AccessRequestError} (`INVALID_TRANSITION`) from a terminal state.
292
+ */
293
+ approveAccessRequest(id: string, options?: ApproveAccessRequestOptions): Promise<AccessRequest>;
294
+ /**
295
+ * Decline a request: `REQUESTED | APPROVED → DECLINED`. Idempotent. Requires
296
+ * `access-requests:manage`.
297
+ *
298
+ * @throws {@link AccessRequestError} (`INVALID_TRANSITION`) from a terminal state.
299
+ */
300
+ declineAccessRequest(id: string, options?: DeclineAccessRequestOptions): Promise<AccessRequest>;
301
+ /**
302
+ * Cancel a request: `REQUESTED | APPROVED → CANCELED`. Idempotent. Requires
303
+ * `access-requests:manage`.
304
+ *
305
+ * @throws {@link AccessRequestError} (`INVALID_TRANSITION`) from a terminal state.
306
+ */
307
+ cancelAccessRequest(id: string, options?: CancelAccessRequestOptions): Promise<AccessRequest>;
308
+ /**
309
+ * Graduate an approved request into a `User`, optionally attaching a tenant.
310
+ *
311
+ * Valid from `APPROVED` (or from `REQUESTED` when
312
+ * {@link GraduateAccessRequestOptions.allowFromRequested} is set). Creates a
313
+ * user when none exists for the email, or **links** the existing one
314
+ * otherwise (reusing {@link UserCollection}). Idempotent: a second call on an
315
+ * already-`GRADUATED` request returns the same user (and an existing
316
+ * membership for the requested tenant, if any) without re-creating anything.
317
+ *
318
+ * Requires `access-requests:manage`.
319
+ *
320
+ * @throws {@link AccessRequestError} — `NOT_FOUND` (unknown id),
321
+ * `INVALID_TRANSITION` (terminal/declined/canceled or `REQUESTED` without
322
+ * `allowFromRequested`), `TENANT_NOT_FOUND`, or `ROLE_NOT_FOUND`.
323
+ */
324
+ graduateAccessRequest(id: string, options?: GraduateAccessRequestOptions): Promise<GraduateAccessRequestResult>;
325
+ }
326
+ //# sourceMappingURL=AccessRequestService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccessRequestService.d.ts","sourceRoot":"","sources":["../../src/services/AccessRequestService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AAKpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EACL,mBAAmB,EAGnB,KAAK,YAAY,EACjB,UAAU,EACX,MAAM,mBAAmB,CAAC;AAI3B;;;GAGG;AACH,eAAO,MAAM,2BAA2B;IACtC,sDAAsD;;IAEtD,uEAAuE;;CAE/D,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,uBAAuB,GACjC,CAAC,OAAO,2BAA2B,CAAC,CAAC,MAAM,OAAO,2BAA2B,CAAC,CAAC;AAEjF;;;GAGG;AACH,MAAM,WAAW,iCAAiC;IAChD,6CAA6C;IAC7C,UAAU,EAAE,uBAAuB,CAAC;IACpC,kEAAkE;IAClE,EAAE,CAAC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AAsB;CAK1D;AAiBD;;GAEG;AACH,qBAAa,oBAAoB;;gBAYnB,OAAO,EAAE,2BAA2B;IAMhD;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAWjC;;OAEG;WACU,MAAM,CACjB,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,oBAAoB,CAAC;IAMhC;;;;OAIG;IACH,IAAI,UAAU,IAAI,uBAAuB,CAExC;IAID;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACG,mBAAmB,CACvB,KAAK,EAAE,wBAAwB,GAC9B,OAAO,CAAC,aAAa,CAAC;IA6DzB;;;OAGG;IACG,kBAAkB,CACtB,MAAM,GAAE,wBAA6B,GACpC,OAAO,CAAC,aAAa,EAAE,CAAC;IAkB3B;;;OAGG;IACG,gBAAgB,CACpB,EAAE,EAAE,MAAM,EACV,OAAO,GAAE;QAAE,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAO,GACnC,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAUhC;;;;;;OAMG;IACG,oBAAoB,CACxB,EAAE,EAAE,MAAM,EACV,OAAO,GAAE,2BAAgC,GACxC,OAAO,CAAC,aAAa,CAAC;IAyBzB;;;;;OAKG;IACG,oBAAoB,CACxB,EAAE,EAAE,MAAM,EACV,OAAO,GAAE,2BAAgC,GACxC,OAAO,CAAC,aAAa,CAAC;IAyBzB;;;;;OAKG;IACG,mBAAmB,CACvB,EAAE,EAAE,MAAM,EACV,OAAO,GAAE,0BAA+B,GACvC,OAAO,CAAC,aAAa,CAAC;IA2BzB;;;;;;;;;;;;;;;OAeG;IACG,qBAAqB,CACzB,EAAE,EAAE,MAAM,EACV,OAAO,GAAE,4BAAiC,GACzC,OAAO,CAAC,2BAA2B,CAAC;CAuTxC"}
@@ -2,6 +2,7 @@
2
2
  * Service exports for smrt-users
3
3
  * @packageDocumentation
4
4
  */
5
+ export { ACCESS_REQUEST_CAPABILITIES, type AccessRequestAuthorizationContext, type AccessRequestAuthorizer, type AccessRequestCapability, AccessRequestError, type AccessRequestErrorCode, type AccessRequestEvent, type AccessRequestEventHandler, type AccessRequestEventType, AccessRequestService, type AccessRequestServiceOptions, type ApproveAccessRequestOptions, type CancelAccessRequestOptions, type CreateAccessRequestInput, type DeclineAccessRequestOptions, type GraduateAccessRequestOptions, type GraduateAccessRequestResult, type GraduateExistingTenantOption, type GraduateNewTenantOption, type GraduateTenantOption, type ListAccessRequestsFilter, } from './AccessRequestService.js';
5
6
  export { MagicLinkError, type MagicLinkResult, MagicLinkService, type MagicLinkServiceOptions, type MagicLinkVerifyResult, } from './MagicLinkService.js';
6
7
  export { type CreateAuthorizationUrlOptions, decodeOidcTransaction, encodeOidcTransaction, getUsersOidcConfig, type OidcCallbackResult, OidcLoginError, type OidcLoginResult, OidcLoginService, type OidcLoginServiceOptions, type OidcProviderConfig, type OidcProviderKind, type OidcProviderMetadata, type OidcProviderResolution, type OidcProviderResolutionOptions, type OidcTokenEndpointAuthMethod, type OidcTokenSet, type OidcTransaction, type ResolvedOidcProviderConfig, resolveOidcProviderConfig, type UsersOidcConfig, } from './OidcLoginService.js';
7
8
  export { type PermissionCatalog, PermissionCatalogService, type PermissionCatalogSource, type PermissionCatalogSyncResult, type PermissionDefinition, type PostgresPermissionAction, type PostgresPermissionBinding, registerPermissionDefinitions, syncPermissionCatalog, type UsersConfig, } from './PermissionCatalogService.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,cAAc,EACd,KAAK,eAAe,EACpB,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,GAC3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,KAAK,6BAA6B,EAClC,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,KAAK,kBAAkB,EACvB,cAAc,EACd,KAAK,eAAe,EACpB,gBAAgB,EA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AK,oBAAoB,EACzB,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAC9B,6BAA6B,EAC7B,qBAAqB,EACrB,KAAK,WAAW,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,kBAAkB,EAClB,KAAK,iCAAiC,GACvC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,+BAA+B,EAC/B,KAAK,mCAAmC,EACxC,6BAA6B,EAC7B,KAAK,kCAAkC,EACvC,KAAK,8BAA8B,GACpC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,kCAAkC,EAClC,wBAAwB,EACxB,KAAK,+BAA+B,EACpC,KAAK,+BAA+B,EACpC,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,KAAK,cAAc,EACnB,cAAc,EACd,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,KAAK,kBAAkB,EACvB,aAAa,EACb,KAAK,yBAAyB,GAC/B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,+CAA+C,EAC/C,qCAAqC,EACrC,sCAAsC,EACtC,oCAAoC,EACpC,+BAA+B,EAC/B,iBAAiB,EACjB,0BAA0B,EAC1B,mBAAmB,EACnB,KAAK,0BAA0B,GAChC,MAAM,0BAA0B,CAAC"}
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-06-30T04:09:12.864Z",
3
+ "generatedAt": "2026-07-01T02:36:07.189Z",
4
4
  "packageName": "@happyvertical/smrt-users",
5
- "packageVersion": "0.37.1",
5
+ "packageVersion": "0.37.2",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "b0ced21be693bf01f11fb206f171ebb40444d75aa98c4cd39eacefcd6c79e0c4",
10
- "packageJson": "cc8759f2964ac8f51688704e6adf66c51e876581b27b0ea4516c2115d816d1c2",
11
- "agents": "2684404a1735fd4993d4383f2dfed5f9c0f4de68f0cbfcd996f7e94eb50ac9c8"
9
+ "manifest": "fae4644a4f6304f9e45cd231941f0e5f197a44ec9bdf6905a3c528a589fae546",
10
+ "packageJson": "bd0c5070da8950403f025840c2d39f35a05789bfea1c109a04ed1cdeb50d9760",
11
+ "agents": "7244609f8590febc0f58df6f139e22317a1489541071ac249a5c07557b95dee3"
12
12
  },
13
13
  "exports": [
14
14
  ".",
@@ -55,6 +55,28 @@
55
55
  "tags": [],
56
56
  "risks": [],
57
57
  "objects": [
58
+ {
59
+ "name": "AccessRequestCollection",
60
+ "qualifiedName": "@happyvertical/smrt-users:AccessRequestCollection",
61
+ "collection": "accessrequests",
62
+ "tableName": "access_requests",
63
+ "packageName": "@happyvertical/smrt-users",
64
+ "extends": "SmrtCollection",
65
+ "fields": [],
66
+ "relationships": [],
67
+ "methods": [
68
+ "findByEmail",
69
+ "findByStatus",
70
+ "findOpen",
71
+ "findOpenByEmail"
72
+ ],
73
+ "surfaces": [],
74
+ "relationshipFeatures": [
75
+ "uuidColumns"
76
+ ],
77
+ "tags": [],
78
+ "risks": []
79
+ },
58
80
  {
59
81
  "name": "UsersCliAuthRequestCollection",
60
82
  "qualifiedName": "@happyvertical/smrt-users:UsersCliAuthRequestCollection",
@@ -414,6 +436,98 @@
414
436
  "tags": [],
415
437
  "risks": []
416
438
  },
439
+ {
440
+ "name": "AccessRequest",
441
+ "qualifiedName": "@happyvertical/smrt-users:AccessRequest",
442
+ "collection": "accessrequests",
443
+ "tableName": "access_requests",
444
+ "packageName": "@happyvertical/smrt-users",
445
+ "extends": "SmrtObject",
446
+ "fields": [
447
+ {
448
+ "name": "email",
449
+ "type": "text",
450
+ "required": true,
451
+ "columnType": "TEXT"
452
+ },
453
+ {
454
+ "name": "name",
455
+ "type": "text",
456
+ "required": false,
457
+ "columnType": "TEXT"
458
+ },
459
+ {
460
+ "name": "status",
461
+ "type": "text",
462
+ "required": false,
463
+ "columnType": "TEXT"
464
+ },
465
+ {
466
+ "name": "source",
467
+ "type": "text",
468
+ "required": false,
469
+ "columnType": "TEXT"
470
+ },
471
+ {
472
+ "name": "requestContext",
473
+ "type": "text",
474
+ "required": false,
475
+ "columnType": "TEXT"
476
+ },
477
+ {
478
+ "name": "note",
479
+ "type": "text",
480
+ "required": false,
481
+ "columnType": "TEXT"
482
+ },
483
+ {
484
+ "name": "requestedAt",
485
+ "type": "datetime",
486
+ "required": false,
487
+ "columnType": "TIMESTAMP"
488
+ },
489
+ {
490
+ "name": "decidedAt",
491
+ "type": "datetime",
492
+ "required": false,
493
+ "columnType": "TIMESTAMP"
494
+ },
495
+ {
496
+ "name": "decidedBy",
497
+ "type": "text",
498
+ "required": false,
499
+ "columnType": "TEXT"
500
+ },
501
+ {
502
+ "name": "resultingUserId",
503
+ "type": "text",
504
+ "required": false,
505
+ "columnType": "TEXT"
506
+ },
507
+ {
508
+ "name": "tenantHint",
509
+ "type": "text",
510
+ "required": false,
511
+ "columnType": "TEXT"
512
+ }
513
+ ],
514
+ "relationships": [],
515
+ "methods": [
516
+ "getRequestContext",
517
+ "getTenantHint",
518
+ "isApproved",
519
+ "isOpen",
520
+ "isTerminal",
521
+ "setRequestContext",
522
+ "setTenantHint"
523
+ ],
524
+ "surfaces": [],
525
+ "relationshipFeatures": [
526
+ "uuidColumns"
527
+ ],
528
+ "tags": [],
529
+ "risks": []
530
+ },
417
531
  {
418
532
  "name": "UsersCliAuthRequest",
419
533
  "qualifiedName": "@happyvertical/smrt-users:UsersCliAuthRequest",
@@ -2739,7 +2853,7 @@
2739
2853
  "junctionCollections": 0,
2740
2854
  "hierarchicalObjects": 0,
2741
2855
  "polymorphicAssociations": 0,
2742
- "uuidColumns": 47
2856
+ "uuidColumns": 49
2743
2857
  },
2744
- "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (13)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is plain string (not FK) to smrt-profiles. Email auto-lowercased. |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
2858
+ "agentDoc": "# @happyvertical/smrt-users\n\nMulti-tenant user management with RBAC, hierarchical tenants, session handling, and SvelteKit integration.\n\n## Models (14)\n\n| Model | Key Pattern |\n|-------|-------------|\n| User | Auth identity. `profileId` is plain string (not FK) to smrt-profiles. Email auto-lowercased. |\n| AccessRequest | \"Request access / waitlist\" record captured before a `User` exists. CLOSED generated surface (`api`/`mcp`/`cli` = `[]`) — all access via `AccessRequestService`. Email normalized + indexed; JSON `requestContext` (NOT `context` — reserved for slug scoping). |\n| Tenant | **STI** + hierarchical parent-child. `hierarchyPath` (materialized path), `hierarchyLevel`. Max depth 10. |\n| Session | Server-side. Secure UUID. TTL in **seconds** (not ms). Status auto-updates to EXPIRED on access. |\n| MagicLinkToken | Single-use email login token. Backed by `MagicLinkService`. |\n| Role | `tenantId = null` → system role (available to all tenants). `isSystem: true` blocks deletion. |\n| Permission | Slug format: `resource.action`. Parsed by PermissionResolver. |\n| Membership | User + Tenant + Role junction. UNIQUE(userId, tenantId). |\n| Group | Team within a tenant. Multiple roles via GroupRole. |\n| GroupMember, GroupRole, RolePermission | Join tables. |\n| MembershipOverride | Per-user permission grant/deny. **DENY always wins.** |\n| TenantPermissionOverride | Tenant-level cascade overrides. Effect: INHERIT/GRANT/DENY. |\n\n## Permission Resolution — Precedence (broad → specific, most-specific wins)\n\n`PermissionResolver.resolvePermissions` builds the effective set in this order;\neach later layer overrides earlier ones:\n\n1. **Tenant-inherited** — walk ancestors, apply each `TenantPermissionOverride`\n down the cascade (GRANT adds, DENY removes within the hierarchy)\n2. **Membership role** — base permissions from the user's role in the tenant\n3. **Group roles** — permissions from all groups the user belongs to **in that tenant**\n4. **Tenant-level DENY** *(removes; overrides role/group grants, tenant-wide)* — a\n `TenantPermissionOverride` with effect `DENY` is a HARD, tenant-wide block: it\n subtracts the DENY'd slug even if a role or group granted it (steps 2–3). It\n sits just **above** the per-user membership overrides and **below** role/group.\n5. **Membership GRANT override** *(re-adds; most specific)* — a per-user GRANT can\n re-add a slug a tenant DENY'd in step 4, because it is more specific.\n6. **Membership DENY override** *(absolute; always wins)* — a per-user DENY removes\n the slug last and is never overridden.\n\nSo a permission a role grants but the tenant DENYs is **removed**, unless that\nexact user also has a membership-GRANT override for it. A membership-DENY always\nwins. Tenant-DENY of an inherited/cascade grant still blocks it (unchanged).\nThe hard block reflects the tenant cascade's **net** resolution, not an\nunconditional union of every DENY in the chain — so a more-specific tenant GRANT\n(e.g. a child sub-tenant re-granting a permission its parent DENYs) still wins.\n\n**Critical**: `getGroupIdsForTenant(userId, tenantId)` (joins with groups table to scope by tenant). Never use `getGroupIds()` — it's cross-tenant.\n\n## Hierarchical Tenants\n\n- `TenantCollection.createChild()` auto-calculates hierarchy fields, enforces depth limit\n- `moveToParent()` updates tenant + ALL descendants' paths/levels\n- `cascadePermissions` (parent pushes down) + `inheritPermissions` (child accepts) — both must be true\n- `getTree(rootId?)` returns nested structure for UI\n\n## SvelteKit Integration\n\n```typescript\n// hooks.server.ts\nexport const handle = createSessionHandler({ db, ttl: 604800, skipPaths: ['/api/public'] });\n// Populates event.locals: { user, membership, permissions: string[], tenantId, sessionId }\n\n// +page.server.ts\nawait createSessionCookie(event, userId, tenantId, { db });\nawait destroySessionCookie(event, { db });\nawait switchSessionTenant(event, tenantId, { db });\n```\n\n## Security (S5 #1400)\n\n- **Generated REST/MCP surface is READ-ONLY for every RBAC/identity model.**\n User, Tenant, Group, Membership, MembershipOverride, Role, Permission,\n RolePermission, GroupRole, GroupMember, and TenantPermissionOverride generate\n `list`/`get` only — `create`/`update`/`delete` are intentionally NOT\n generated. The merged `requireRouteAuth` gate (#1540) enforces *authentication*,\n not *authorization*, and these models are not `@TenantScoped`, so an\n auto-generated mutating route would let any authenticated user self-grant a\n role/permission, flip a tenant's cascade flags, or change another user's auth\n identity. Mutate them through the permission-gated services (`TenantService`,\n collection helpers) or consumer-owned, permission-checked handlers. A\n structural regression test (`security-audit-1400.test.ts`) enumerates the\n registry to assert no authority model exposes a mutating op. (`cli` stays\n enabled — local-operator surface, outside the network/agent threat model.)\n- **`switchTenant` is fail-closed AND rotates the session id.**\n `SessionService.switchTenant` / `switchSessionTenant` verify the session's user\n has an ACTIVE membership in the target tenant before any write (the tenant id\n is the isolation key for every `@TenantScoped` query). A non-member/unknown-\n session switch returns `{ switched: false, sessionId: null, ... }` and mutates\n nothing. On a successful switch into a NON-null tenant the session id is\n ROTATED: a fresh `Session` (new secure id, fresh TTL, same user, new tenant,\n device context carried over) is minted and the old session is REVOKED — so a\n captured pre-switch id immediately stops validating, shrinking the blast radius\n of a leaked id across a tenant boundary. `switchTenant` returns a\n `SwitchTenantResult` (`{ switched, sessionId, session, rotated }`); callers MUST\n persist the returned `sessionId`. `switchSessionTenant` does this for you by\n re-setting the session cookie (preserving httpOnly/secure/sameSite) to the new\n id. A `null` clear stays in place (no rotation, no cookie change). The\n low-level `SessionCollection.setSessionTenant` is the UNGUARDED primitive (used\n for the null-clear path) — never call it with an untrusted tenant id.\n- **OIDC `email_verified` is enforced.** `UserCollection.getOrCreateFromOidc`\n refuses to provision a user when the IdP explicitly returns\n `email_verified: false` (opt out with `{ allowUnverifiedEmail: true }`). An\n absent claim makes no assertion and is not enforced.\n\n## Gotchas\n\n- **seedSystemRoles() required**: call `RoleCollection.seedSystemRoles()` at app init (creates owner/admin/member/viewer)\n- **PermissionResolver casts `as any`**: collections have protected constructors — known framework limitation\n- **Session TTL in seconds**: `DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60` (not milliseconds)\n- **Users are cross-tenant**: one user, many tenants via Membership. Email globally unique.\n- **Batch permission queries**: resolver fetches all permission IDs in one query, then maps to slugs (avoids N+1)\n"
2745
2859
  }
package/dist/sveltekit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { O as OidcLoginError, h as DEFAULT_SESSION_TTL, Z as withSessionPermissionContext, H as TerminalAuthRateLimitError, F as TerminalAuthError, Y as resolveOidcProviderConfig, u as OidcLoginService, N as encodeOidcTransaction, X as getUsersOidcConfig, L as decodeOidcTransaction, I as TerminalAuthService, z as SessionService } from "./chunks/TerminalAuthService-bY1oWeAh.js";
1
+ import { O as OidcLoginError, j as DEFAULT_SESSION_TTL, Z as withSessionPermissionContext, I as TerminalAuthRateLimitError, H as TerminalAuthError, Y as resolveOidcProviderConfig, v as OidcLoginService, N as encodeOidcTransaction, X as getUsersOidcConfig, L as decodeOidcTransaction, J as TerminalAuthService, A as SessionService } from "./chunks/TerminalAuthService-DcgimQYo.js";
2
2
  import { createLogger } from "@happyvertical/logger";
3
3
  import { ObjectRegistry } from "@happyvertical/smrt-core";
4
4
  import { classnameToTablename } from "@happyvertical/smrt-core/utils";
@@ -2,7 +2,7 @@
2
2
  * Type definitions for smrt-users
3
3
  * @packageDocumentation
4
4
  */
5
- export { MembershipStatus, OverrideEffect, SessionStatus, TenantPermissionEffect, TenantStatus, UserStatus, } from '@happyvertical/smrt-types';
5
+ export { AccessRequestStatus, MembershipStatus, OverrideEffect, SessionStatus, TenantPermissionEffect, TenantStatus, UserStatus, } from '@happyvertical/smrt-types';
6
6
  /**
7
7
  * Default system role slugs
8
8
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,sBAAsB,EACtB,YAAY,EACZ,UAAU,GACX,MAAM,2BAA2B,CAAC;AAInC;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;;;CAKrB,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;EAqBhB,CAAC;AAEX,MAAM,MAAM,eAAe,GACzB,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,OAAO,kBAAkB,CAAC,CAAC;AAI/D;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,kBAAkB;IAClB,IAAI,EAAE,gBAAgB,CAAC;IAEvB,+CAA+C;IAC/C,UAAU,EAAE,MAAM,CAAC;IAEnB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,YAInC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,sBAAsB,EACtB,YAAY,EACZ,UAAU,GACX,MAAM,2BAA2B,CAAC;AAInC;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;;;CAKrB,CAAC;AAEX;;GAEG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;EAqBhB,CAAC;AAEX,MAAM,MAAM,eAAe,GACzB,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,OAAO,kBAAkB,CAAC,CAAC;AAI/D;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;AAEpE;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,kBAAkB;IAClB,IAAI,EAAE,gBAAgB,CAAC;IAEvB,+CAA+C;IAC/C,UAAU,EAAE,MAAM,CAAC;IAEnB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,YAInC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-users",
3
- "version": "0.37.1",
3
+ "version": "0.37.2",
4
4
  "description": "Multi-tenant user management for the SMRT framework - users, tenants, roles, permissions, groups",
5
5
  "type": "module",
6
6
  "smrtRawPrimitives": "strict",
@@ -43,12 +43,12 @@
43
43
  "dependencies": {
44
44
  "@happyvertical/logger": "^0.74.10",
45
45
  "jose": "^6.1.3",
46
- "@happyvertical/smrt-config": "0.37.1",
47
- "@happyvertical/smrt-profiles": "0.37.1",
48
- "@happyvertical/smrt-tenancy": "0.37.1",
49
- "@happyvertical/smrt-core": "0.37.1",
50
- "@happyvertical/smrt-ui": "0.37.1",
51
- "@happyvertical/smrt-types": "0.37.1"
46
+ "@happyvertical/smrt-profiles": "0.37.2",
47
+ "@happyvertical/smrt-config": "0.37.2",
48
+ "@happyvertical/smrt-core": "0.37.2",
49
+ "@happyvertical/smrt-tenancy": "0.37.2",
50
+ "@happyvertical/smrt-types": "0.37.2",
51
+ "@happyvertical/smrt-ui": "0.37.2"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@happyvertical/sql": "^0.74.10",
@@ -61,7 +61,7 @@
61
61
  "typescript": "^5.9.3",
62
62
  "vite": "^7.3.6",
63
63
  "vitest": "^4.0.17",
64
- "@happyvertical/smrt-vitest": "0.37.1"
64
+ "@happyvertical/smrt-vitest": "0.37.2"
65
65
  },
66
66
  "keywords": [
67
67
  "smrt",