-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.ts
More file actions
53 lines (47 loc) · 1.6 KB
/
plugin.ts
File metadata and controls
53 lines (47 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// SPDX-FileCopyrightText: 2024 Dyne.org foundation
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Plugin } from '@slangroom/core';
import { HTTP } from "@cerbos/http";
// read the version from the package.json
import packageJson from '@slangroom/cerbos/package.json' with { type: 'json' };
import { actionSchema, principalSchema, resourceSchema } from './types.js';
export const version = packageJson.version;
export class CerbosError extends Error {
constructor(message: string) {
super(message);
this.name = 'Slangroom @slangroom/cerbos@' + packageJson.version + ' Error';
}
};
const p = new Plugin();
/**
* @internal
*/
export const allowed = p.new('connect',
['principal', 'resource', 'action'],
'evaluate access',
async (ctx) => {
const cerbosUrl = ctx.fetchConnect()[0];
const { success: principalIsValid, data: principal } = principalSchema.safeParse(ctx.fetch("principal"));
if (!principalIsValid)
return ctx.fail(new CerbosError("Principal is not valid"));
const { success: resourceIsValid, data: resource } = resourceSchema.safeParse(ctx.fetch("resource"));
if (!resourceIsValid)
return ctx.fail(new CerbosError("Resource is not valid"));
const { success: actionIsValid, data: action } = actionSchema.safeParse(ctx.fetch("action"));
if (!actionIsValid)
return ctx.fail(new CerbosError("Action is not valid"));
try {
const cerbos = new HTTP(cerbosUrl);
const result = await cerbos.isAllowed({
principal,
resource,
action,
});
return ctx.pass(result);
} catch (e) {
return ctx.fail(new CerbosError(e.message));
}
}
)
export const cerbos = p;