@tatara/cli 0.5.0 → 0.7.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.
- package/dist/bin.mjs +370 -30
- package/package.json +1 -1
- package/templates/features/auth-keycloak/files+authz/src/core/auth/tests/keycloak-authz.test.ts +2 -2
- package/templates/features/authz/files/src/core/authz/commands/grant-role.ts +5 -5
- package/templates/features/authz/files/src/core/authz/commands/sync-permissions.ts +2 -2
- package/templates/features/authz/files/src/core/authz/db/seed.ts +2 -2
- package/templates/features/authz/files/src/core/authz/index.ts +9 -0
- package/templates/features/authz/files/src/core/authz/routes/authorization.routes.ts +9 -280
- package/templates/features/authz/files/src/core/authz/system-roles.ts +0 -2
- package/templates/features/authz/files/src/core/authz/tests/authz.test.ts +1 -2
- package/templates/features/authz/files/tests/helpers/authz.ts +6 -8
- package/templates/features/authz/files+drizzle/src/core/authz/db/store.ts +3 -3
- package/templates/features/authz/files+prisma/src/core/authz/db/store.ts +3 -3
- package/templates/features/email/files/src/core/email/send.ts +8 -17
- package/templates/features/i18n/files/src/core/i18n/index.ts +5 -35
- package/templates/features/jobs/files/src/apps/cron/index.ts +4 -21
- package/templates/features/jobs/files/src/apps/worker/index.ts +11 -19
- package/templates/features/jobs/files/src/core/jobs/commands/enqueue.ts +1 -1
- package/templates/features/jobs/files/src/core/jobs/index.ts +10 -0
- package/templates/features/jobs/files/src/modules/example/consumers/send-welcome.ts +1 -1
- package/templates/features/jobs/files/src/modules/example/schedules/heartbeat.ts +1 -1
- package/templates/features/jobs/files/src/modules/example/tests/jobs.test.ts +4 -4
- package/templates/features/storage/files/src/core/storage/commands/check.ts +3 -3
- package/templates/features/storage/files/src/core/storage/index.ts +19 -5
- package/templates/features/storage/files/src/core/storage/tests/storage.test.ts +1 -1
- package/templates/generators/consumer/files/src/modules/__moduleKebab__/consumers/__nameKebab__.ts +1 -1
- package/templates/generators/consumer/files/src/modules/__moduleKebab__/tests/__nameKebab__.consumer.test.ts +1 -1
- package/templates/generators/permission/files/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
- package/templates/generators/resource/files+authz/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
- package/templates/generators/route/files+authz/src/modules/__moduleKebab__/permissions/__nameKebab__.permissions.ts +1 -1
- package/templates/generators/schedule/files/src/modules/__moduleKebab__/schedules/__nameKebab__.ts +1 -1
- package/templates/versions.json +6 -1
- package/templates/features/authz/files/src/core/authz/cache.ts +0 -31
- package/templates/features/authz/files/src/core/authz/catalog.ts +0 -85
- package/templates/features/authz/files/src/core/authz/constants.ts +0 -32
- package/templates/features/authz/files/src/core/authz/middleware.ts +0 -21
- package/templates/features/authz/files/src/core/authz/permissions.ts +0 -31
- package/templates/features/authz/files/src/core/authz/resolver.ts +0 -98
- package/templates/features/authz/files/src/core/authz/services/audit.ts +0 -24
- package/templates/features/authz/files/src/core/authz/services/grants.ts +0 -29
- package/templates/features/authz/files/src/core/authz/services/members.ts +0 -84
- package/templates/features/authz/files/src/core/authz/services/roles.ts +0 -73
- package/templates/features/authz/files/src/core/authz/services/sync.ts +0 -34
- package/templates/features/authz/files/src/core/authz/types.ts +0 -87
- package/templates/features/authz/files/src/core/authz/validators.ts +0 -99
- package/templates/features/jobs/files/src/core/jobs/define.ts +0 -37
- package/templates/features/jobs/files/src/core/jobs/lock.ts +0 -17
- package/templates/features/jobs/files/src/core/jobs/process.ts +0 -19
- package/templates/features/jobs/files/src/core/jobs/queue.ts +0 -29
- package/templates/features/jobs/files/src/core/jobs/redis.ts +0 -17
- package/templates/features/storage/files/src/core/storage/local.ts +0 -34
- package/templates/features/storage/files/src/core/storage/s3.ts +0 -66
- package/templates/features/storage/files/src/core/storage/storage.ts +0 -21
package/templates/versions.json
CHANGED
|
@@ -36,5 +36,10 @@
|
|
|
36
36
|
"@tatara/db": "0.1.0",
|
|
37
37
|
"@tatara/testing": "0.1.0",
|
|
38
38
|
"@tatara/auth": "0.1.0",
|
|
39
|
-
"@tatara/keycloak": "0.1.0"
|
|
39
|
+
"@tatara/keycloak": "0.1.0",
|
|
40
|
+
"@tatara/authz": "0.1.0",
|
|
41
|
+
"@tatara/storage": "0.1.0",
|
|
42
|
+
"@tatara/email": "0.1.0",
|
|
43
|
+
"@tatara/i18n": "0.1.0",
|
|
44
|
+
"@tatara/jobs": "0.1.0"
|
|
40
45
|
}
|
|
@@ -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
|
-
}
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { invalidateMember } from "#core/authz/cache";
|
|
2
|
-
import { type OverlayEffect, type Scope, SYSTEM_ACTOR } from "#core/authz/constants";
|
|
3
|
-
import { store } from "#core/authz/db/store";
|
|
4
|
-
import { audit } from "#core/authz/services/audit";
|
|
5
|
-
import { validateGrants } from "#core/authz/services/grants";
|
|
6
|
-
import { NotFoundError } from "@tatara/http";
|
|
7
|
-
|
|
8
|
-
export async function getMember(orgId: string, userId: string) {
|
|
9
|
-
const [roles, overlays] = await Promise.all([
|
|
10
|
-
store.memberRoles(orgId, userId),
|
|
11
|
-
store.listOverlays(orgId, userId),
|
|
12
|
-
]);
|
|
13
|
-
return { userId, orgId, roles, overlays };
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export async function assignRole(actorId: string | null, orgId: string, userId: string, roleId: string) {
|
|
17
|
-
const role = await store.findRole(orgId, roleId);
|
|
18
|
-
if (!role) throw new NotFoundError("Role");
|
|
19
|
-
const added = await store.assignRole(orgId, userId, roleId, actorId);
|
|
20
|
-
invalidateMember(userId, orgId);
|
|
21
|
-
if (added && actorId) {
|
|
22
|
-
await audit({ orgId, actorId, targetUserId: userId, changeType: "member_role_assigned", after: { roleId, key: role.key } });
|
|
23
|
-
}
|
|
24
|
-
return added;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export async function revokeRole(actorId: string, orgId: string, userId: string, roleId: string) {
|
|
28
|
-
const removed = await store.revokeRole(orgId, userId, roleId);
|
|
29
|
-
if (!removed) throw new NotFoundError("Role assignment");
|
|
30
|
-
invalidateMember(userId, orgId);
|
|
31
|
-
await audit({ orgId, actorId, targetUserId: userId, changeType: "member_role_revoked", before: { roleId } });
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Removes all of a user's access in an org; called when they stop being a member. */
|
|
35
|
-
export async function removeMemberAccess(orgId: string, userId: string, actorId = SYSTEM_ACTOR) {
|
|
36
|
-
const removed = await store.removeMember(orgId, userId);
|
|
37
|
-
invalidateMember(userId, orgId);
|
|
38
|
-
if (removed.roles + removed.overlays > 0) {
|
|
39
|
-
await audit({
|
|
40
|
-
orgId,
|
|
41
|
-
actorId,
|
|
42
|
-
targetUserId: userId,
|
|
43
|
-
changeType: "member_removed",
|
|
44
|
-
before: removed,
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
return removed;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface OverlayInput {
|
|
51
|
-
resource: string;
|
|
52
|
-
action: string;
|
|
53
|
-
scope?: Scope | null;
|
|
54
|
-
effect: OverlayEffect;
|
|
55
|
-
reason?: string | null;
|
|
56
|
-
expiresAt?: Date | null;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Per-user grant or deny, optionally expiring. Deny always wins over any grant. */
|
|
60
|
-
export async function addOverlay(actorId: string | null, orgId: string, userId: string, input: OverlayInput) {
|
|
61
|
-
const [grant] = validateGrants([input], { allowMeta: input.effect === "deny" });
|
|
62
|
-
if (!grant) throw new NotFoundError("Permission");
|
|
63
|
-
const id = await store.addOverlay({
|
|
64
|
-
orgId,
|
|
65
|
-
userId,
|
|
66
|
-
...grant,
|
|
67
|
-
effect: input.effect,
|
|
68
|
-
grantedBy: actorId,
|
|
69
|
-
reason: input.reason ?? null,
|
|
70
|
-
expiresAt: input.expiresAt ?? null,
|
|
71
|
-
});
|
|
72
|
-
invalidateMember(userId, orgId);
|
|
73
|
-
if (actorId) {
|
|
74
|
-
await audit({ orgId, actorId, targetUserId: userId, changeType: "overlay_granted", after: { id, ...grant, effect: input.effect } });
|
|
75
|
-
}
|
|
76
|
-
return id;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export async function removeOverlay(actorId: string, orgId: string, userId: string, overlayId: string) {
|
|
80
|
-
const removed = await store.removeOverlay(orgId, userId, overlayId);
|
|
81
|
-
if (!removed) throw new NotFoundError("Overlay");
|
|
82
|
-
invalidateMember(userId, orgId);
|
|
83
|
-
await audit({ orgId, actorId, targetUserId: userId, changeType: "overlay_revoked", before: removed });
|
|
84
|
-
}
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import { invalidateAll } from "#core/authz/cache";
|
|
2
|
-
import { store } from "#core/authz/db/store";
|
|
3
|
-
import { audit } from "#core/authz/services/audit";
|
|
4
|
-
import { validateGrants } from "#core/authz/services/grants";
|
|
5
|
-
import { SYSTEM_ROLE_KEYS } from "#core/authz/system-roles";
|
|
6
|
-
import type { RoleRow } from "#core/authz/types";
|
|
7
|
-
import { BusinessRuleError, ConflictError, NotFoundError } from "@tatara/http";
|
|
8
|
-
|
|
9
|
-
export interface RoleInput {
|
|
10
|
-
key: string;
|
|
11
|
-
name: string;
|
|
12
|
-
description?: string | null;
|
|
13
|
-
grants: { resource: string; action: string; scope?: string | null }[];
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function listRoles(orgId: string): Promise<RoleRow[]> {
|
|
17
|
-
return store.listRoles(orgId);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
async function customRole(orgId: string, roleId: string): Promise<RoleRow> {
|
|
21
|
-
const role = await store.findRole(orgId, roleId);
|
|
22
|
-
if (!role) throw new NotFoundError("Role");
|
|
23
|
-
if (role.isSystem) throw new BusinessRuleError("SYSTEM_ROLE_IMMUTABLE", "Built-in roles cannot be changed");
|
|
24
|
-
return role;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export async function createRole(actorId: string, orgId: string, input: RoleInput): Promise<RoleRow> {
|
|
28
|
-
if (SYSTEM_ROLE_KEYS.has(input.key)) {
|
|
29
|
-
throw new ConflictError(`"${input.key}" is a built-in role key`);
|
|
30
|
-
}
|
|
31
|
-
if (await store.findRoleByKey(orgId, input.key)) throw new ConflictError(`Role "${input.key}" exists`);
|
|
32
|
-
const grants = validateGrants(input.grants, { allowMeta: false });
|
|
33
|
-
const id = await store.createRole({
|
|
34
|
-
orgId,
|
|
35
|
-
key: input.key,
|
|
36
|
-
name: input.name,
|
|
37
|
-
description: input.description ?? null,
|
|
38
|
-
isSystem: false,
|
|
39
|
-
grants,
|
|
40
|
-
});
|
|
41
|
-
const role = await store.findRole(orgId, id);
|
|
42
|
-
if (!role) throw new NotFoundError("Role");
|
|
43
|
-
await audit({ orgId, actorId, changeType: "role_created", after: role });
|
|
44
|
-
return role;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export async function updateRole(
|
|
48
|
-
actorId: string,
|
|
49
|
-
orgId: string,
|
|
50
|
-
roleId: string,
|
|
51
|
-
input: Partial<Omit<RoleInput, "key">>,
|
|
52
|
-
): Promise<RoleRow> {
|
|
53
|
-
const before = await customRole(orgId, roleId);
|
|
54
|
-
await store.updateRole(roleId, {
|
|
55
|
-
...(input.name === undefined ? {} : { name: input.name }),
|
|
56
|
-
...(input.description === undefined ? {} : { description: input.description }),
|
|
57
|
-
...(input.grants ? { grants: validateGrants(input.grants, { allowMeta: false }) } : {}),
|
|
58
|
-
});
|
|
59
|
-
invalidateAll();
|
|
60
|
-
const after = await customRole(orgId, roleId);
|
|
61
|
-
await audit({ orgId, actorId, changeType: "role_updated", before, after });
|
|
62
|
-
return after;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export async function deleteRole(actorId: string, orgId: string, roleId: string): Promise<void> {
|
|
66
|
-
const role = await customRole(orgId, roleId);
|
|
67
|
-
if (role.memberCount > 0) {
|
|
68
|
-
throw new ConflictError(`Role "${role.key}" is assigned to ${role.memberCount} member(s)`);
|
|
69
|
-
}
|
|
70
|
-
await store.deleteRole(roleId);
|
|
71
|
-
invalidateAll();
|
|
72
|
-
await audit({ orgId, actorId, changeType: "role_deleted", before: role });
|
|
73
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { invalidateAll } from "#core/authz/cache";
|
|
2
|
-
import { SYSTEM_ORG_ID } from "#core/authz/constants";
|
|
3
|
-
import { store } from "#core/authz/db/store";
|
|
4
|
-
import { validateGrants } from "#core/authz/services/grants";
|
|
5
|
-
import { SYSTEM_ROLES } from "#core/authz/system-roles";
|
|
6
|
-
import { grantKey } from "#core/authz/types";
|
|
7
|
-
import { catalog } from "#generated/permissions";
|
|
8
|
-
|
|
9
|
-
/** Creates or updates every built-in role so its grants match the code. Idempotent. */
|
|
10
|
-
export async function syncSystemRoles(): Promise<{ created: string[]; updated: string[] }> {
|
|
11
|
-
const created: string[] = [];
|
|
12
|
-
const updated: string[] = [];
|
|
13
|
-
for (const meta of SYSTEM_ROLES) {
|
|
14
|
-
const grants = validateGrants(
|
|
15
|
-
(catalog.roleGrants[meta.key] ?? []).map(([resource, action, scope]) => ({ resource, action, scope })),
|
|
16
|
-
{ allowMeta: true },
|
|
17
|
-
);
|
|
18
|
-
const existing = await store.findRoleByKey(SYSTEM_ORG_ID, meta.key);
|
|
19
|
-
if (!existing) {
|
|
20
|
-
await store.createRole({ orgId: SYSTEM_ORG_ID, key: meta.key, name: meta.name, description: meta.description, isSystem: true, grants });
|
|
21
|
-
created.push(meta.key);
|
|
22
|
-
continue;
|
|
23
|
-
}
|
|
24
|
-
const want = new Set(grants.map(grantKey));
|
|
25
|
-
const have = new Set(existing.grants.map(grantKey));
|
|
26
|
-
const same = want.size === have.size && [...want].every((k) => have.has(k));
|
|
27
|
-
if (!same || existing.name !== meta.name || existing.description !== meta.description) {
|
|
28
|
-
await store.updateRole(existing.id, { name: meta.name, description: meta.description, grants });
|
|
29
|
-
updated.push(meta.key);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
if (created.length || updated.length) invalidateAll();
|
|
33
|
-
return { created, updated };
|
|
34
|
-
}
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import type { OverlayEffect, Scope } from "#core/authz/constants";
|
|
2
|
-
|
|
3
|
-
export interface PermissionGrant {
|
|
4
|
-
resource: string;
|
|
5
|
-
action: string;
|
|
6
|
-
scope: Scope | null;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export interface OverlayRow extends PermissionGrant {
|
|
10
|
-
id: string;
|
|
11
|
-
orgId: string;
|
|
12
|
-
userId: string;
|
|
13
|
-
effect: OverlayEffect;
|
|
14
|
-
grantedBy: string | null;
|
|
15
|
-
reason: string | null;
|
|
16
|
-
expiresAt: Date | null;
|
|
17
|
-
createdAt: Date;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export interface RoleRow {
|
|
21
|
-
id: string;
|
|
22
|
-
orgId: string;
|
|
23
|
-
key: string;
|
|
24
|
-
name: string;
|
|
25
|
-
description: string | null;
|
|
26
|
-
isSystem: boolean;
|
|
27
|
-
grants: PermissionGrant[];
|
|
28
|
-
memberCount: number;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface AuditRow {
|
|
32
|
-
id: string;
|
|
33
|
-
orgId: string;
|
|
34
|
-
actorId: string;
|
|
35
|
-
targetUserId: string | null;
|
|
36
|
-
changeType: string;
|
|
37
|
-
before: unknown;
|
|
38
|
-
after: unknown;
|
|
39
|
-
at: Date;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** A member's resolved permissions in one org. */
|
|
43
|
-
export interface EffectivePermissions {
|
|
44
|
-
grants: PermissionGrant[];
|
|
45
|
-
/** "resource:action:scope|*" keys denied by overlays; deny always wins */
|
|
46
|
-
denies: Set<string>;
|
|
47
|
-
roles: string[];
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function grantKey(grant: PermissionGrant): string {
|
|
51
|
-
return `${grant.resource}:${grant.action}:${grant.scope ?? "*"}`;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Everything authz reads and writes; implemented once per ORM in #core/authz/db/store. */
|
|
55
|
-
export interface AuthzStore {
|
|
56
|
-
roleGrants(orgId: string, userId: string, impliedRoleKeys: string[]): Promise<{
|
|
57
|
-
roles: string[];
|
|
58
|
-
grants: PermissionGrant[];
|
|
59
|
-
}>;
|
|
60
|
-
activeOverlays(orgId: string, userId: string, now: Date): Promise<OverlayRow[]>;
|
|
61
|
-
listRoles(orgId: string): Promise<RoleRow[]>;
|
|
62
|
-
findRole(orgId: string, roleId: string): Promise<RoleRow | null>;
|
|
63
|
-
findRoleByKey(orgId: string, key: string): Promise<RoleRow | null>;
|
|
64
|
-
createRole(input: {
|
|
65
|
-
orgId: string;
|
|
66
|
-
key: string;
|
|
67
|
-
name: string;
|
|
68
|
-
description: string | null;
|
|
69
|
-
isSystem: boolean;
|
|
70
|
-
grants: PermissionGrant[];
|
|
71
|
-
}): Promise<string>;
|
|
72
|
-
updateRole(
|
|
73
|
-
roleId: string,
|
|
74
|
-
input: { name?: string; description?: string | null; grants?: PermissionGrant[] },
|
|
75
|
-
): Promise<void>;
|
|
76
|
-
deleteRole(roleId: string): Promise<void>;
|
|
77
|
-
memberRoles(orgId: string, userId: string): Promise<RoleRow[]>;
|
|
78
|
-
assignRole(orgId: string, userId: string, roleId: string, by: string | null): Promise<boolean>;
|
|
79
|
-
revokeRole(orgId: string, userId: string, roleId: string): Promise<boolean>;
|
|
80
|
-
/** Deletes every role assignment and overlay the user has in the org. */
|
|
81
|
-
removeMember(orgId: string, userId: string): Promise<{ roles: number; overlays: number }>;
|
|
82
|
-
listOverlays(orgId: string, userId: string): Promise<OverlayRow[]>;
|
|
83
|
-
addOverlay(input: Omit<OverlayRow, "id" | "createdAt">): Promise<string>;
|
|
84
|
-
removeOverlay(orgId: string, userId: string, overlayId: string): Promise<OverlayRow | null>;
|
|
85
|
-
writeAudit(input: Omit<AuditRow, "id" | "at">): Promise<void>;
|
|
86
|
-
listAudit(orgId: string, limit: number): Promise<AuditRow[]>;
|
|
87
|
-
}
|