1import * as AVP from "@distilled.cloud/aws/verifiedpermissions";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Binding from "../../Binding.ts";
5import { isBindingHost } from "../Lambda/Function.ts";
6import {
7 type BatchIsAuthorizedRequest,
8 type BatchIsAuthorizedWithTokenRequest,
9 IsAuthorized,
10 type IsAuthorizedRequest,
11 type IsAuthorizedWithTokenRequest,
12} from "./IsAuthorized.ts";
13import type { PolicyStore } from "./PolicyStore.ts";
14
15export const IsAuthorizedHttp = Layer.effect(
16 IsAuthorized,
17 Effect.gen(function* () {
18 const isAuthorized = yield* AVP.isAuthorized;
19 const isAuthorizedWithToken = yield* AVP.isAuthorizedWithToken;
20 const batchIsAuthorized = yield* AVP.batchIsAuthorized;
21 const batchIsAuthorizedWithToken = yield* AVP.batchIsAuthorizedWithToken;
22
23 return Effect.fn(function* <S extends PolicyStore>(store: S) {
24 const PolicyStoreId = yield* store.policyStoreId;
25 if (!globalThis.__ALCHEMY_RUNTIME__) {
26 const host = yield* Binding.Host;
27 if (isBindingHost(host)) {
28 yield* host.bind`Allow(${host}, AWS.VerifiedPermissions.IsAuthorized(${store}))`(
29 {
30 policyStatements: [
31 {
32 Effect: "Allow",
33 // the batch operations authorize under the non-batch
34 // verifiedpermissions:IsAuthorized[WithToken] actions
35 Action: [
36 "verifiedpermissions:IsAuthorized",
37 "verifiedpermissions:IsAuthorizedWithToken",
38 "verifiedpermissions:BatchIsAuthorized",
39 "verifiedpermissions:BatchIsAuthorizedWithToken",
40 ],
41 Resource: [store.policyStoreArn],
42 },
43 ],
44 },
45 );
46 }
47 }
48 const label = store.LogicalId;
49 return {
50 isAuthorized: Effect.fn(
51 `AWS.VerifiedPermissions.IsAuthorized(${label})`,
52 )(function* (request: IsAuthorizedRequest) {
53 const policyStoreId = yield* PolicyStoreId;
54 return yield* isAuthorized({ ...request, policyStoreId });
55 }),
56 isAuthorizedWithToken: Effect.fn(
57 `AWS.VerifiedPermissions.IsAuthorizedWithToken(${label})`,
58 )(function* (request: IsAuthorizedWithTokenRequest) {
59 const policyStoreId = yield* PolicyStoreId;
60 return yield* isAuthorizedWithToken({ ...request, policyStoreId });
61 }),
62 batchIsAuthorized: Effect.fn(
63 `AWS.VerifiedPermissions.BatchIsAuthorized(${label})`,
64 )(function* (request: BatchIsAuthorizedRequest) {
65 const policyStoreId = yield* PolicyStoreId;
66 return yield* batchIsAuthorized({ ...request, policyStoreId });
67 }),
68 batchIsAuthorizedWithToken: Effect.fn(
69 `AWS.VerifiedPermissions.BatchIsAuthorizedWithToken(${label})`,
70 )(function* (request: BatchIsAuthorizedWithTokenRequest) {
71 const policyStoreId = yield* PolicyStoreId;
72 return yield* batchIsAuthorizedWithToken({
73 ...request,
74 policyStoreId,
75 });
76 }),
77 };
78 });
79 }),
80);