@manablox/auth 0.2.0 → 0.3.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.
@@ -0,0 +1,305 @@
1
+ import { Database, MembershipRow, Repositories, SpaceRow } from "@manablox/db";
2
+ import { ALL_PERMISSIONS, AuthConfig, BUILT_IN_ROLES, BuiltInRole, CONTENT_ACTIONS, ContentAction, ContentPermission, ContentPermission as ContentPermission$1, Grant, Manablox, PERMISSION_GROUPS, Permission, Permission as Permission$1, PermissionGroup, SpaceRole, SpaceRole as SpaceRole$1, grantsCover, intersectGrants, isBuiltInRole, normaliseGrants, parseGrant, permissionsFor, typesCoveredBy } from "@manablox/core";
3
+ //#region src/rbac.d.ts
4
+ export interface Principal {
5
+ userId: string;
6
+ email: string;
7
+ /** Instance-wide role; `superadmin` short-circuits every space check. */
8
+ role: string;
9
+ /** Space id → the name of the role held there. */
10
+ spaces: Record<string, SpaceRole$1>;
11
+ /**
12
+ * Space id → the grants that role carries, resolved when the principal is. Absent for
13
+ * a space whose role is built in: those are answered from the table above.
14
+ */
15
+ permissions?: Record<string, readonly string[]>;
16
+ /** True when the request authenticated with an API key rather than a session. */
17
+ viaApiKey?: boolean;
18
+ /**
19
+ * Spaces this principal is confined to, or `null`/absent for no confinement. Set by an
20
+ * API key that was issued with a space restriction: it narrows the key below its
21
+ * owner's own access and, unlike a role, it also binds a superadmin.
22
+ */
23
+ allowedSpaceIds?: string[] | null;
24
+ /**
25
+ * Grants this principal is confined to, or `null`/absent for no confinement. Set by an
26
+ * API key issued with a permission restriction: like `allowedSpaceIds` it only ever
27
+ * narrows the owner's own access, and it binds a superadmin too.
28
+ */
29
+ allowedGrants?: readonly string[] | null;
30
+ }
31
+ /** The grants a principal's role gives in a space, whatever kind of role it is. */
32
+ export declare function grantsIn(principal: Principal, spaceId: string): readonly string[];
33
+ /**
34
+ * What a principal can actually do in a space: the role's grants (everything, for a
35
+ * superadmin) narrowed by an API key's restriction, if the request came through one.
36
+ */
37
+ export declare function effectiveGrants(principal: Principal, spaceId: string): readonly string[];
38
+ export declare function can(principal: Principal | null, spaceId: string | null, permission: Permission$1, typeId?: string | null): boolean;
39
+ export declare function assertCan(principal: Principal | null, spaceId: string | null, permission: Permission$1, typeId?: string | null): void;
40
+ /**
41
+ * The content types a principal may perform an action on in a space, or `null` for
42
+ * every type — what a listing narrows its filter to.
43
+ */
44
+ export declare function allowedTypeIds(principal: Principal | null, spaceId: string, permission: ContentPermission$1): string[] | null;
45
+ /** Roles used by field-level `readRoles`/`writeRoles` checks. */
46
+ export declare function actorRoles(principal: Principal | null, spaceId: string | null): string[];
47
+ //#endregion
48
+ //#region src/api-key.d.ts
49
+ export interface IssuedApiKey {
50
+ id: string;
51
+ name: string;
52
+ /** The full secret, shown once at creation and never recoverable afterwards. */
53
+ key: string;
54
+ prefix: string;
55
+ }
56
+ export interface IssueApiKeyOptions {
57
+ expiresAt?: Date | undefined;
58
+ /** Spaces the key may act in. `null`/omitted issues an unrestricted key. */
59
+ spaceIds?: string[] | null | undefined;
60
+ /** Grants the key may use. `null`/omitted leaves the owner's role as the limit. */
61
+ permissions?: string[] | null | undefined;
62
+ }
63
+ /**
64
+ * Takes a presented key apart. The secret is base64url and may itself contain `_`, so
65
+ * the key is not split on it: the prefix is a fixed twelve hex characters and the
66
+ * secret is whatever follows.
67
+ */
68
+ export declare function parseApiKey(presented: string): {
69
+ prefix: string;
70
+ secret: string;
71
+ } | null;
72
+ /**
73
+ * Long-lived credentials for headless consumers.
74
+ *
75
+ * Keys are stored as a SHA-256 digest, never in plaintext, and are looked up by an
76
+ * indexed non-secret prefix so verification is one indexed read plus one constant-time
77
+ * comparison — not a scan-and-compare over every row.
78
+ */
79
+ export declare class ApiKeyService {
80
+ private readonly db;
81
+ private readonly repos;
82
+ constructor(db: Database, repos: Repositories);
83
+ issue(userId: string, name: string, options?: IssueApiKeyOptions): Promise<IssuedApiKey>;
84
+ /**
85
+ * Deletes the row rather than clearing `enabled`: a revoked key is never listed again
86
+ * or re-enabled, so a disabled row is only a secret digest left lying around.
87
+ */
88
+ revoke(id: string): Promise<void>;
89
+ list(userId: string): Promise<{
90
+ id: string;
91
+ name: string | null;
92
+ start: string | null;
93
+ enabled: boolean;
94
+ expiresAt: Date | null;
95
+ lastRequest: Date | null;
96
+ spaceIds: string[] | null;
97
+ permissions: string[] | null;
98
+ createdAt: Date;
99
+ }[]>;
100
+ resolve(presented: string): Promise<Principal | null>;
101
+ /** Removes expired keys; scheduled by the jobs package. */
102
+ pruneExpired(): Promise<number>;
103
+ }
104
+ //#endregion
105
+ //#region src/password.d.ts
106
+ /**
107
+ * Argon2id, the current OWASP recommendation over bcrypt — which also silently truncates
108
+ * passwords at 72 bytes. One definition serves better-auth's own sign-in path and the
109
+ * accounts an administrator creates, so both write the same hash format.
110
+ */
111
+ export declare function hashPassword(password: string): Promise<string>;
112
+ export declare function verifyPassword(stored: string, password: string): Promise<boolean>;
113
+ /** Matches better-auth's `minPasswordLength`, so a password set here signs in there. */
114
+ export declare const MIN_PASSWORD_LENGTH = 12;
115
+ //#endregion
116
+ //#region src/user.service.d.ts
117
+ export type InstanceRole = 'superadmin' | 'editor';
118
+ export interface CreateUserInput {
119
+ name: string;
120
+ email: string;
121
+ password: string;
122
+ role: InstanceRole;
123
+ }
124
+ export interface UpdateUserInput {
125
+ name?: string | undefined;
126
+ email?: string | undefined;
127
+ }
128
+ /** A user row without anything a directory listing should not carry. */
129
+ export interface UserSummary {
130
+ id: string;
131
+ name: string;
132
+ email: string;
133
+ image: string | null;
134
+ role: string;
135
+ banned: boolean;
136
+ banReason: string | null;
137
+ createdAt: Date;
138
+ updatedAt: Date;
139
+ }
140
+ export interface UserDetail extends UserSummary {
141
+ memberships: Array<{
142
+ spaceId: string;
143
+ role: MembershipRow['role'];
144
+ space: SpaceRow;
145
+ }>;
146
+ }
147
+ /**
148
+ * Instance-wide user administration: the accounts, their instance role, and whether they
149
+ * may sign in at all. Space membership stays with `SpaceService`, because it is a
150
+ * property of the space.
151
+ *
152
+ * Every rule here exists to keep the instance reachable: an administrator cannot lock
153
+ * themself out, and the instance always keeps at least one superadmin.
154
+ */
155
+ export declare class UserService {
156
+ private readonly repos;
157
+ constructor(repos: Repositories);
158
+ get(userId: string): Promise<UserDetail>;
159
+ list(pagination: {
160
+ limit: number;
161
+ offset: number;
162
+ }, search?: string): Promise<{
163
+ total: number;
164
+ limit: number;
165
+ offset: number;
166
+ items: UserSummary[];
167
+ }>;
168
+ create(input: CreateUserInput): Promise<UserSummary>;
169
+ update(userId: string, input: UpdateUserInput): Promise<UserSummary>;
170
+ /** Changing the instance role; the last superadmin cannot step down. */
171
+ setRole(userId: string, role: InstanceRole): Promise<UserSummary>;
172
+ /**
173
+ * A new password, and every session gone with the old one: whoever held the account
174
+ * before the reset does not keep it afterwards.
175
+ */
176
+ setPassword(userId: string, password: string): Promise<void>;
177
+ /** A banned user is signed out everywhere and refused on the next request. */
178
+ ban(actorId: string, userId: string, reason: string | null): Promise<UserSummary>;
179
+ unban(userId: string): Promise<UserSummary>;
180
+ delete(actorId: string, userId: string): Promise<void>;
181
+ /** Signs the user out of every device without touching the account. */
182
+ revokeSessions(userId: string): Promise<void>;
183
+ private require;
184
+ private assertNotSelf;
185
+ /**
186
+ * Whatever happens to `userId`, one superadmin must remain — otherwise the instance
187
+ * has no one left who can create a space or manage users, and no way back.
188
+ */
189
+ private assertNotLastSuperadmin;
190
+ }
191
+ //#endregion
192
+ //#region src/index.d.ts
193
+ export type ManabloxAuth = ReturnType<typeof createAuth>;
194
+ /** better-auth, wired to the Drizzle schema. Sessions are rows, so concurrent devices
195
+ * each hold their own. */
196
+ export interface AuthCallbacks {
197
+ /** Runs after a user row is created, inside better-auth's own transaction path. */
198
+ onUserCreated?: (userId: string) => Promise<void>;
199
+ /**
200
+ * Whether the public sign-up endpoint may create an account right now. Absent means
201
+ * always. The host closes it once the first account exists, so every later account is
202
+ * created by an administrator rather than by whoever finds the login page.
203
+ */
204
+ allowSignUp?: () => Promise<boolean>;
205
+ }
206
+ export declare function createAuth(config: AuthConfig, db: Database, callbacks?: AuthCallbacks): import("better-auth").Auth<{
207
+ secret: string;
208
+ baseURL?: string;
209
+ trustedOrigins: string[];
210
+ database: (options: import("better-auth").BetterAuthOptions) => import("better-auth").DBAdapter<import("better-auth").BetterAuthOptions>;
211
+ emailAndPassword: {
212
+ enabled: boolean;
213
+ minPasswordLength: number;
214
+ password: {
215
+ hash: typeof hashPassword;
216
+ verify: ({ hash: stored, password }: {
217
+ hash: string;
218
+ password: string;
219
+ }) => Promise<boolean>;
220
+ };
221
+ };
222
+ session: {
223
+ expiresIn: number;
224
+ updateAge: number;
225
+ cookieCache: {
226
+ enabled: true;
227
+ maxAge: number;
228
+ };
229
+ };
230
+ plugins: [{
231
+ id: "bearer";
232
+ version: string;
233
+ hooks: {
234
+ before: {
235
+ matcher(context: import("better-auth").HookEndpointContext): boolean;
236
+ handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
237
+ context: {
238
+ headers: Headers;
239
+ };
240
+ } | undefined>>;
241
+ }[];
242
+ after: {
243
+ matcher(context: import("better-auth").HookEndpointContext): true;
244
+ handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>;
245
+ }[];
246
+ };
247
+ options: import("better-auth/plugins").BearerOptions | undefined;
248
+ }];
249
+ databaseHooks: {
250
+ user: {
251
+ create: {
252
+ before: (user: {
253
+ id: string;
254
+ createdAt: Date;
255
+ updatedAt: Date;
256
+ email: string;
257
+ emailVerified: boolean;
258
+ name: string;
259
+ image?: string | null | undefined;
260
+ } & Record<string, unknown>) => Promise<{
261
+ data: {
262
+ id: string;
263
+ createdAt: Date;
264
+ updatedAt: Date;
265
+ email: string;
266
+ emailVerified: boolean;
267
+ name: string;
268
+ image?: string | null | undefined;
269
+ } & Record<string, unknown>;
270
+ }>;
271
+ after: (user: {
272
+ id: string;
273
+ createdAt: Date;
274
+ updatedAt: Date;
275
+ email: string;
276
+ emailVerified: boolean;
277
+ name: string;
278
+ image?: string | null | undefined;
279
+ } & Record<string, unknown>) => Promise<void>;
280
+ };
281
+ };
282
+ };
283
+ advanced: {
284
+ database: {
285
+ generateId: () => `${string}-${string}-${string}-${string}-${string}`;
286
+ };
287
+ };
288
+ }>;
289
+ /**
290
+ * Resolves a request's session into a `Principal`, including its space memberships.
291
+ * Returns `null` for anonymous requests rather than throwing — route guards decide.
292
+ */
293
+ export declare function resolvePrincipal(auth: ManabloxAuth, repos: Repositories, headers: Headers, apiKeys?: ApiKeyService): Promise<Principal | null>;
294
+ /**
295
+ * Promotes the very first account to `superadmin` and grants it ownership of every
296
+ * existing space, so a fresh install is reachable.
297
+ *
298
+ * Called from better-auth's user-create hook rather than at startup, so it fires for an
299
+ * account created after the server is already running.
300
+ */
301
+ export declare function promoteFirstUser(manablox: Manablox, repos: Repositories, userId: string): Promise<void>;
302
+ /** Covers an instance whose first account predates this behaviour. */
303
+ export declare function attachBootstrapOwner(manablox: Manablox, repos: Repositories): void;
304
+ //#endregion
305
+ export { ALL_PERMISSIONS, BUILT_IN_ROLES, type BuiltInRole, CONTENT_ACTIONS, type ContentAction, type ContentPermission, type Grant, PERMISSION_GROUPS, type Permission, type PermissionGroup, type SpaceRole, grantsCover, intersectGrants, isBuiltInRole, normaliseGrants, parseGrant, permissionsFor, typesCoveredBy };