@specdest/devkit 0.4.17 → 0.4.19
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/README.md +5 -2
- package/dist/npm/cli.js +2 -0
- package/dist/npm/commands.d.ts +1 -0
- package/dist/npm/commands.js +15 -9
- package/dist/npm/github-doppler-secrets.d.ts +8 -0
- package/dist/npm/github-doppler-secrets.js +156 -0
- package/dist/npm/host-automation.js +22 -1
- package/dist/npm/index.js +2 -1
- package/dist/npm/predefined-packages/abac.js +30 -7
- package/dist/npm/predefined-packages/admin-ui-templates/AdminAccessAssignments.tsx.template +67 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminConfirmDialog.tsx.template +46 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminDataTable.tsx.template +49 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminDetailLayout.tsx.template +15 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminEmptyState.tsx.template +17 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminFilterBar.tsx.template +16 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminFormLayout.tsx.template +19 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminMembershipManager.tsx.template +56 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminPage.tsx.template +19 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminPageHeader.tsx.template +19 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminPagination.tsx.template +20 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminPermissionMatrix.tsx.template +54 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminRoleManager.tsx.template +81 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminShell.tsx.template +20 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminSidebar.tsx.template +18 -0
- package/dist/npm/predefined-packages/admin-ui-templates/AdminStatCard.tsx.template +22 -0
- package/dist/npm/predefined-packages/admin-ui.d.ts +2 -0
- package/dist/npm/predefined-packages/admin-ui.js +83 -0
- package/dist/npm/predefined-packages/auth-templates/README.md.template +9 -0
- package/dist/npm/predefined-packages/auth-templates/convex.ts.template +18 -0
- package/dist/npm/predefined-packages/auth-templates/identity.ts.template +2 -0
- package/dist/npm/predefined-packages/auth-templates/supabase.ts.template +36 -0
- package/dist/npm/predefined-packages/auth.js +22 -7
- package/dist/npm/predefined-packages/multi-tenancy.js +21 -5
- package/dist/npm/predefined-packages/registry.js +2 -0
- package/dist/npm/predefined-packages/security-templates/README.md.template +15 -0
- package/dist/npm/predefined-packages/security-templates/convex-authorization.ts.template +109 -0
- package/dist/npm/predefined-packages/security-templates/permissions.ts.template +40 -0
- package/dist/npm/predefined-packages/security-templates/supabase-admin-rpc.sql.template +54 -0
- package/dist/npm/predefined-packages/security-templates/supabase-authorization.sql.template +138 -0
- package/dist/npm/predefined-packages/security-templates/supabase-posts-example.sql.template +39 -0
- package/dist/npm/predefined-packages/tenant-templates/README.md.template +11 -0
- package/dist/npm/predefined-packages/tenant-templates/tenant-context.ts.template +22 -0
- package/dist/npm/project-check.d.ts +12 -0
- package/dist/npm/project-check.js +54 -1
- package/dist/npm/supabase-local.js +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** Server-side authorization for Convex queries and mutations.
|
|
2
|
+
* Call these helpers only from server functions. Loaders must read trusted DB records.
|
|
3
|
+
*/
|
|
4
|
+
import { canAccess, type Actor, type Assignment, type Resource, type Role } from '../src/lib/permissions.ts';
|
|
5
|
+
|
|
6
|
+
type Context = { auth: { getUserIdentity(): Promise<{ subject: string } | null> } };
|
|
7
|
+
type PolicyLoaders = {
|
|
8
|
+
ctx: Context;
|
|
9
|
+
loadActor: (subject: string) => Promise<Actor | null>;
|
|
10
|
+
loadRoles: () => Promise<readonly Role[]>;
|
|
11
|
+
loadAssignments: () => Promise<readonly Assignment[]>;
|
|
12
|
+
};
|
|
13
|
+
type Operation = { feature: string; action: string; tenantId: string | null };
|
|
14
|
+
type VerifiedPolicy = { actor: Actor; roles: readonly Role[]; assignments: readonly Assignment[] };
|
|
15
|
+
|
|
16
|
+
async function verifiedPolicy(input: PolicyLoaders): Promise<VerifiedPolicy> {
|
|
17
|
+
const identity = await input.ctx.auth.getUserIdentity();
|
|
18
|
+
if (!identity?.subject) throw new Error('Unauthorized');
|
|
19
|
+
const actor = await input.loadActor(identity.subject);
|
|
20
|
+
if (!actor || actor.id !== identity.subject) throw new Error('Forbidden');
|
|
21
|
+
const [roles, assignments] = await Promise.all([input.loadRoles(), input.loadAssignments()]);
|
|
22
|
+
return { actor, roles, assignments };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Resource reads and writes fail closed when the stored resource does not exist.
|
|
26
|
+
* `requireResource: false` is only valid for a create or collection-level check.
|
|
27
|
+
*/
|
|
28
|
+
export async function authorize(input: PolicyLoaders & Operation & {
|
|
29
|
+
loadResource: () => Promise<Resource | null>;
|
|
30
|
+
requireResource?: boolean;
|
|
31
|
+
}): Promise<void> {
|
|
32
|
+
const { actor, roles, assignments } = await verifiedPolicy(input);
|
|
33
|
+
if (input.requireResource === false && input.action !== 'create') throw new Error('Forbidden');
|
|
34
|
+
const resource = await input.loadResource();
|
|
35
|
+
if (input.requireResource !== false && !resource) throw new Error('Forbidden');
|
|
36
|
+
if (!canAccess({ actor, roles, assignments, resource, feature: input.feature, action: input.action, tenantId: input.tenantId })) {
|
|
37
|
+
throw new Error('Forbidden');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Use inside a Convex mutation. Authorization and write share its transaction.
|
|
42
|
+
* `loadResource` must look up the real document and return its stored owner/tenant.
|
|
43
|
+
*/
|
|
44
|
+
export async function authorizedMutation<T>(input: Parameters<typeof authorize>[0] & {
|
|
45
|
+
/** For create, supply the server-validated resource scope to be persisted. */
|
|
46
|
+
newResource?: Resource;
|
|
47
|
+
write: () => Promise<T>;
|
|
48
|
+
}): Promise<T> {
|
|
49
|
+
if (input.action === 'read') throw new Error('Forbidden');
|
|
50
|
+
if (input.action === 'create') {
|
|
51
|
+
if (input.requireResource !== false || !input.newResource ||
|
|
52
|
+
input.newResource.tenantId !== input.tenantId) throw new Error('Forbidden');
|
|
53
|
+
const identity = await input.ctx.auth.getUserIdentity();
|
|
54
|
+
if (!identity?.subject || input.newResource.ownerId !== identity.subject) throw new Error('Forbidden');
|
|
55
|
+
} else if (input.requireResource === false) {
|
|
56
|
+
throw new Error('Forbidden');
|
|
57
|
+
}
|
|
58
|
+
await authorize(input);
|
|
59
|
+
return await input.write();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Collection reads: verify the caller once and filter each server-loaded row.
|
|
63
|
+
* Never expose an unfiltered result or accept client-supplied rows/ownership.
|
|
64
|
+
* Fetch an authorized result set before applying any public pagination.
|
|
65
|
+
*/
|
|
66
|
+
export async function authorizedRows<T extends Resource>(input: PolicyLoaders & Operation & {
|
|
67
|
+
loadRows: () => Promise<readonly T[]>;
|
|
68
|
+
}): Promise<T[]> {
|
|
69
|
+
const { actor, roles, assignments } = await verifiedPolicy(input);
|
|
70
|
+
if (input.action !== 'read') throw new Error('Forbidden');
|
|
71
|
+
const rows = await input.loadRows();
|
|
72
|
+
return rows.filter((resource) => canAccess({
|
|
73
|
+
actor, roles, assignments, resource,
|
|
74
|
+
feature: input.feature, action: input.action, tenantId: input.tenantId,
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Assign an existing tenant role from a Convex mutation.
|
|
79
|
+
* The role, target membership and acting administrator are loaded from trusted
|
|
80
|
+
* database records. Requiring `any` for every delegated grant prevents an
|
|
81
|
+
* administrator with only `edit:own` from granting `edit:any` or `edit:own`.
|
|
82
|
+
* Do NOT pass client-authored grant definitions or role objects to loaders.
|
|
83
|
+
*/
|
|
84
|
+
export async function authorizedRoleAssignment<T>(input: PolicyLoaders & {
|
|
85
|
+
tenantId: string;
|
|
86
|
+
roleId: string;
|
|
87
|
+
targetUserId: string;
|
|
88
|
+
loadTargetRole: () => Promise<(Role & { tenantId: string }) | null>;
|
|
89
|
+
hasTargetMembership: () => Promise<boolean>;
|
|
90
|
+
writeAssignment: () => Promise<T>;
|
|
91
|
+
}): Promise<T> {
|
|
92
|
+
const { actor, roles, assignments } = await verifiedPolicy(input);
|
|
93
|
+
const canManage = canAccess({
|
|
94
|
+
actor, roles, assignments, tenantId: input.tenantId, resource: null,
|
|
95
|
+
feature: 'access', action: 'manage',
|
|
96
|
+
});
|
|
97
|
+
if (!canManage || !input.targetUserId || !input.roleId) throw new Error('Forbidden');
|
|
98
|
+
const [role, isMember] = await Promise.all([input.loadTargetRole(), input.hasTargetMembership()]);
|
|
99
|
+
if (!isMember || !role || role.id !== input.roleId || role.tenantId !== input.tenantId) {
|
|
100
|
+
throw new Error('Forbidden');
|
|
101
|
+
}
|
|
102
|
+
for (const grant of role.grants) {
|
|
103
|
+
if (!canAccess({
|
|
104
|
+
actor, roles, assignments, resource: null, tenantId: input.tenantId,
|
|
105
|
+
feature: grant.resource, action: grant.action,
|
|
106
|
+
})) throw new Error('Forbidden');
|
|
107
|
+
}
|
|
108
|
+
return await input.writeAssignment();
|
|
109
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Shared policy semantics. UI checks are advisory: enforce again at the data boundary. */
|
|
2
|
+
export type Permission = `${string}:${string}`;
|
|
3
|
+
export type Grant = { resource: string; action: string; scope: 'any' | 'own' };
|
|
4
|
+
export type Role = { id: string; grants: readonly Grant[] };
|
|
5
|
+
export type Membership = { tenantId: string; roleIds: readonly string[]; groupIds: readonly string[] };
|
|
6
|
+
export type Actor = { id: string; globalRoleIds: readonly string[]; memberships: readonly Membership[] };
|
|
7
|
+
export type Resource = { ownerId: string; tenantId: string | null };
|
|
8
|
+
export type Assignment = { roleId: string; userId?: string; groupId?: string; tenantId: string | null };
|
|
9
|
+
|
|
10
|
+
/** All inputs MUST be loaded on the server from trusted identity + database records. */
|
|
11
|
+
export function canAccess(input: {
|
|
12
|
+
actor: Actor | null;
|
|
13
|
+
resource: Resource | null;
|
|
14
|
+
action: string;
|
|
15
|
+
feature: string;
|
|
16
|
+
tenantId: string | null;
|
|
17
|
+
roles: readonly Role[];
|
|
18
|
+
assignments: readonly Assignment[];
|
|
19
|
+
}): boolean {
|
|
20
|
+
const { actor, resource, action, feature, tenantId, roles, assignments } = input;
|
|
21
|
+
if (!actor || !actor.id || !feature || !action) return false;
|
|
22
|
+
if (resource && resource.tenantId !== tenantId) return false;
|
|
23
|
+
const membership = tenantId === null ? null : actor.memberships.find((m) => m.tenantId === tenantId);
|
|
24
|
+
if (tenantId !== null && !membership) return false;
|
|
25
|
+
const applicable = new Set<string>();
|
|
26
|
+
for (const assignment of assignments) {
|
|
27
|
+
if (assignment.tenantId !== tenantId) continue;
|
|
28
|
+
const validSubject = Boolean(assignment.userId) !== Boolean(assignment.groupId);
|
|
29
|
+
if (validSubject && (assignment.userId === actor.id || (membership && assignment.groupId && membership.groupIds.includes(assignment.groupId)))) {
|
|
30
|
+
applicable.add(assignment.roleId);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// Global roles never implicitly authorize tenant resources.
|
|
34
|
+
for (const roleId of tenantId === null ? actor.globalRoleIds : membership?.roleIds ?? []) applicable.add(roleId);
|
|
35
|
+
const grants = roles.filter((role) => applicable.has(role.id)).flatMap((role) => role.grants);
|
|
36
|
+
return grants.some((grant) =>
|
|
37
|
+
grant.resource === feature && grant.action === action &&
|
|
38
|
+
(grant.scope === 'any' || (resource !== null && resource.ownerId === actor.id))
|
|
39
|
+
);
|
|
40
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
-- OPTIONAL PRIVILEGED OPERATIONS: review and apply after supabase-authorization.sql.
|
|
2
|
+
-- Unlike client writes to authorization tables, these narrowly scoped RPCs
|
|
3
|
+
-- authenticate via auth.uid(), require access:manage (any scope), and prevent
|
|
4
|
+
-- assigning permissions the administrator does not already hold (any scope).
|
|
5
|
+
-- New tenants/roles/grants must be provisioned by a separately audited server
|
|
6
|
+
-- workflow; do not expose service-role credentials to any client.
|
|
7
|
+
create or replace function app_authz.assign_tenant_role(
|
|
8
|
+
p_tenant uuid, p_user uuid, p_role uuid
|
|
9
|
+
) returns void language plpgsql security definer set search_path = '' as $$
|
|
10
|
+
begin
|
|
11
|
+
if not app_authz.allowed(p_tenant, 'access', 'manage', null) then
|
|
12
|
+
raise exception 'Forbidden' using errcode = '42501';
|
|
13
|
+
end if;
|
|
14
|
+
if not exists (
|
|
15
|
+
select 1 from app_authz.roles r
|
|
16
|
+
where r.id = p_role and r.tenant_id = p_tenant
|
|
17
|
+
) or not exists (
|
|
18
|
+
select 1 from app_authz.tenant_memberships m
|
|
19
|
+
where m.tenant_id = p_tenant and m.user_id = p_user
|
|
20
|
+
) then
|
|
21
|
+
raise exception 'Invalid tenant, role or member' using errcode = '42501';
|
|
22
|
+
end if;
|
|
23
|
+
if exists (
|
|
24
|
+
select 1 from app_authz.role_permissions rp
|
|
25
|
+
where rp.role_id = p_role
|
|
26
|
+
and not app_authz.allowed(p_tenant, rp.feature, rp.action, null)
|
|
27
|
+
) then
|
|
28
|
+
raise exception 'Cannot delegate permissions not held by administrator'
|
|
29
|
+
using errcode = '42501';
|
|
30
|
+
end if;
|
|
31
|
+
insert into app_authz.user_roles (user_id, tenant_id, role_id)
|
|
32
|
+
values (p_user, p_tenant, p_role)
|
|
33
|
+
on conflict do nothing;
|
|
34
|
+
end;
|
|
35
|
+
$$;
|
|
36
|
+
|
|
37
|
+
create or replace function app_authz.revoke_tenant_role(
|
|
38
|
+
p_tenant uuid, p_user uuid, p_role uuid
|
|
39
|
+
) returns void language plpgsql security definer set search_path = '' as $$
|
|
40
|
+
begin
|
|
41
|
+
if not app_authz.allowed(p_tenant, 'access', 'manage', null) then
|
|
42
|
+
raise exception 'Forbidden' using errcode = '42501';
|
|
43
|
+
end if;
|
|
44
|
+
delete from app_authz.user_roles
|
|
45
|
+
where tenant_id = p_tenant and user_id = p_user and role_id = p_role;
|
|
46
|
+
end;
|
|
47
|
+
$$;
|
|
48
|
+
revoke all on function app_authz.assign_tenant_role(uuid, uuid, uuid) from public;
|
|
49
|
+
revoke all on function app_authz.revoke_tenant_role(uuid, uuid, uuid) from public;
|
|
50
|
+
grant execute on function app_authz.assign_tenant_role(uuid, uuid, uuid) to authenticated;
|
|
51
|
+
grant execute on function app_authz.revoke_tenant_role(uuid, uuid, uuid) to authenticated;
|
|
52
|
+
-- Audit execution, tenant membership revocation, grant revocation and races
|
|
53
|
+
-- before enabling these RPCs in production. Additional operations (e.g. group
|
|
54
|
+
-- assignments, user invitations, grant editing) need separately reviewed APIs.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
-- REFERENCE ONLY: adapt and review before adding to a real Supabase declarative schema.
|
|
2
|
+
-- Identity model: auth.uid() is a verified Supabase Auth UUID, never client-provided.
|
|
3
|
+
-- External OIDC subjects require a trusted mapping to auth.users IDs.
|
|
4
|
+
-- Tenant scope is mandatory in this example. Single-tenant/global policies differ.
|
|
5
|
+
create schema if not exists app_authz;
|
|
6
|
+
|
|
7
|
+
create table if not exists app_authz.tenants (
|
|
8
|
+
id uuid primary key default gen_random_uuid(),
|
|
9
|
+
name text not null
|
|
10
|
+
);
|
|
11
|
+
create table if not exists app_authz.tenant_memberships (
|
|
12
|
+
tenant_id uuid not null references app_authz.tenants(id),
|
|
13
|
+
user_id uuid not null references auth.users(id),
|
|
14
|
+
primary key (tenant_id, user_id)
|
|
15
|
+
);
|
|
16
|
+
create table if not exists app_authz.roles (
|
|
17
|
+
id uuid primary key default gen_random_uuid(),
|
|
18
|
+
tenant_id uuid references app_authz.tenants(id),
|
|
19
|
+
name text not null,
|
|
20
|
+
unique (id, tenant_id)
|
|
21
|
+
);
|
|
22
|
+
create table if not exists app_authz.role_permissions (
|
|
23
|
+
role_id uuid not null references app_authz.roles(id) on delete cascade,
|
|
24
|
+
feature text not null,
|
|
25
|
+
action text not null,
|
|
26
|
+
scope text not null check (scope in ('any','own')),
|
|
27
|
+
primary key (role_id, feature, action, scope)
|
|
28
|
+
);
|
|
29
|
+
create table if not exists app_authz.user_roles (
|
|
30
|
+
user_id uuid not null references auth.users(id),
|
|
31
|
+
tenant_id uuid not null references app_authz.tenants(id),
|
|
32
|
+
role_id uuid not null,
|
|
33
|
+
primary key (user_id, tenant_id, role_id),
|
|
34
|
+
foreign key (tenant_id, user_id) references app_authz.tenant_memberships(tenant_id, user_id),
|
|
35
|
+
foreign key (role_id, tenant_id) references app_authz.roles(id, tenant_id)
|
|
36
|
+
);
|
|
37
|
+
create table if not exists app_authz.groups (
|
|
38
|
+
id uuid primary key default gen_random_uuid(),
|
|
39
|
+
tenant_id uuid not null references app_authz.tenants(id),
|
|
40
|
+
name text not null,
|
|
41
|
+
unique (id, tenant_id)
|
|
42
|
+
);
|
|
43
|
+
create table if not exists app_authz.group_memberships (
|
|
44
|
+
group_id uuid not null,
|
|
45
|
+
tenant_id uuid not null,
|
|
46
|
+
user_id uuid not null references auth.users(id),
|
|
47
|
+
primary key (group_id, user_id),
|
|
48
|
+
foreign key (group_id, tenant_id) references app_authz.groups(id, tenant_id),
|
|
49
|
+
foreign key (tenant_id, user_id) references app_authz.tenant_memberships(tenant_id, user_id)
|
|
50
|
+
);
|
|
51
|
+
create table if not exists app_authz.group_roles (
|
|
52
|
+
group_id uuid not null,
|
|
53
|
+
tenant_id uuid not null,
|
|
54
|
+
role_id uuid not null,
|
|
55
|
+
primary key (group_id, role_id),
|
|
56
|
+
foreign key (group_id, tenant_id) references app_authz.groups(id, tenant_id),
|
|
57
|
+
foreign key (role_id, tenant_id) references app_authz.roles(id, tenant_id)
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
-- Deny unprivileged access even if a schema/table is exposed through PostgREST.
|
|
61
|
+
-- Provision tenant/role/group records only through a trusted, admin-authorized backend.
|
|
62
|
+
alter table app_authz.tenants enable row level security;
|
|
63
|
+
alter table app_authz.tenant_memberships enable row level security;
|
|
64
|
+
alter table app_authz.roles enable row level security;
|
|
65
|
+
alter table app_authz.role_permissions enable row level security;
|
|
66
|
+
alter table app_authz.user_roles enable row level security;
|
|
67
|
+
alter table app_authz.groups enable row level security;
|
|
68
|
+
alter table app_authz.group_memberships enable row level security;
|
|
69
|
+
alter table app_authz.group_roles enable row level security;
|
|
70
|
+
revoke all on schema app_authz from public, anon, authenticated;
|
|
71
|
+
revoke all on all tables in schema app_authz from public, anon, authenticated;
|
|
72
|
+
|
|
73
|
+
-- SECURITY DEFINER reads only database-owned memberships and assignments.
|
|
74
|
+
-- The function owner must be trusted and migrations must control these tables.
|
|
75
|
+
create or replace function app_authz.allowed(p_tenant uuid, p_feature text, p_action text,
|
|
76
|
+
p_owner uuid default null)
|
|
77
|
+
returns boolean language sql stable security definer
|
|
78
|
+
set search_path = '' as $$
|
|
79
|
+
select auth.uid() is not null and p_tenant is not null and exists (
|
|
80
|
+
select 1 from app_authz.tenant_memberships m
|
|
81
|
+
join app_authz.role_permissions rp on true
|
|
82
|
+
join app_authz.roles r on r.id = rp.role_id and r.tenant_id = p_tenant
|
|
83
|
+
where m.user_id = auth.uid() and m.tenant_id = p_tenant
|
|
84
|
+
and rp.feature = p_feature and rp.action = p_action
|
|
85
|
+
and (rp.scope = 'any' or (p_owner is not null and p_owner = auth.uid()))
|
|
86
|
+
and (
|
|
87
|
+
exists (
|
|
88
|
+
select 1 from app_authz.user_roles ur
|
|
89
|
+
where ur.user_id = m.user_id and ur.tenant_id = m.tenant_id and ur.role_id = r.id
|
|
90
|
+
)
|
|
91
|
+
or exists (
|
|
92
|
+
select 1 from app_authz.group_memberships gm
|
|
93
|
+
join app_authz.group_roles gr on gr.group_id = gm.group_id and gr.tenant_id = gm.tenant_id
|
|
94
|
+
where gm.user_id = m.user_id and gm.tenant_id = m.tenant_id and gr.role_id = r.id
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
);
|
|
98
|
+
$$;
|
|
99
|
+
revoke all on function app_authz.allowed(uuid,text,text,uuid) from public;
|
|
100
|
+
grant usage on schema app_authz to authenticated;
|
|
101
|
+
grant execute on function app_authz.allowed(uuid,text,text,uuid) to authenticated;
|
|
102
|
+
|
|
103
|
+
-- Attach this immutable-scope trigger to each tenant-owned resource table.
|
|
104
|
+
-- Supply exact tenant and owner column names as trigger arguments.
|
|
105
|
+
create or replace function app_authz.prevent_scope_reassignment()
|
|
106
|
+
returns trigger language plpgsql set search_path = '' as $$
|
|
107
|
+
begin
|
|
108
|
+
if tg_nargs <> 2 then
|
|
109
|
+
raise exception 'Expected tenant and owner column names';
|
|
110
|
+
end if;
|
|
111
|
+
if (to_jsonb(new) ->> tg_argv[0]) is distinct from (to_jsonb(old) ->> tg_argv[0])
|
|
112
|
+
or (to_jsonb(new) ->> tg_argv[1]) is distinct from (to_jsonb(old) ->> tg_argv[1]) then
|
|
113
|
+
raise exception 'Tenant or ownership reassignment is not permitted';
|
|
114
|
+
end if;
|
|
115
|
+
return new;
|
|
116
|
+
end;
|
|
117
|
+
$$;
|
|
118
|
+
revoke all on function app_authz.prevent_scope_reassignment() from public;
|
|
119
|
+
|
|
120
|
+
-- Example for a real application table app.posts(tenant_id uuid, owner_id uuid, ...).
|
|
121
|
+
-- Keep this as a recipe reference, not an automatically deployed policy.
|
|
122
|
+
-- ALTER TABLE app.posts ENABLE ROW LEVEL SECURITY;
|
|
123
|
+
-- CREATE POLICY posts_read ON app.posts FOR SELECT TO authenticated
|
|
124
|
+
-- USING (app_authz.allowed(tenant_id, 'post', 'read', owner_id));
|
|
125
|
+
-- CREATE POLICY posts_insert ON app.posts FOR INSERT TO authenticated
|
|
126
|
+
-- WITH CHECK (owner_id = auth.uid() AND
|
|
127
|
+
-- app_authz.allowed(tenant_id, 'post', 'create', owner_id));
|
|
128
|
+
-- CREATE POLICY posts_update ON app.posts FOR UPDATE TO authenticated
|
|
129
|
+
-- USING (app_authz.allowed(tenant_id, 'post', 'edit', owner_id))
|
|
130
|
+
-- WITH CHECK (app_authz.allowed(tenant_id, 'post', 'edit', owner_id));
|
|
131
|
+
-- CREATE POLICY posts_delete ON app.posts FOR DELETE TO authenticated
|
|
132
|
+
-- USING (app_authz.allowed(tenant_id, 'post', 'delete', owner_id));
|
|
133
|
+
-- CREATE TRIGGER posts_protect_scope BEFORE UPDATE ON app.posts
|
|
134
|
+
-- FOR EACH ROW EXECUTE FUNCTION app_authz.prevent_scope_reassignment('tenant_id', 'owner_id');
|
|
135
|
+
-- UPDATE requires this trigger: RLS WITH CHECK does not enforce immutability.
|
|
136
|
+
-- Composite foreign keys bind tenant roles, group assignments, and memberships
|
|
137
|
+
-- to the same tenant. Global roles require a separate deliberate policy.
|
|
138
|
+
-- Audit all privileged writes, RLS, revocation, and cross-tenant scenarios.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
-- RUNNABLE INTEGRATION EXAMPLE, not automatically installed as a migration.
|
|
2
|
+
-- Requires supabase-authorization.sql to be reviewed/applied first.
|
|
3
|
+
-- This demonstration table is separate from application tables: never run it
|
|
4
|
+
-- as a substitute for policies on real business resources.
|
|
5
|
+
create table if not exists public.authorization_example_posts (
|
|
6
|
+
id uuid primary key default gen_random_uuid(),
|
|
7
|
+
tenant_id uuid not null references app_authz.tenants(id),
|
|
8
|
+
owner_id uuid not null references auth.users(id),
|
|
9
|
+
body text not null
|
|
10
|
+
);
|
|
11
|
+
alter table public.authorization_example_posts enable row level security;
|
|
12
|
+
revoke all on public.authorization_example_posts from public, anon;
|
|
13
|
+
grant select, insert, update, delete on public.authorization_example_posts to authenticated;
|
|
14
|
+
|
|
15
|
+
create policy authorization_example_posts_select on public.authorization_example_posts
|
|
16
|
+
for select to authenticated using (
|
|
17
|
+
app_authz.allowed(tenant_id, 'post', 'read', owner_id)
|
|
18
|
+
);
|
|
19
|
+
create policy authorization_example_posts_insert on public.authorization_example_posts
|
|
20
|
+
for insert to authenticated with check (
|
|
21
|
+
owner_id = (select auth.uid())
|
|
22
|
+
and app_authz.allowed(tenant_id, 'post', 'create', owner_id)
|
|
23
|
+
);
|
|
24
|
+
create policy authorization_example_posts_update on public.authorization_example_posts
|
|
25
|
+
for update to authenticated using (
|
|
26
|
+
app_authz.allowed(tenant_id, 'post', 'edit', owner_id)
|
|
27
|
+
) with check (
|
|
28
|
+
app_authz.allowed(tenant_id, 'post', 'edit', owner_id)
|
|
29
|
+
);
|
|
30
|
+
create policy authorization_example_posts_delete on public.authorization_example_posts
|
|
31
|
+
for delete to authenticated using (
|
|
32
|
+
app_authz.allowed(tenant_id, 'post', 'delete', owner_id)
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
create trigger authorization_example_posts_protect_scope
|
|
36
|
+
before update on public.authorization_example_posts
|
|
37
|
+
for each row execute function app_authz.prevent_scope_reassignment('tenant_id', 'owner_id');
|
|
38
|
+
-- Required: test authenticated Supabase client reads/writes with identities in
|
|
39
|
+
-- separate tenants and verify denied reads, updates and changed owner/tenant.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Multi-tenancy integration
|
|
2
|
+
|
|
3
|
+
This project-owned helper validates tenant selection against a trusted membership list. It does not create organizations, membership CRUD, or schema enforcement.
|
|
4
|
+
|
|
5
|
+
1. Persist tenant memberships and tenant roles in backend-owned tables. Do not authorize from client-supplied membership lists.
|
|
6
|
+
2. Persist active tenant choice as a client preference only. Every backend request must independently validate membership and resource tenant association.
|
|
7
|
+
3. Supabase: bind each tenant-owned data table to memberships with RLS; prevent changing tenant IDs on existing rows.
|
|
8
|
+
4. Convex: scope queries and mutations by verified tenant membership and validate the resource's actual tenant before returning or changing it.
|
|
9
|
+
5. Membership management requires a verified tenant administrator; revocation must be effective at the data boundary.
|
|
10
|
+
|
|
11
|
+
Single-tenant applications need not install the `multi-tenancy` package.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Pure active-tenant selection. Memberships must come from server-owned data. */
|
|
2
|
+
export type TenantMembership = { tenantId: string; roleIds: readonly string[] };
|
|
3
|
+
|
|
4
|
+
export function resolveActiveTenant(
|
|
5
|
+
requestedTenantId: string | null,
|
|
6
|
+
memberships: readonly TenantMembership[],
|
|
7
|
+
): TenantMembership | null {
|
|
8
|
+
if (requestedTenantId === null) return null;
|
|
9
|
+
const membership = memberships.find((item) => item.tenantId === requestedTenantId);
|
|
10
|
+
if (!membership) throw new Error('Forbidden: tenant membership required');
|
|
11
|
+
return membership;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Persist selection only as a preference; always revalidate on every server request. */
|
|
15
|
+
export function getTenantMembership(
|
|
16
|
+
tenantId: string,
|
|
17
|
+
memberships: readonly TenantMembership[],
|
|
18
|
+
): TenantMembership {
|
|
19
|
+
const selected = resolveActiveTenant(tenantId, memberships);
|
|
20
|
+
if (!selected) throw new Error('Forbidden: tenant membership required');
|
|
21
|
+
return selected;
|
|
22
|
+
}
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
export type CheckerDiagnostic = {
|
|
2
|
+
path?: string;
|
|
3
|
+
line?: number;
|
|
4
|
+
column?: number;
|
|
5
|
+
message: string;
|
|
6
|
+
};
|
|
7
|
+
export declare function collectCheckerDiagnostics(output: {
|
|
8
|
+
stdout?: string;
|
|
9
|
+
stderr?: string;
|
|
10
|
+
}): CheckerDiagnostic[];
|
|
11
|
+
export declare function formatCheckerDiagnostics(diagnostics: CheckerDiagnostic[]): string;
|
|
1
12
|
export declare function runWithConcurrency<T, R>(items: T[], limit: number, worker: (item: T, index: number) => Promise<R>): Promise<R[]>;
|
|
2
13
|
export declare function canonicalCheck(projectRoot: string, source: any, options?: any): Promise<{
|
|
3
14
|
exitCode: number;
|
|
@@ -20,6 +31,7 @@ export declare function canonicalCheck(projectRoot: string, source: any, options
|
|
|
20
31
|
exitCode: any;
|
|
21
32
|
stdout: any;
|
|
22
33
|
stderr: any;
|
|
34
|
+
diagnostics: CheckerDiagnostic[];
|
|
23
35
|
}[];
|
|
24
36
|
versionProblems?: undefined;
|
|
25
37
|
}>;
|
|
@@ -7,6 +7,53 @@ import { readRuleProfile } from "./project-context.js";
|
|
|
7
7
|
import { loadCanonicalProjectContext, prepareCanonicalManifest } from "./project-runtime.js";
|
|
8
8
|
import { assertPredefinedPackageState } from "./predefined-packages/health.js";
|
|
9
9
|
import { readInstalledState, writeChecksState } from "./state.js";
|
|
10
|
+
function diagnosticFromLine(rawLine) {
|
|
11
|
+
const line = rawLine.trim().replace(/^-\s+/u, '');
|
|
12
|
+
if (!line || /^#\s/u.test(line) || /\b(?:ok|not applicable|not affected)$/iu.test(line))
|
|
13
|
+
return null;
|
|
14
|
+
const located = line.match(/^(.+?):(\d+)(?::(\d+))?(?::|\s)+(.*)$/u);
|
|
15
|
+
if (located) {
|
|
16
|
+
return {
|
|
17
|
+
path: located[1],
|
|
18
|
+
line: Number(located[2]),
|
|
19
|
+
...(located[3] ? { column: Number(located[3]) } : {}),
|
|
20
|
+
message: located[4],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const fileOnly = line.match(/^([^:]+\.[A-Za-z0-9]+):\s+(.+)$/u);
|
|
24
|
+
if (fileOnly)
|
|
25
|
+
return { path: fileOnly[1], message: fileOnly[2] };
|
|
26
|
+
return { message: line };
|
|
27
|
+
}
|
|
28
|
+
export function collectCheckerDiagnostics(output) {
|
|
29
|
+
const diagnostics = [];
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
for (const stream of [output.stdout ?? '', output.stderr ?? '']) {
|
|
32
|
+
for (const rawLine of stream.split(/\r?\n/u)) {
|
|
33
|
+
const diagnostic = diagnosticFromLine(rawLine);
|
|
34
|
+
if (!diagnostic)
|
|
35
|
+
continue;
|
|
36
|
+
const key = JSON.stringify(diagnostic);
|
|
37
|
+
if (!seen.has(key)) {
|
|
38
|
+
seen.add(key);
|
|
39
|
+
diagnostics.push(diagnostic);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return diagnostics;
|
|
44
|
+
}
|
|
45
|
+
export function formatCheckerDiagnostics(diagnostics) {
|
|
46
|
+
return diagnostics
|
|
47
|
+
.map((diagnostic) => {
|
|
48
|
+
if (!diagnostic.path)
|
|
49
|
+
return ` ${diagnostic.message}\n`;
|
|
50
|
+
const location = [diagnostic.path, diagnostic.line, diagnostic.column]
|
|
51
|
+
.filter((value) => value !== undefined)
|
|
52
|
+
.join(':');
|
|
53
|
+
return ` ${location}\n ${diagnostic.message}\n`;
|
|
54
|
+
})
|
|
55
|
+
.join('');
|
|
56
|
+
}
|
|
10
57
|
function execute(command, args, cwd) {
|
|
11
58
|
return new Promise((resolve, reject) => {
|
|
12
59
|
const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
@@ -150,7 +197,12 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
150
197
|
return { group, execution };
|
|
151
198
|
});
|
|
152
199
|
for (const { group, execution } of groupExecutions) {
|
|
153
|
-
const
|
|
200
|
+
const diagnostics = collectCheckerDiagnostics(execution);
|
|
201
|
+
const result = {
|
|
202
|
+
status: execution.exitCode === 0 ? 'pass' : 'fail',
|
|
203
|
+
...execution,
|
|
204
|
+
diagnostics,
|
|
205
|
+
};
|
|
154
206
|
for (const id of group.ids)
|
|
155
207
|
results[id] = result;
|
|
156
208
|
if (execution.exitCode !== 0)
|
|
@@ -173,6 +225,7 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
173
225
|
exitCode: execution.exitCode,
|
|
174
226
|
stdout: execution.stdout,
|
|
175
227
|
stderr: execution.stderr,
|
|
228
|
+
diagnostics: collectCheckerDiagnostics(execution),
|
|
176
229
|
})),
|
|
177
230
|
};
|
|
178
231
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specdest/devkit",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.19",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"specdest": "dist/npm/cli.js"
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"rules:audit": "node scripts/generate-rule-audit.mjs --check",
|
|
38
38
|
"rules:audit:write": "node scripts/generate-rule-audit.mjs",
|
|
39
39
|
"typecheck:checkers": "node scripts/typecheck-checkers.mjs",
|
|
40
|
-
"build": "node -e \"require('node:fs').rmSync('dist/npm',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
40
|
+
"build": "node -e \"require('node:fs').rmSync('dist/npm',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node scripts/copy-admin-ui-templates.mjs",
|
|
41
41
|
"prepack": "pnpm run build",
|
|
42
42
|
"format:check": "oxfmt --check src/*.ts",
|
|
43
43
|
"format": "oxfmt --write src/*.ts"
|