@tatara/cli 0.4.0 → 0.6.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 (42) hide show
  1. package/dist/bin.mjs +377 -94
  2. package/package.json +1 -1
  3. package/templates/features/admin/files/src/modules/example/routes/admin-greeting.routes.ts +1 -1
  4. package/templates/features/auth/files/src/core/auth/routes/me.routes.ts +1 -1
  5. package/templates/features/auth-keycloak/files/src/core/auth/commands/keycloak-token.ts +2 -2
  6. package/templates/features/auth-keycloak/files/src/core/auth/keycloak.ts +7 -56
  7. package/templates/features/auth-keycloak/files/src/core/auth/tests/keycloak-tokens.test.ts +2 -2
  8. package/templates/features/auth-keycloak/files+authz/src/core/auth/tests/keycloak-authz.test.ts +2 -2
  9. package/templates/features/authz/files/src/core/authz/commands/grant-role.ts +5 -5
  10. package/templates/features/authz/files/src/core/authz/commands/sync-permissions.ts +2 -2
  11. package/templates/features/authz/files/src/core/authz/db/seed.ts +2 -2
  12. package/templates/features/authz/files/src/core/authz/index.ts +9 -0
  13. package/templates/features/authz/files/src/core/authz/routes/authorization.routes.ts +9 -280
  14. package/templates/features/authz/files/src/core/authz/system-roles.ts +0 -2
  15. package/templates/features/authz/files/src/core/authz/tests/authz.test.ts +1 -2
  16. package/templates/features/authz/files/tests/helpers/authz.ts +6 -8
  17. package/templates/features/authz/files+drizzle/src/core/authz/db/store.ts +3 -3
  18. package/templates/features/authz/files+prisma/src/core/authz/db/store.ts +3 -3
  19. package/templates/features/better-auth/files/src/core/auth/delivery.ts +6 -30
  20. package/templates/features/better-auth/files/src/core/auth/principal.ts +7 -38
  21. package/templates/features/better-auth/files/src/core/auth/sms.ts +3 -12
  22. package/templates/features/better-auth/files/tests/helpers/auth.ts +9 -12
  23. package/templates/generators/permission/files/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
  24. package/templates/generators/resource/files+authz/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
  25. package/templates/generators/route/files+authz/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
  26. package/templates/versions.json +4 -1
  27. package/templates/features/auth/files/src/core/auth/middleware.ts +0 -29
  28. package/templates/features/auth-keycloak/files/src/core/auth/keycloak-plugin.ts +0 -154
  29. package/templates/features/authz/files/src/core/authz/cache.ts +0 -31
  30. package/templates/features/authz/files/src/core/authz/catalog.ts +0 -85
  31. package/templates/features/authz/files/src/core/authz/constants.ts +0 -32
  32. package/templates/features/authz/files/src/core/authz/middleware.ts +0 -21
  33. package/templates/features/authz/files/src/core/authz/permissions.ts +0 -31
  34. package/templates/features/authz/files/src/core/authz/resolver.ts +0 -98
  35. package/templates/features/authz/files/src/core/authz/services/audit.ts +0 -24
  36. package/templates/features/authz/files/src/core/authz/services/grants.ts +0 -29
  37. package/templates/features/authz/files/src/core/authz/services/members.ts +0 -84
  38. package/templates/features/authz/files/src/core/authz/services/roles.ts +0 -73
  39. package/templates/features/authz/files/src/core/authz/services/sync.ts +0 -34
  40. package/templates/features/authz/files/src/core/authz/types.ts +0 -87
  41. package/templates/features/authz/files/src/core/authz/validators.ts +0 -99
  42. package/templates/features/better-auth/files/src/core/auth/openapi.ts +0 -60
@@ -1,14 +1,5 @@
1
+ import { consoleSmsSender, type SmsSender } from "@tatara/auth";
1
2
  import { logger } from "#core/logging/logger";
2
3
 
3
- /** Implement this for your SMS provider and return it from `smsSender`. */
4
- export interface SmsSender {
5
- send(to: string, text: string): Promise<void>;
6
- }
7
-
8
- const consoleSender: SmsSender = {
9
- async send(to) {
10
- logger.info({ to }, "sms not sent: no SMS provider configured (see src/core/auth/sms.ts)");
11
- },
12
- };
13
-
14
- export const smsSender: SmsSender = consoleSender;
4
+ /** Logs instead of sending. Replace with an SmsSender for your provider. */
5
+ export const smsSender: SmsSender = consoleSmsSender(logger);
@@ -1,5 +1,5 @@
1
+ import { createTestUser as createUser, sessionHeaders } from "@tatara/auth/testing";
1
2
  import { auth } from "#core/auth/auth";
