@frigear-nu/users 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +6 -3
  2. package/dist/module.d.mts +3 -13
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +14 -8
  5. package/dist/runtime/admin-menus.js +3 -1
  6. package/dist/runtime/app/components/UserCreateSlideover.d.vue.ts +3 -6
  7. package/dist/runtime/app/components/UserCreateSlideover.vue +3 -21
  8. package/dist/runtime/app/components/UserCreateSlideover.vue.d.ts +3 -6
  9. package/dist/runtime/app/composables/useUserActions.d.ts +1 -3
  10. package/dist/runtime/app/composables/useUserActions.js +2 -2
  11. package/dist/runtime/app/pages/admin.vue +8 -8
  12. package/dist/runtime/app/tabs/Overview.vue +10 -30
  13. package/dist/runtime/app/utils/admin-user.d.ts +11 -3
  14. package/dist/runtime/i18n/lang/da.json +13 -4
  15. package/dist/runtime/i18n/lang/en.json +13 -4
  16. package/dist/runtime/server/mcp/tools/get-my-profile.js +1 -1
  17. package/dist/runtime/server/routes/admin/new.get.js +1 -1
  18. package/dist/runtime/server/routes/admin/stats.get.js +1 -1
  19. package/dist/runtime/server/routes/admin/user-resend.post.js +1 -1
  20. package/dist/runtime/server/routes/admin/user.get.js +6 -9
  21. package/dist/runtime/server/routes/admin/user.patch.js +2 -8
  22. package/dist/runtime/server/routes/admin/users.get.js +21 -13
  23. package/dist/runtime/server/routes/admin/users.post.js +2 -5
  24. package/dist/runtime/server/routes/me/profile.patch.js +2 -2
  25. package/dist/runtime/server/utils/admin.d.ts +54 -81
  26. package/dist/runtime/server/utils/admin.js +57 -48
  27. package/dist/runtime/server/utils/dto.d.ts +1 -2
  28. package/dist/runtime/server/utils/dto.js +0 -1
  29. package/dist/runtime/server/utils/require-user.d.ts +11 -6
  30. package/dist/runtime/server/utils/require-user.js +3 -6
  31. package/dist/runtime/server/utils/roles.d.ts +17 -0
  32. package/dist/runtime/server/utils/roles.js +8 -0
  33. package/dist/runtime/utils/api.d.ts +2 -4
  34. package/dist/runtime/utils/api.js +3 -5
  35. package/package.json +13 -13
  36. package/dist/runtime/server/plugins/users-read-scope.d.ts +0 -2
  37. package/dist/runtime/server/plugins/users-read-scope.js +0 -6
  38. package/dist/runtime/server/routes/admin/roles.get.d.ts +0 -2
  39. package/dist/runtime/server/routes/admin/roles.get.js +0 -4
@@ -1,5 +1,5 @@
1
1
  import { db, schema } from "@nuxthub/db";
