policy.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export * as Policy from "./policy"
  2. import { Context, Effect as EffectRuntime, Layer, Schema } from "effect"
  3. import { Wildcard } from "./util/wildcard"
  4. import { Location } from "./location"
  5. export const Effect = Schema.Literals(["allow", "deny"]).annotate({ identifier: "Policy.Effect" })
  6. export type Effect = typeof Effect.Type
  7. export class Info extends Schema.Class<Info>("Policy.Info")({
  8. action: Schema.String,
  9. effect: Effect,
  10. resource: Schema.String,
  11. }) {}
  12. export interface Interface {
  13. readonly load: (statements: Info[]) => EffectRuntime.Effect<void>
  14. readonly evaluate: (action: string, resource: string, fallback: Effect) => EffectRuntime.Effect<Effect>
  15. readonly hasStatements: () => boolean
  16. }
  17. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Policy") {}
  18. export const layer = Layer.effect(
  19. Service,
  20. EffectRuntime.gen(function* () {
  21. let statements: Info[] = []
  22. yield* Location.Service
  23. return Service.of({
  24. load: EffectRuntime.fn("Policy.load")(function* (input) {
  25. statements = input
  26. }),
  27. hasStatements: () => statements.length > 0,
  28. evaluate: EffectRuntime.fn("Policy.evaluate")(function* (action, resource, fallback) {
  29. return (
  30. statements.findLast(
  31. (statement) => Wildcard.match(action, statement.action) && Wildcard.match(resource, statement.resource),
  32. )?.effect ?? fallback
  33. )
  34. }),
  35. })
  36. }),
  37. )
  38. export const locationLayer = layer