2
- import { newId } from "@tatara/db";
3
3
  // tatara:slot imports
4
4
 
5
5
  export interface AsUserOptions {
@@ -12,14 +12,13 @@ export interface AsUserOptions {
12
12
 
13
13
  /** Creates a verified user and returns their id. */
14
14
  export async function createTestUser(options: AsUserOptions = {}): Promise<string> {
15
- const ctx = await auth.$context;
16
- const user = await ctx.internalAdapter.createUser({
17
- email: options.email ?? `user-${newId()}@example.com`,
18
- name: options.name ?? "Test User",
19
- emailVerified: true,
20
- // tatara:slot user-fields
21
- }, { method: "admin" });
22
- return user.id;
15
+ return createUser(auth, {
16
+ email: options.email,
17
+ name: options.name,
18
+ fields: {
19
+ // tatara:slot user-fields
20
+ },
21
+ });
23
22
  }
24
23
 
25
24
  /** A new user with a real session; the token is sent as a bearer token. */
@@ -28,9 +27,7 @@ export async function authenticate(
28
27
  ): Promise<{ userId: string; headers: Record<string, string> }> {
29
28
  // tatara:slot authenticate
30
29
  const userId = await createTestUser(options);
31
- const ctx = await auth.$context;
32
- const session = await ctx.internalAdapter.createSession(userId);
33
- return { userId, headers: { authorization: `Bearer ${session.token}` } };
30
+ return { userId, headers: await sessionHeaders(auth, userId) };
34
31
  }
35
32
 
36
33
  /** Headers that authenticate as a new user. */
@@ -1,4 +1,4 @@
1
- import { definePermissions } from "#core/authz/catalog";
1
+ import { definePermissions } from "@tatara/authz";
2
2
 
3
3
  export default definePermissions({
4
4
  resources: {
@@ -1,4 +1,4 @@
1
- import { definePermissions } from "#core/authz/catalog";
1
+ import { definePermissions } from "@tatara/authz";
2
2
 
3
3
  export default definePermissions({
4
4
  resources: {
@@ -1,4 +1,4 @@
1
- import { definePermissions } from "#core/authz/catalog";
1
+ import { definePermissions } from "@tatara/authz";
2
2
 
3
3
  export default definePermissions({
4
4
  resources: {
@@ -34,5 +34,8 @@
34
34
  "@tatara/core": "0.1.0",
35
35
  "@tatara/http": "0.1.0",
36
36
  "@tatara/db": "0.1.0",
37
- "@tatara/testing": "0.1.0"
37
+ "@tatara/testing": "0.1.0",
38
+ "@tatara/auth": "0.1.0",
39
+ "@tatara/keycloak": "0.1.0",
40
+ "@tatara/authz": "0.1.0"
38
41
  }
@@ -1,29 +0,0 @@
1
- import { createMiddleware } from "hono/factory";
2
- import type { Context } from "hono";
3
- import type { AppEnv, Principal } from "#core/http/context";
4
- import { ForbiddenError, UnauthorizedError } from "@tatara/http";
5
-
6
- /** 401 unless the request carries a valid session or token. */
7
- export function requireAuth() {
8
- return createMiddleware<AppEnv>(async (c, next) => {
9
- if (!c.get("principal")) throw new UnauthorizedError();
10
- await next();
11
- });
12
- }
13
-
14
- /** 401 without a principal, 403 unless it has at least one of the roles. */
15
- export function requireRole(...roles: string[]) {
16
- return createMiddleware<AppEnv>(async (c, next) => {
17
- const principal = c.get("principal");
18
- if (!principal) throw new UnauthorizedError();
19
- if (!principal.roles.some((role) => roles.includes(role))) throw new ForbiddenError();
20
- await next();
21
- });
22
- }
23
-
24
- /** The authenticated principal; use in handlers behind requireAuth(). */
25
- export function currentPrincipal(c: Context<AppEnv>): Principal {
26
- const principal = c.get("principal");
27
- if (!principal) throw new UnauthorizedError();
28
- return principal;
29
- }
@@ -1,154 +0,0 @@
1
- import type { BetterAuthPlugin } from "better-auth";
2
- import { createAuthEndpoint } from "better-auth/api";
3
- import { z } from "zod";
4
- import {
5
- type KeycloakClaims,
6
- organizationOf,
7
- rolesOf,
8
- verifyAccessToken,
9
- } from "#core/auth/keycloak";
10
- import { logger } from "#core/logging/logger";
11
-
12
- export interface KeycloakPrincipal {
13
- userId: string;
14
- orgId: string | null;
15
- roles: string[];
16
- kind: "user" | "service";
17
- claims: KeycloakClaims;
18
- }
19
-
20
- export interface KeycloakTokensOptions {
21
- /** Record the token's organization as a better-auth organization + membership. */
22
- organizations?: boolean;
23
- }
24
-
25
- type Adapter = Parameters<NonNullable<BetterAuthPlugin["init"]>>[0]["adapter"];
26
-
27
- const ACCOUNT_PROVIDER = "keycloak";
28
-
29
- async function ensureUser(adapter: Adapter, claims: KeycloakClaims): Promise<boolean> {
30
- // an unverified email could claim someone else's address, so it is never stored
31
- const verified = claims.email_verified === true && Boolean(claims.email);
32
- const email = verified
33
- ? (claims.email as string).toLowerCase()
34
- : `${claims.sub}@users.keycloak.invalid`;
35
- const name = claims.name ?? claims.preferred_username ?? claims.sub;
36
- const owner = await adapter.findOne<{ id: string }>({
37
- model: "user",
38
- where: [{ field: "email", value: email }],
39
- });
40
- const existing = await adapter.findOne<{ id: string }>({
41
- model: "user",
42
- where: [{ field: "id", value: claims.sub }],
43
- });
44
- if (existing) {
45
- const emailFree = !owner || owner.id === claims.sub;
46
- if (!emailFree) logger.warn({ sub: claims.sub }, "keycloak email belongs to another account");
47
- await adapter.update({
48
- model: "user",
49
- where: [{ field: "id", value: claims.sub }],
50
- update: {
51
- name,
52
- ...(emailFree ? { email, emailVerified: verified } : {}),
53
- updatedAt: new Date(),
54
- },
55
- });
56
- return true;
57
- }
58
- if (owner) {
59
- // never attach a Keycloak identity to an account that signs in another way
60
- logger.warn({ sub: claims.sub }, "keycloak token email belongs to another account");
61
- return false;
62
- }
63
- const now = new Date();
64
- await adapter.create({
65
- model: "user",
66
- data: { id: claims.sub, email, emailVerified: verified, name, createdAt: now, updatedAt: now },
67
- forceAllowId: true,
68
- });
69
- await adapter.create({
70
- model: "account",
71
- data: {
72
- userId: claims.sub,
73
- accountId: claims.sub,
74
- providerId: ACCOUNT_PROVIDER,
75
- createdAt: now,
76
- updatedAt: now,
77
- },
78
- });
79
- return true;
80
- }
81
-
82
- async function ensureMembership(adapter: Adapter, orgId: string, userId: string): Promise<void> {
83
- const org = await adapter.findOne({
84
- model: "organization",
85
- where: [{ field: "id", value: orgId }],
86
- });
87
- if (!org) {
88
- await adapter.create({
89
- model: "organization",
90
- data: { id: orgId, name: orgId, slug: orgId, createdAt: new Date() },
91
- forceAllowId: true,
92
- });
93
- }
94
- const member = await adapter.findOne({
95
- model: "member",
96
- where: [
97
- { field: "organizationId", value: orgId },
98
- { field: "userId", value: userId },
99
- ],
100
- });
101
- if (!member) {
102
- await adapter.create({
103
- model: "member",
104
- data: { organizationId: orgId, userId, role: "member", createdAt: new Date() },
105
- });
106
- }
107
- }
108
-
109
- /**
110
- * Lets the API accept access tokens issued by Keycloak (a resource server).
111
- * Verified tokens become principals; their users and organizations are kept in better-auth's tables.
112
- */
113
- export function keycloakTokens(options: KeycloakTokensOptions = {}) {
114
- // subjects already synced by this process; tokens are re-verified on every request regardless
115
- const synced = new Set<string>();
116
- return {
117
- id: "keycloak-tokens",
118
- endpoints: {
119
- // no path: callable only on the server as auth.api.verifyKeycloakToken
120
- verifyKeycloakToken: createAuthEndpoint(
121
- { method: "POST", body: z.object({ token: z.string() }) },
122
- async (ctx): Promise<KeycloakPrincipal | null> => {
123
- let claims: KeycloakClaims;
124
- try {
125
- claims = await verifyAccessToken(ctx.body.token);
126
- } catch (error) {
127
- logger.debug({ err: error }, "rejected keycloak token");
128
- return null;
129
- }
130
- const isService = claims.preferred_username?.startsWith("service-account-") ?? false;
131
- const orgId = organizationOf(claims);
132
- if (!isService) {
133
- const key = `${claims.sub}|${orgId ?? ""}|${claims.email ?? ""}`;
134
- if (!synced.has(key)) {
135
- const { adapter } = ctx.context;
136
- if (!(await ensureUser(adapter, claims))) return null;
137
- if (orgId && options.organizations)
138
- await ensureMembership(adapter, orgId, claims.sub);
139
- if (synced.size > 10_000) synced.clear();
140
- synced.add(key);
141
- }
142
- }
143
- return {
144
- userId: claims.sub,
145
- orgId,
146
- roles: rolesOf(claims),
147
- kind: isService ? "service" : "user",
148
- claims,
149
- };
150
- },
151
- ),
152
- },
153
- } satisfies BetterAuthPlugin;
154
- }
@@ -1,31 +0,0 @@
1
- import { CACHE_TTL_MS } from "#core/authz/constants";
2
- import type { EffectivePermissions } from "#core/authz/types";
3
-
4
- const entries = new Map<string, { value: EffectivePermissions; expires: number }>();
5
-
6
- const key = (orgId: string, userId: string, roles: string[]) =>
7
- `${orgId}:${userId}:${[...roles].sort().join(",")}`;
8
-
9
- export function getCached(orgId: string, userId: string, roles: string[]) {
10
- const entry = entries.get(key(orgId, userId, roles));
11
- if (!entry || entry.expires < Date.now()) return undefined;
12
- return entry.value;
13
- }
14
-
15
- export function setCached(orgId: string, userId: string, roles: string[], value: EffectivePermissions) {
16
- if (entries.size > 10_000) entries.clear();
17
- entries.set(key(orgId, userId, roles), { value, expires: Date.now() + CACHE_TTL_MS });
18
- }
19
-
20
- /** Drops cached sets for one member (any org when orgId is omitted). */
21
- export function invalidateMember(userId: string, orgId?: string) {
22
- for (const k of entries.keys()) {
23
- const [o, u] = k.split(":");
24
- if (u === userId && (!orgId || o === orgId)) entries.delete(k);
25
- }
26
- }
27
-
28
- /** Role definitions changed: every cached set may be stale. */
29
- export function invalidateAll() {
30
- entries.clear();
31
- }
@@ -1,85 +0,0 @@
1
- import { SCOPES, type Scope } from "#core/authz/constants";
2
- import type { SystemRoleKey } from "#core/authz/system-roles";
3
-
4
- export interface ActionSpec {
5
- /** scoped actions are checked at own | team | org */
6
- readonly scoped: boolean;
7
- }
8
-
9
- export type ResourceSpecs = Record<string, Record<string, ActionSpec>>;
10
-
11
- export type GrantTuple = readonly [resource: string, action: string, scope?: Scope];
12
-
13
- export interface PermissionSlice<R extends ResourceSpecs = ResourceSpecs> {
14
- /** resources this module owns and the actions on them */
15
- readonly resources: R;
16
- /** grants this module adds to each built-in role, for its own resources */
17
- readonly roleGrants?: Partial<Record<SystemRoleKey, readonly GrantTuple[]>>;
18
- }
19
-
20
- /** "resource:action" keys of one slice, for typed `requirePermission(...)` calls. */
21
- export type PermissionKeysOf<S> = S extends PermissionSlice<infer R>
22
- ? { [K in keyof R & string]: `${K}:${keyof R[K] & string}` }[keyof R & string]
23
- : never;
24
-
25
- /** Default export of every `permissions/*.permissions.ts`; merged by `tatara sync`. */
26
- export function definePermissions<const R extends ResourceSpecs>(
27
- slice: PermissionSlice<R>,
28
- ): PermissionSlice<R> {
29
- return slice;
30
- }
31
-
32
- export interface Catalog {
33
- resources: ResourceSpecs;
34
- keys: string[];
35
- roleGrants: Partial<Record<SystemRoleKey, GrantTuple[]>>;
36
- }
37
-
38
- export function mergeCatalogs(...slices: PermissionSlice[]): Catalog {
39
- const resources: Record<string, Record<string, ActionSpec>> = {};
40
- const roleGrants: Partial<Record<SystemRoleKey, GrantTuple[]>> = {};
41
- for (const slice of slices) {
42
- for (const [resource, actions] of Object.entries(slice.resources)) {
43
- if (resources[resource]) throw new Error(`Permission resource "${resource}" is declared twice`);
44
- resources[resource] = actions;
45
- }
46
- for (const [role, grants] of Object.entries(slice.roleGrants ?? {})) {
47
- const key = role as SystemRoleKey;
48
- roleGrants[key] = [...(roleGrants[key] ?? []), ...(grants ?? [])];
49
- }
50
- }
51
- const keys = Object.entries(resources).flatMap(([resource, actions]) =>
52
- Object.keys(actions).map((action) => `${resource}:${action}`),
53
- );
54
- return { resources, keys, roleGrants };
55
- }
56
-
57
- /** Resources only built-in roles may grant: authorization itself. */
58
- export const META_RESOURCES: ReadonlySet<string> = new Set(["role", "member", "audit_log"]);
59
-
60
- export class InvalidGrantError extends Error {}
61
-
62
- /** Throws unless (resource, action, scope) exists in the catalog with a matching scope shape. */
63
- export function assertGrantValid(
64
- catalog: Catalog,
65
- grant: { resource: string; action: string; scope?: string | null },
66
- ): void {
67
- const spec = catalog.resources[grant.resource]?.[grant.action];
68
- if (!spec) throw new InvalidGrantError(`Unknown permission ${grant.resource}:${grant.action}`);
69
- const scope = grant.scope ?? null;
70
- if (spec.scoped && !scope) {
71
- throw new InvalidGrantError(
72
- `${grant.resource}:${grant.action} is scoped; pass one of ${SCOPES.join(", ")}`,
73
- );
74
- }
75
- if (spec.scoped && scope && !(SCOPES as readonly string[]).includes(scope)) {
76
- throw new InvalidGrantError(`Scope "${scope}" must be one of ${SCOPES.join(", ")}`);
77
- }
78
- if (!spec.scoped && scope) {
79
- throw new InvalidGrantError(`${grant.resource}:${grant.action} is not scoped; drop the scope`);
80
- }
81
- }
82
-
83
- export function isScoped(catalog: Catalog, resource: string, action: string): boolean {
84
- return catalog.resources[resource]?.[action]?.scoped === true;
85
- }
@@ -1,32 +0,0 @@
1
- /** Scope hierarchy: a grant at a higher rank satisfies a check at a lower one (org > team > own). */
2
- export const SCOPES = ["own", "team", "org"] as const;
3
- export type Scope = (typeof SCOPES)[number];
4
-
5
- export const SCOPE_RANK: Record<Scope, number> = { own: 1, team: 2, org: 3 };
6
-
7
- export const OVERLAY_EFFECTS = ["grant", "deny"] as const;
8
- export type OverlayEffect = (typeof OVERLAY_EFFECTS)[number];
9
-
10
- export const AUDIT_CHANGE_TYPES = [
11
- "role_created",
12
- "role_updated",
13
- "role_deleted",
14
- "member_role_assigned",
15
- "member_role_revoked",
16
- "overlay_granted",
17
- "overlay_revoked",
18
- "member_removed",
19
- ] as const;
20
- export type AuditChangeType = (typeof AUDIT_CHANGE_TYPES)[number];
21
-
22
- /** Audit actor for changes made by the system rather than a user (e.g. org membership hooks). */
23
- export const SYSTEM_ACTOR = "system";
24
-
25
- /** Org used when the principal has none (single-tenant apps, users without an active org). */
26
- export const DEFAULT_ORG_ID = "default";
27
-
28
- /** Org id stored on system (built-in) roles; they apply to every org. */
29
- export const SYSTEM_ORG_ID = "";
30
-
31
- /** How long a resolved permission set is cached in-process. */
32
- export const CACHE_TTL_MS = 30_000;
@@ -1,21 +0,0 @@
1
- import { createMiddleware } from "hono/factory";
2
- import type { Scope } from "#core/authz/constants";
3
- import { checkPermission } from "#core/authz/resolver";
4
- import type { AppEnv } from "#core/http/context";
5
- import { ForbiddenError, UnauthorizedError } from "@tatara/http";
6
- import type { PermissionKey } from "#generated/permissions";
7
-
8
- /**
9
- * 401 without a principal, 403 unless it holds `resource:action` (at `scope` or wider).
10
- * Pair with `security: [{ bearerAuth: ["resource:action"] }]` so the route documents it.
11
- */
12
- export function requirePermission(permission: PermissionKey, scope?: Scope) {
13
- return createMiddleware<AppEnv>(async (c, next) => {
14
- const principal = c.get("principal");
15
- if (!principal) throw new UnauthorizedError();
16
- if (!(await checkPermission(principal, permission, scope))) {
17
- throw new ForbiddenError(`Missing permission ${permission}${scope ? ` (${scope})` : ""}`);
18
- }
19
- await next();
20
- });
21
- }
@@ -1,31 +0,0 @@
1
- import { definePermissions } from "#core/authz/catalog";
2
-
3
- /** Authorization's own resources; only built-in roles may grant them. */
4
- export default definePermissions({
5
- resources: {
6
- role: {
7
- read: { scoped: false },
8
- create: { scoped: false },
9
- update: { scoped: false },
10
- delete: { scoped: false },
11
- },
12
- member: {
13
- read: { scoped: false },
14
- update: { scoped: false },
15
- },
16
- audit_log: {
17
- read: { scoped: false },
18
- },
19
- },
20
- roleGrants: {
21
- admin: [
22
- ["role", "read"],
23
- ["role", "create"],
24
- ["role", "update"],
25
- ["role", "delete"],
26
- ["member", "read"],
27
- ["member", "update"],
28
- ["audit_log", "read"],
29
- ],
30
- },
31
- });
@@ -1,98 +0,0 @@
1
- import { getCached, setCached } from "#core/authz/cache";
2
- import { DEFAULT_ORG_ID, SCOPE_RANK, type Scope } from "#core/authz/constants";
3
- import { store } from "#core/authz/db/store";
4
- import { SYSTEM_ROLE_KEYS } from "#core/authz/system-roles";
5
- import { type EffectivePermissions, grantKey, type PermissionGrant } from "#core/authz/types";
6
- import type { Principal } from "#core/http/context";
7
-
8
- /** The org a principal acts in: its active org, or the default org. */
9
- export function orgOf(principal: Pick<Principal, "orgId">): string {
10
- return principal.orgId ?? DEFAULT_ORG_ID;
11
- }
12
-
13
- /** Roles from the identity provider that match a built-in role key are honoured as that role. */
14
- function impliedRoles(principal: Pick<Principal, "roles">): string[] {
15
- return principal.roles.filter((role) => SYSTEM_ROLE_KEYS.has(role));
16
- }
17
-
18
- /**
19
- * Effective permissions = grants of the member's roles (assigned in the org, plus built-in
20
- * roles implied by the identity provider) + active grant overlays − active deny overlays.
21
- */
22
- export async function effectivePermissions(
23
- principal: Pick<Principal, "userId" | "orgId" | "roles">,
24
- ): Promise<EffectivePermissions> {
25
- const orgId = orgOf(principal);
26
- const implied = impliedRoles(principal);
27
- const cached = getCached(orgId, principal.userId, implied);
28
- if (cached) return cached;
29
-
30
- const [{ roles, grants }, overlays] = await Promise.all([
31
- store.roleGrants(orgId, principal.userId, implied),
32
- store.activeOverlays(orgId, principal.userId, new Date()),
33
- ]);
34
- const all: PermissionGrant[] = [...grants];
35
- const denies = new Set<string>();
36
- for (const overlay of overlays) {
37
- const grant = { resource: overlay.resource, action: overlay.action, scope: overlay.scope };
38
- if (overlay.effect === "deny") denies.add(grantKey(grant));
39
- else all.push(grant);
40
- }
41
- const value = { grants: all, denies, roles };
42
- setCached(orgId, principal.userId, implied, value);
43
- return value;
44
- }
45
-
46
- /** Pure check against a resolved set: deny wins; scoped checks honour org > team > own. */
47
- export function allows(
48
- permissions: EffectivePermissions,
49
- resource: string,
50
- action: string,
51
- scope?: Scope,
52
- ): boolean {
53
- if (permissions.denies.has(`${resource}:${action}:${scope ?? "*"}`)) return false;
54
- if (scope && permissions.denies.has(`${resource}:${action}:*`)) return false;
55
- // a denied grant can never satisfy a check, even a narrower one
56
- const live = permissions.grants.filter(
57
- (g) => !permissions.denies.has(grantKey(g)) && !permissions.denies.has(`${g.resource}:${g.action}:*`),
58
- );
59
- if (!scope) {
60
- return live.some((g) => g.resource === resource && g.action === action);
61
- }
62
- const required = SCOPE_RANK[scope];
63
- return live.some(
64
- (g) =>
65
- g.resource === resource &&
66
- g.action === action &&
67
- g.scope !== null &&
68
- SCOPE_RANK[g.scope] >= required,
69
- );
70
- }
71
-
72
- export async function checkPermission(
73
- principal: Pick<Principal, "userId" | "orgId" | "roles">,
74
- permission: string,
75
- scope?: Scope,
76
- ): Promise<boolean> {
77
- const [resource = "", action = ""] = permission.split(":");
78
- return allows(await effectivePermissions(principal), resource, action, scope);
79
- }
80
-
81
- /**
82
- * The widest scope the principal holds for a scoped action. Middleware proves the caller
83
- * may act at some scope; services use this to decide which rows to return.
84
- */
85
- export async function resolveScope(
86
- principal: Pick<Principal, "userId" | "orgId" | "roles">,
87
- permission: string,
88
- ): Promise<Scope | null> {
89
- const [resource = "", action = ""] = permission.split(":");
90
- const permissions = await effectivePermissions(principal);
91
- let best: Scope | null = null;
92
- for (const g of permissions.grants) {
93
- if (g.resource !== resource || g.action !== action || g.scope === null) continue;
94
- if (permissions.denies.has(grantKey(g))) continue;
95
- if (!best || SCOPE_RANK[g.scope] > SCOPE_RANK[best]) best = g.scope;
96
- }
97
- return best;
98
- }
@@ -1,24 +0,0 @@
1
- import type { AuditChangeType } from "#core/authz/constants";
2
- import { store } from "#core/authz/db/store";
3
-
4
- export async function audit(input: {
5
- orgId: string;
6
- actorId: string;
7
- targetUserId?: string | null;
8
- changeType: AuditChangeType;
9
- before?: unknown;
10
- after?: unknown;
11
- }): Promise<void> {
12
- await store.writeAudit({
13
- orgId: input.orgId,
14
- actorId: input.actorId,
15
- targetUserId: input.targetUserId ?? null,
16
- changeType: input.changeType,
17
- before: input.before,
18
- after: input.after,
19
- });
20
- }
21
-
22
- export function listAudit(orgId: string, limit = 50) {
23
- return store.listAudit(orgId, limit);
24
- }
@@ -1,29 +0,0 @@
1
- import { assertGrantValid, InvalidGrantError, META_RESOURCES } from "#core/authz/catalog";
2
- import type { Scope } from "#core/authz/constants";
3
- import type { PermissionGrant } from "#core/authz/types";
4
- import { BusinessRuleError } from "@tatara/http";
5
- import { catalog } from "#generated/permissions";
6
-
7
- /** Validates grants against the catalog; custom roles and overlays may not grant meta resources. */
8
- export function validateGrants(
9
- grants: { resource: string; action: string; scope?: string | null }[],
10
- options: { allowMeta: boolean },
11
- ): PermissionGrant[] {
12
- return grants.map((grant) => {
13
- try {
14
- assertGrantValid(catalog, grant);
15
- } catch (error) {
16
- if (error instanceof InvalidGrantError) {
17
- throw new BusinessRuleError("INVALID_GRANT", error.message);
18
- }
19
- throw error;
20
- }
21
- if (!options.allowMeta && META_RESOURCES.has(grant.resource)) {
22
- throw new BusinessRuleError(
23
- "META_GRANT_FORBIDDEN",
24
- `${grant.resource}:${grant.action} can only be granted by built-in roles`,
25
- );
26
- }
27
- return { resource: grant.resource, action: grant.action, scope: (grant.scope as Scope) ?? null };
28
- });
29
- }