2
- import { and, count, eq, isNotNull, isNull, or } from "drizzle-orm";
2
+ import { and, asc, count, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
3
3
  import { z } from "zod";
4
4
  import { escapeLike, likeEscaped as like, orderByQuery, pageQuery, pageRange, paginate } from "@frigear-nu/module-kit/server";
5
5
  const querySchema = pageQuery({
@@ -11,27 +11,27 @@ const querySchema = pageQuery({
11
11
  }
12
12
  });
13
13
  export default defineEventHandler(async (event) => {
14
- const actor = await authorizeUsersAdmin(event, "view", {}, { scopes: [USERS_READ_SCOPE] });
14
+ await authorizeUsersAdmin(event, "list");
15
15
  const query = await getValidatedQuery(event, querySchema.parse);
16
- const withRole = usersHaveRoles();
17
- const columns = schema.users;
16
+ const userRoles = usersRoleAssignments();
18
17
  const conditions = [];
19
18
  if (query.q) {
20
19
  const pattern = `%${escapeLike(query.q)}%`;
21
- const matches = [like(schema.users.name, pattern), like(schema.users.email, pattern)];
22
- if (withRole && columns.role) matches.push(like(columns.role, pattern));
23
- conditions.push(or(...matches));
20
+ conditions.push(or(like(schema.users.name, pattern), like(schema.users.email, pattern)));
21
+ }
22
+ if (query.role && userRoles) {
23
+ conditions.push(sql`exists (select 1 from ${userRoles} where ${userRoles.userId} = ${schema.users.id} and ${userRoles.role} = ${query.role})`);
24
24
  }
25
- if (query.role && withRole && columns.role) conditions.push(eq(columns.role, query.role));
26
25
  if (query.verified) {
27
26
  conditions.push(query.verified === "true" ? isNotNull(schema.users.emailVerifiedAt) : isNull(schema.users.emailVerifiedAt));
28
27
  }
29
28
  const where = conditions.length ? and(...conditions) : void 0;
29
+ const firstRole = userRoles ? sql`(select min(${userRoles.role}) from ${userRoles} where ${userRoles.userId} = ${schema.users.id})` : void 0;
30
30
  const orderBy = orderByQuery({
31
31
  id: schema.users.id,
32
32
  name: schema.users.name,
33
33
  email: schema.users.email,
34
- role: withRole ? columns.role : void 0,
34
+ role: firstRole,
35
35
  createdAt: schema.users.createdAt,
36
36
  lastLoginAt: schema.users.lastLoginAt
37
37
  }, query, { tiebreaker: schema.users.id });
@@ -41,15 +41,23 @@ export default defineEventHandler(async (event) => {
41
41
  db.select({ total: count() }).from(schema.users).where(where)
42
42
  ]);
43
43
  const subscriptions = await latestSubscriptions(rows.map((user) => user.id));
44
- const roles = withRole ? await assignableRoles(event, actor.id) : [];
44
+ const rolesByUser = /* @__PURE__ */ new Map();
45
+ if (userRoles && rows.length) {
46
+ const assigned = await db.select({ userId: userRoles.userId, role: userRoles.role }).from(userRoles).where(inArray(userRoles.userId, rows.map((user) => user.id))).orderBy(asc(userRoles.role));
47
+ for (const { userId, role } of assigned) rolesByUser.set(userId, [...rolesByUser.get(userId) ?? [], role]);
48
+ }
45
49
  return {
46
50
  ...paginate({
47
51
  total: totals?.total ?? 0,
48
52
  query,
49
- items: rows.map((user) => ({ ...toAdminUserDto(user), subscription: subscriptions.get(user.id) ?? null }))
53
+ items: rows.map((user) => ({
54
+ ...toAdminUserDto(user),
55
+ subscription: subscriptions.get(user.id) ?? null,
56
+ ...userRoles ? { roles: rolesByUser.get(user.id) ?? [] } : {}
57
+ }))
50
58
  }),
51
- hasRoles: withRole,
59
+ hasRoles: !!userRoles,
52
60
  hasSubscriptions: !!schema.subscriptions,
53
- roles
61
+ roles: userRoles ? usersStoredRoleOptions() : []
54
62
  };
55
63
  });
@@ -5,7 +5,6 @@ import { emailField, nameField } from "../../schemas.js";
5
5
  const bodySchema = z.object({
6
6
  name: nameField(),
7
7
  email: emailField(),
8
- role: z.string().trim().min(1).max(60).optional(),
9
8
  // Verified accounts are signed in by the emailed link below; leave unverified to let the user verify themselves.
10
9
  emailVerified: z.boolean().default(false),
11
10
  sendWelcomeEmail: z.boolean().default(true)
@@ -13,14 +12,12 @@ const bodySchema = z.object({
13
12
  export default defineEventHandler(async (event) => {
14
13
  await authorizeUsersAdmin(event, "create");
15
14
  const input = await readValidatedBody(event, bodySchema.parse);
16
- const withRole = usersHaveRoles();
17
- await authorizeUsersAdmin(event, "create", { input: { role: withRole ? input.role : void 0, email: input.email, name: input.name } });
15
+ if (input.emailVerified) await authorize(event, USERS_MANAGE_PERMISSION);
18
16
  await assertEmailAvailable(input.email);
19
17
  const [user] = await db.insert(schema.users).values({
20
18
  name: input.name,
21
19
  email: input.email,
22
- emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null,
23
- ...withRole && input.role ? { role: input.role } : {}
20
+ emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null
24
21
  }).returning();
25
22
  if (!user) {
26
23
  throw apiError(500, "internal_error", "Failed to create the user.");
@@ -9,7 +9,7 @@ const bodySchema = z.object({
9
9
  avatar: avatarField().optional()
10
10
  });
11
11
  export default defineEventHandler(async (event) => {
12
- const user = await requireUser(event, { sessionOnly: true });
12
+ const { user, kind } = await authorize(event, "profile:write");
13
13
  const { name, avatar } = await readValidatedBody(event, bodySchema.parse);
14
14
  const [updated] = await db.update(schema.users).set({
15
15
  ...name !== void 0 ? { name } : {},
@@ -17,6 +17,6 @@ export default defineEventHandler(async (event) => {
17
17
  updatedAt: /* @__PURE__ */ new Date()
18
18
  }).where(eq(schema.users.id, user.id)).returning();
19
19
  if (!updated) throw notFound("User not found.");
20
- await setUserSession(event, { user: mapUserToSession(updated) });
20
+ if (kind === "session") await setUserSession(event, { user: mapUserToSession(updated) });
21
21
  return toProfileDto(updated);
22
22
  });
@@ -1,96 +1,69 @@
1
1
  import type { H3Event } from 'h3';
2
- export type UsersAdminAction = 'view' | 'create' | 'update' | 'delete';
3
- export type UsersAdminContext = {
4
- event: H3Event;
5
- /** The signed-in user making the request. */
6
- userId: number;
7
- action: UsersAdminAction;
8
- /** `create`/`update`: the values being written (`role` only when an authorization module added the column). */
9
- input?: {
10
- role?: string;
11
- email?: string;
12
- name?: string;
13
- };
14
- /**
15
- * `update`/`delete`: the user being changed, as stored. `emailVerifiedAt` is there so a host that grants roles by
16
- * email (an allowlist) can require a verified address, as it does at sign-in.
17
- */
18
- target?: {
19
- id: number;
20
- email: string;
21
- role?: string;
22
- emailVerifiedAt?: Date | null;
23
- };
24
- /** Set to `true` to allow. Denied by default. */
25
- allowed: boolean;
2
+ import { schema } from '@nuxthub/db';
3
+ import type { AuthPrincipal, AuthUser } from '@frigear-nu/auth/utils';
4
+ /** What a staff member does in the users admin; each maps to one permission (`USERS_PERMISSIONS`). */
5
+ export type UsersAdminAction = 'view' | 'list' | 'create' | 'update' | 'delete' | 'manage';
6
+ /**
7
+ * The permissions of the users admin, by action. `view` reads one user, `list` the directory (and the dashboard
8
+ * numbers); `manage` covers what touches someone's sign-in: changing or verifying their email, emailing a sign-in link.
9
+ */
10
+ export declare const USERS_PERMISSIONS: {
11
+ readonly view: "users:read";
12
+ readonly list: "users:list";
13
+ readonly create: "users:create";
14
+ readonly update: "users:update";
15
+ readonly delete: "users:delete";
16
+ readonly manage: "users:manage";
26
17
  };
27
- /** How a users admin route lets callers in. */
28
- export type UsersAdminCallerOptions = {
18
+ /** The permission to read one user (`GET /api/admin/users/:id` and the routes other modules add below it). */
19
+ export declare const USERS_READ_PERMISSION: "users:read";
20
+ /** The permission for the actions that touch someone's sign-in (email, sign-in links). Sessions only. */
21
+ export declare const USERS_MANAGE_PERMISSION: "users:manage";
22
+ /** A stored user, as `loadUsersAdminTarget` returns it. */
23
+ export type UsersAdminTarget = typeof schema.users.$inferSelect;
24
+ export interface UsersAdminTargetOptions {
29
25
  /**
30
- * `view` only: also accept API tokens and OAuth access tokens that carry these scopes (`users:read` for the
31
- * read-only routes). The host policy still runs against the token's user. Without it, a session is required.
26
+ * Authorize this permission instead of the action's own (`USERS_PERMISSIONS[action]`), for routes other modules add
27
+ * below `/api/admin/users/:id/` (`subscriptions:manage`). The action still decides whether target protection applies:
28
+ * every action but `view` is a write.
32
29
  */
33
- scopes?: string[];
34
- };
35
- /** The scope that lets an API token or OAuth access token read the user directory. Staff only (see the module). */
36
- export declare const USERS_READ_SCOPE = "users:read";
37
- /** The permission to create, change and delete users (role-based access control). Sessions only. */
38
- export declare const USERS_MANAGE_PERMISSION = "users:manage";
39
- export type UsersAdminRolesContext = {
40
- event: H3Event;
41
- /** The signed-in user making the request. */
42
- userId: number;
43
- /** The roles this user may assign, in display order. Replace it to narrow or extend the default (roles already in use). */
44
- roles: string[];
45
- };
46
- /** Whether another module added a `role` column to `users` (`@frigear-nu/authorization`). */
47
- export declare const usersHaveRoles: () => boolean;
48
- /** Whether the host policy lets `userId` view the users admin: who may hold `users:read`. */
49
- export declare const isUsersAdminViewer: (event: H3Event, userId: number) => any;
30
+ permission?: string;
31
+ }
50
32
  /**
51
- * Whether the host policy allows the caller to do `action` (never throws on denial; 401 without a credential). A
52
- * bearer credential is allowed nothing beyond what `options.scopes` opens up.
33
+ * Authorizes the caller for a users admin action (`USERS_PERMISSIONS[action]`, through `authorize`) and returns the
34
+ * caller's user. Throws 401 `unauthorized`, or 403 `session_required` / `insufficient_scope` / `forbidden`.
53
35
  */
54
- export declare function isUsersAdminAllowed(event: H3Event, action: UsersAdminAction, details?: Pick<UsersAdminContext, 'input' | 'target'>, options?: UsersAdminCallerOptions): Promise<{
55
- allowed: any;
56
- user: any;
57
- }>;
36
+ export declare function authorizeUsersAdmin(event: H3Event, action: UsersAdminAction): Promise<AuthUser>;
58
37
  /**
59
- * Asks the host (the `users:admin:authorize` hook) whether the signed-in user may do `action`; throws 401/403
60
- * otherwise. The users module knows nothing about roles or staff: that policy is the host's.
38
+ * The permissions `targetId` holds that `actor` does not (empty when the actor holds them all, or acts on themselves).
39
+ * The target's permissions are their roles' (assigned, default, `auto` and `authorization:roles`) plus `implicit`, as
40
+ * `getUserPermissions` resolves them; sensitive ones count by name. The actor holds a permission through their roles or
41
+ * the `authorization:before` hook. An unknown target holds nothing. Throws 403 `forbidden` when the target's roles
42
+ * cannot be resolved (the role provider, an `authorization:roles` listener or a requirement threw): fail closed.
61
43
  */
62
- export declare function authorizeUsersAdmin(event: H3Event, action: UsersAdminAction, details?: Pick<UsersAdminContext, 'input' | 'target'>, options?: UsersAdminCallerOptions): Promise<any>;
44
+ export declare function usersAdminTargetMissing(event: H3Event, actor: AuthUser, targetId: number): Promise<string[]>;
63
45
  /**
64
- * The roles the signed-in user may assign. Defaults to the roles in use; the host narrows/extends it through the
65
- * `users:admin:roles` hook (e.g. from a role hierarchy and the acting user's own rank).
46
+ * Target protection: staff may only change a user who holds no permission the staff member lacks, so a coordinator
47
+ * cannot edit or delete an admin. Hard-coded, not a policy: no hook or policy can turn it off. Throws 403 `forbidden`.
66
48
  */
67
- export declare function assignableRoles(event: H3Event, userId: number): Promise<string[]>;
49
+ export declare function assertUsersAdminTargetProtected(event: H3Event, actor: AuthUser, targetId: number): Promise<void>;
50
+ /**
51
+ * Loads the user a staff member acts on (`/api/admin/users/:id/...`) and authorizes the action against them. For the
52
+ * module's own routes and the routes other modules add with `extendUsersAdmin`.
53
+ *
54
+ * Authorizes before it looks anything up: 401 / 403 when the caller may not do the action at all, then 400 for a
55
+ * malformed id, 404 for an unknown user, 403 when a policy of the permission denies it on this user, and, for every
56
+ * action but `view`, 403 `forbidden` when the target holds a permission the caller does not (target protection).
57
+ */
58
+ export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create' | 'list'>, options?: UsersAdminTargetOptions): Promise<{
59
+ actor: AuthUser;
60
+ principal: AuthPrincipal;
61
+ target: UsersAdminTarget;
62
+ }>;
63
+ /** Whether the caller may do a write `action` to `target`: the permission (with its policies) and target protection. */
64
+ export declare function canUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'view' | 'list' | 'create'>, target: UsersAdminTarget): Promise<boolean>;
68
65
  /** Latest subscription per user, when a subscriptions table is installed (`@frigear-nu/subscriptions`); else empty. */
69
66
  export declare function latestSubscriptions(userIds: number[]): Promise<Map<number, {
70
67
  planKey: string | null;
71
68
  status: string;
72
69
  }>>;
73
- /** The policy view of a stored user: what the `users:admin:authorize` hook sees as `target`. */
74
- export declare const usersAdminTargetInfo: (user: {
75
- id: number;
76
- email: string;
77
- emailVerifiedAt?: Date | null;
78
- }) => {
79
- id: number;
80
- email: string;
81
- role: string | undefined;
82
- emailVerifiedAt: Date | null;
83
- };
84
- /**
85
- * Loads the user a staff member is acting on (`/api/admin/users/:id/...`) and runs the users admin policy against
86
- * them (`view` for reads, `update` for changes). For routes added with `extendUsersAdmin`.
87
- *
88
- * `options.scopes` lets bearer credentials with those scopes in for `view` (see `UsersAdminCallerOptions`).
89
- *
90
- * Authorizes before it looks anything up: 401 without a session, 403 when the host denies `action` outright, then
91
- * 400 for a malformed id, 404 for an unknown user, and 403 again when the host denies `action` on this target.
92
- */
93
- export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create'>, options?: UsersAdminCallerOptions): Promise<{
94
- actor: any;
95
- target: any;
96
- }>;
@@ -1,42 +1,65 @@
1
1
  import { db, schema } from "@nuxthub/db";
2
- import { desc, getTableColumns, inArray } from "drizzle-orm";
3
- import { intIdParams, notFound } from "@frigear-nu/module-kit/server";
4
- import { principalHasScopes } from "@frigear-nu/auth/utils";
5
- export const USERS_READ_SCOPE = "users:read";
6
- export const USERS_MANAGE_PERMISSION = "users:manage";
7
- export const usersHaveRoles = () => "role" in getTableColumns(schema.users);
8
- const usersViewGate = definePolicyGate("users:admin:authorize", { permission: USERS_READ_SCOPE });
9
- const usersManageGate = definePolicyGate("users:admin:authorize", { permission: USERS_MANAGE_PERMISSION });
10
- const usersAdminGate = {
11
- isAllowed: (event, userId, extra) => (extra.action === "view" ? usersViewGate : usersManageGate).isAllowed(event, userId, extra),
12
- assert: (event, userId, message, extra) => (extra.action === "view" ? usersViewGate : usersManageGate).assert(event, userId, message, extra)
2
+ import { desc, inArray } from "drizzle-orm";
3
+ import { forbidden, intIdParams, notFound } from "@frigear-nu/module-kit/server";
4
+ export const USERS_PERMISSIONS = {
5
+ view: "users:read",
6
+ list: "users:list",
7
+ create: "users:create",
8
+ update: "users:update",
9
+ delete: "users:delete",
10
+ manage: "users:manage"
13
11
  };
14
- const USERS_ADMIN_DENIED = "You are not allowed to manage users.";
15
- export const isUsersAdminViewer = (event, userId) => usersAdminGate.isAllowed(event, userId, { action: "view" });
16
- const requireUsersAdminCaller = (event, action, options) => requireUser(event, action === "view" && options.scopes?.length ? { scopes: options.scopes } : { sessionOnly: true });
17
- export async function isUsersAdminAllowed(event, action, details = {}, options = {}) {
18
- const principal = await requireAuth(event);
19
- const user = principal.user;
20
- const bearerAllowed = action === "view" && !!options.scopes?.length && principalHasScopes(principal, options.scopes);
21
- if (principal.kind !== "session" && !bearerAllowed) return { allowed: false, user };
22
- const allowed = await usersAdminGate.isAllowed(event, user.id, { action, ...details });
23
- return { allowed, user };
12
+ export const USERS_READ_PERMISSION = USERS_PERMISSIONS.view;
13
+ export const USERS_MANAGE_PERMISSION = USERS_PERMISSIONS.manage;
14
+ export async function authorizeUsersAdmin(event, action) {
15
+ return (await authorize(event, USERS_PERMISSIONS[action])).user;
24
16
  }
25
- export async function authorizeUsersAdmin(event, action, details = {}, options = {}) {
26
- const user = await requireUsersAdminCaller(event, action, options);
27
- await usersAdminGate.assert(event, user.id, USERS_ADMIN_DENIED, { action, ...details });
28
- return user;
17
+ export async function usersAdminTargetMissing(event, actor, targetId) {
18
+ if (String(actor.id) === String(targetId)) return [];
19
+ const target = await loadAuthUser(targetId);
20
+ if (!target) return [];
21
+ try {
22
+ await getEffectiveRoles(event, target, { strict: true });
23
+ } catch (error) {
24
+ console.error(`[users] the roles of user ${targetId} could not be resolved, refusing to act on them`, error);
25
+ throw forbidden("You cannot change this user right now: their roles could not be checked.");
26
+ }
27
+ const [targetHeld, actorHeld] = await Promise.all([
28
+ getUserPermissions(event, target),
29
+ getUserPermissions(event, actor)
30
+ ]);
31
+ const held = new Set(actorHeld);
32
+ const missing = [];
33
+ for (const permission of targetHeld) {
34
+ if (held.has(permission)) continue;
35
+ if (!await subjectAllowed(event, actor, permission)) missing.push(permission);
36
+ }
37
+ return missing;
38
+ }
39
+ export async function assertUsersAdminTargetProtected(event, actor, targetId) {
40
+ const missing = await usersAdminTargetMissing(event, actor, targetId);
41
+ if (missing.length) {
42
+ throw forbidden("You cannot change a user who holds permissions you do not have.", { missing });
43
+ }
44
+ }
45
+ export async function loadUsersAdminTarget(event, action, options = {}) {
46
+ const permission = options.permission ?? USERS_PERMISSIONS[action];
47
+ await authorize(event, permission);
48
+ const { id } = await getValidatedRouterParams(event, intIdParams().parse);
49
+ const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
50
+ if (!target) throw notFound("User not found.");
51
+ const principal = await authorize(event, permission, target);
52
+ if (action !== "view") await assertUsersAdminTargetProtected(event, principal.user, target.id);
53
+ return { actor: principal.user, principal, target };
29
54
  }
30
- export async function assignableRoles(event, userId) {
31
- let roles = [];
32
- if (usersHaveRoles()) {
33
- const columns = schema.users;
34
- const rows = await db.selectDistinct({ role: columns.role }).from(schema.users);
35
- roles = rows.map((row) => row.role).filter((role) => !!role);
55
+ export async function canUsersAdminTarget(event, action, target) {
56
+ const principal = await getAuth(event);
57
+ if (!principal || !await allows(event, USERS_PERMISSIONS[action], target)) return false;
58
+ try {
59
+ return !(await usersAdminTargetMissing(event, principal.user, target.id)).length;
60
+ } catch {
61
+ return false;
36
62
  }
37
- const context = { event, userId, roles };
38
- await useNitroApp().hooks.callHook("users:admin:roles", context);
39
- return [...new Set(context.roles)];
40
63
  }
41
64
  export async function latestSubscriptions(userIds) {
42
65
  const result = /* @__PURE__ */ new Map();
@@ -52,17 +75,3 @@ export async function latestSubscriptions(userIds) {
52
75
  }
53
76
  return result;
54
77
  }
55
- export const usersAdminTargetInfo = (user) => ({
56
- id: user.id,
57
- email: user.email,
58
- role: usersHaveRoles() ? user.role : void 0,
59
- emailVerifiedAt: user.emailVerifiedAt ?? null
60
- });
61
- export async function loadUsersAdminTarget(event, action, options = {}) {
62
- await authorizeUsersAdmin(event, action, {}, options);
63
- const { id } = await getValidatedRouterParams(event, intIdParams().parse);
64
- const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
65
- if (!target) throw notFound("User not found.");
66
- const actor = await authorizeUsersAdmin(event, action, { target: usersAdminTargetInfo(target), input: {} }, options);
67
- return { actor, target };
68
- }
@@ -1,11 +1,10 @@
1
1
  import type { AdminUserDto, ProfileDto } from '../../../types.js';
2
- /** The columns the DTOs read; `role`, `emailVerifiedAt` and `lastLoginAt` come from other modules' extensions. */
2
+ /** The columns the DTOs read; `emailVerifiedAt` and `lastLoginAt` come from other modules' extensions. */
3
3
  type UserRowLike = {
4
4
  id: number;
5
5
  name: string;
6
6
  email: string;
7
7
  avatar?: string | null;
8
- role?: string | null;
9
8
  emailVerifiedAt?: Date | number | string | null;
10
9
  lastLoginAt?: Date | number | string | null;
11
10
  createdAt: Date | number | string;
@@ -4,7 +4,6 @@ export function toAdminUserDto(user) {
4
4
  id: user.id,
5
5
  name: user.name,
6
6
  email: user.email,
7
- ...usersHaveRoles() && user.role ? { role: user.role } : {},
8
7
  avatar: user.avatar ?? null,
9
8
  emailVerifiedAt: isoDate(user.emailVerifiedAt),
10
9
  lastLoginAt: isoDate(user.lastLoginAt),
@@ -1,12 +1,17 @@
1
1
  import type { H3Event } from 'h3';
2
- import { type RequireUserOptions } from '@frigear-nu/auth/utils';
2
+ /** How `requireUser` lets callers in. Authentication only: check what the caller may do with `authorize`. */
3
+ export type RequireUserAuthOptions = {
4
+ /** Reject bearer credentials (user tokens, OAuth access tokens). Use for account-level actions. */
5
+ sessionOnly?: boolean;
6
+ };
3
7
  /**
4
- * The signed-in user, or a thrown 401/403 (see `requireAuth` for the credential rules: `scopes`, `sessionOnly`).
5
- * Use `requireAuth` instead when the route only needs to know how the caller authenticated.
8
+ * The signed-in user, or a thrown 401 (403 `session_required` with `sessionOnly` and a bearer credential). It only says
9
+ * who is calling: authorize what they do with `authorize(event, permission)`, which also returns the principal.
6
10
  */
7
- export declare function requireUser(event: H3Event, options?: RequireUserOptions): Promise<any>;
11
+ export declare function requireUser(event: H3Event, options?: RequireUserAuthOptions): Promise<any>;
8
12
  /**
9
13
  * The caller's user when there is one, otherwise `null` (never throws). For routes that are open to everyone but
10
- * personalise for a signed-in user. A bearer credential missing the required `scopes` counts as anonymous.
14
+ * personalise for a signed-in user. Authentication only: a bearer credential counts whatever it may do, so check a
15
+ * permission with `allows(event, permission)` before using it for anything beyond the caller's identity.
11
16
  */
12
- export declare function getUser(event: H3Event, options?: Pick<RequireUserOptions, 'scopes'>): Promise<any>;
17
+ export declare function getUser(event: H3Event): Promise<any>;
@@ -1,9 +1,6 @@
1
- import { principalHasScopes } from "@frigear-nu/auth/utils";
2
1
  export async function requireUser(event, options = {}) {
3
- return (await requireAuth(event, options)).user;
2
+ return (await requireAuth(event, { sessionOnly: options.sessionOnly })).user;
4
3
  }
5
- export async function getUser(event, options = {}) {
6
- const principal = await getAuth(event);
7
- if (!principal) return null;
8
- return !options.scopes?.length || principalHasScopes(principal, options.scopes) ? principal.user : null;
4
+ export async function getUser(event) {
5
+ return (await getAuth(event))?.user ?? null;
9
6
  }
@@ -0,0 +1,17 @@
1
+ import type { AnyColumn } from 'drizzle-orm';
2
+ /** The `authorization_user_roles` table, when `@frigear-nu/authorization` registered it; else `undefined`. */
3
+ export declare function usersRoleAssignments(): {
4
+ userId: AnyColumn;
5
+ role: AnyColumn;
6
+ } | undefined;
7
+ /** A role the users list can be filtered by. */
8
+ export interface UsersRoleOption {
9
+ value: string;
10
+ label: string;
11
+ labelKey?: string;
12
+ }
13
+ /**
14
+ * The roles that can be stored on a user (configured, not `auto`, not a default role), for the list filter. Default and
15
+ * `auto` roles are held without a stored row, so filtering by them would find nobody.
16
+ */
17
+ export declare function usersStoredRoleOptions(): UsersRoleOption[];
@@ -0,0 +1,8 @@
1
+ import { schema } from "@nuxthub/db";
2
+ import { table } from "#auth/roles";
3
+ export function usersRoleAssignments() {
4
+ return schema.authorizationUserRoles;
5
+ }
6
+ export function usersStoredRoleOptions() {
7
+ return Object.values(table.roles).filter((role) => !role.auto && !role.default).map((role) => ({ value: role.name, label: role.label, ...role.labelKey ? { labelKey: role.labelKey } : {} })).sort((a, b) => a.label.localeCompare(b.label));
8
+ }
@@ -3,7 +3,7 @@ export type { AdminUserDto, ProfileDto };
3
3
  /** The users API: self-service under `/api/users`, staff under `/api/admin/users`. */
4
4
  export declare const usersApi: {
5
5
  readonly me: {
6
- /** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. Session only. */
6
+ /** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. `profile:write` (implicit). */
7
7
  readonly profile: "/api/users/me";
8
8
  /** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
9
9
  readonly email: "/api/users/me/email";
@@ -17,7 +17,7 @@ export declare const usersApi: {
17
17
  /** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
18
18
  readonly emailChangeRevert: "/api/users/email-change/revert";
19
19
  readonly admin: {
20
- /** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
20
+ /** `GET` (paginated list, `users:list`; `useTableQuery` keys plus `role`, `verified`) and `POST` (create, `users:create`, 201). */
21
21
  readonly users: "/api/admin/users";
22
22
  /** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
23
23
  readonly user: (id: number | string) => string;
@@ -27,7 +27,5 @@ export declare const usersApi: {
27
27
  readonly new: "/api/admin/users/new";
28
28
  /** `GET`: `{ total, newUsers, days }` (dashboard). */
29
29
  readonly stats: "/api/admin/users/stats";
30
- /** `GET`: `{ roles }` the caller may assign. */
31
- readonly roles: "/api/admin/users/roles";
32
30
  };
33
31
  };
@@ -2,7 +2,7 @@ const base = "/api/users";
2
2
  const adminBase = "/api/admin/users";
3
3
  export const usersApi = {
4
4
  me: {
5
- /** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. Session only. */
5
+ /** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. `profile:write` (implicit). */
6
6
  profile: `${base}/me`,
7
7
  /** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
8
8
  email: `${base}/me/email`,
@@ -16,7 +16,7 @@ export const usersApi = {
16
16
  /** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
17
17
  emailChangeRevert: `${base}/email-change/revert`,
18
18
  admin: {
19
- /** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
19
+ /** `GET` (paginated list, `users:list`; `useTableQuery` keys plus `role`, `verified`) and `POST` (create, `users:create`, 201). */
20
20
  users: adminBase,
21
21
  /** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
22
22
  user: (id) => `${adminBase}/${encodeURIComponent(String(id))}`,
@@ -25,8 +25,6 @@ export const usersApi = {
25
25
  /** `GET`: the newest sign-ups of the last 30 days (dashboard). */
26
26
  new: `${adminBase}/new`,
27
27
  /** `GET`: `{ total, newUsers, days }` (dashboard). */
28
- stats: `${adminBase}/stats`,
29
- /** `GET`: `{ roles }` the caller may assign. */
30
- roles: `${adminBase}/roles`
28
+ stats: `${adminBase}/stats`
31
29
  }
32
30
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frigear-nu/users",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "The user entity for the main frigear app: the users table, admin user management and self-service profile, email and password changes. Sign-in lives in @frigear-nu/auth.",
5
5
  "homepage": "https://docs.frigear.dev/modules/identity/users",
6
6
  "repository": {
@@ -34,11 +34,11 @@
34
34
  "playground"
35
35
  ],
36
36
  "dependencies": {
37
- "@frigear-nu/auth": "^0.4.0",
38
- "@frigear-nu/mcp": "^0.3.0",
39
- "@frigear-nu/module-kit": "^1.3.4",
40
- "@frigear-nu/notify": "^0.2.4",
41
- "@frigear-nu/ui": "^0.2.5",
37
+ "@frigear-nu/auth": "^0.5.0",
38
+ "@frigear-nu/mcp": "^0.4.0",
39
+ "@frigear-nu/module-kit": "^1.3.5",
40
+ "@frigear-nu/notify": "^0.2.5",
41
+ "@frigear-nu/ui": "^0.2.6",
42
42
  "@libsql/client": "^0.18.0",
43
43
  "@nuxt/kit": "^4.6.4",
44
44
  "drizzle-kit": "^0.31.11",
@@ -48,9 +48,9 @@
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@frigear-nu/admin": ">=0.0.0",
51
- "@frigear-nu/email-templates": "^0.1.0",
52
- "@frigear-nu/menu": "^0.2.4",
53
- "@frigear-nu/widget": "^0.2.4",
51
+ "@frigear-nu/email-templates": "^0.1.1",
52
+ "@frigear-nu/menu": "^0.3.0",
53
+ "@frigear-nu/widget": "^0.3.0",
54
54
  "@nuxt/ui": "^4.12.0",
55
55
  "@nuxthub/core": "^0.10.12"
56
56
  },
@@ -73,10 +73,10 @@
73
73
  },
74
74
  "devDependencies": {
75
75
  "@electric-sql/pglite": "^0.5.15",
76
- "@frigear-nu/admin": "^0.3.0",
77
- "@frigear-nu/email-templates": "^0.1.0",
78
- "@frigear-nu/menu": "^0.2.4",
79
- "@frigear-nu/widget": "^0.2.4",
76
+ "@frigear-nu/admin": "^0.4.0",
77
+ "@frigear-nu/email-templates": "^0.1.1",
78
+ "@frigear-nu/menu": "^0.3.0",
79
+ "@frigear-nu/widget": "^0.3.0",
80
80
  "@nuxt/devtools": "^4.1.0",
81
81
  "@nuxt/eslint-config": "^1.17.0",
82
82
  "@nuxt/module-builder": "^1.0.3",
@@ -1,2 +0,0 @@
1
- declare const _default: any;
2
- export default _default;
@@ -1,6 +0,0 @@
1
- export default defineNitroPlugin((nitroApp) => {
2
- nitroApp.hooks.hook("auth:scope-available", async (ctx) => {
3
- if (ctx.scope.name !== USERS_READ_SCOPE || !ctx.available) return;
4
- ctx.available = await isUsersAdminViewer(ctx.event, ctx.user.id);
5
- });
6
- });
@@ -1,2 +0,0 @@
1
- declare const _default: any;
2
- export default _default;
@@ -1,4 +0,0 @@
1
- export default defineEventHandler(async (event) => {
2
- const user = await authorizeUsersAdmin(event, "view");
3
- return { roles: await assignableRoles(event, user.id) };
4
- });