policy.ts 1.6 KB

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