@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 262 lines 10.7 KB
Raw
1 import * as IoTManagedIntegrations from "@alchemy.run/aws/IoTManagedIntegrations";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "bindings-handler.ts");
12
13 // Same synthetic Zigbee install-code QR payload the ManagedThing lifecycle
14 // test uses — CreateManagedThing validates the payload shape, not that the
15 // device exists. Checked in as a constant (never generated at test time).
16 const ZIGBEE_QR_PAYLOAD = "Z:24FD5B0000015C63$I:83FED3407A939738";
17
18 export class IoTMITestFunction extends Lambda.Function<Lambda.Function>()("IoTMITestFunction") {}
19
20 /**
21 * Every route answers `{ …fields }` on success or `{ errorTag }` when the
22 * operation fails with a TYPED error. The gated test asserts concrete fields
23 * where the API can succeed against an unprovisioned device, and asserts the
24 * tag is typed-and-not-AccessDenied elsewhere — which proves the binding
25 * wiring, the identifier injection, and the IAM grants.
26 */
27 const errorTagged = <A, E extends { _tag: string }, R>(
28 effect: Effect.Effect<A, E, R>,
29 ): Effect.Effect<A | { errorTag: string }, never, R> =>
30 effect.pipe(
31 Effect.map((a): A | { errorTag: string } => a),
32 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
33 );
34
35 /**
36 * Bindings fixture: a credential locker + an (unprovisioned) Zigbee DEVICE
37 * managed thing, and a Lambda bound to every IoT Managed Integrations
38 * runtime binding. Deployed only by the gated Bindings test (the service
39 * exists in a handful of regions).
40 */
41 export default IoTMITestFunction.make(
42 {
43 main,
44 functionUrl: true,
45 timeout: Duration.seconds(30),
46 },
47 Effect.gen(function* () {
48 const locker = yield* IoTManagedIntegrations.CredentialLocker("Locker", {});
49 const thing = yield* IoTManagedIntegrations.ManagedThing("Device", {
50 role: "DEVICE",
51 authenticationMaterial: Redacted.make(ZIGBEE_QR_PAYLOAD),
52 authenticationMaterialType: "ZIGBEE_QR_BAR_CODE",
53 credentialLockerId: locker.credentialLockerId,
54 serialNumber: "SN-ALCHEMY-BINDINGS-0001",
55 tags: { fixture: "iot-mi-bindings" },
56 });
57
58 const sendCommand = yield* IoTManagedIntegrations.SendManagedThingCommand(thing);
59 const getState = yield* IoTManagedIntegrations.GetManagedThingState(thing);
60 const getCapabilities = yield* IoTManagedIntegrations.GetManagedThingCapabilities(thing);
61 const getCertificate = yield* IoTManagedIntegrations.GetManagedThingCertificate(thing);
62 const getConnectivity = yield* IoTManagedIntegrations.GetManagedThingConnectivityData(thing);
63 const getMetaData = yield* IoTManagedIntegrations.GetManagedThingMetaData(thing);
64 const listThingSchemas = yield* IoTManagedIntegrations.ListManagedThingSchemas(thing);
65 const startDiscovery = yield* IoTManagedIntegrations.StartDeviceDiscovery();
66 const getDiscovery = yield* IoTManagedIntegrations.GetDeviceDiscovery();
67 const listDiscoveries = yield* IoTManagedIntegrations.ListDeviceDiscoveries();
68 const listDiscovered = yield* IoTManagedIntegrations.ListDiscoveredDevices();
69 const getSchemaVersion = yield* IoTManagedIntegrations.GetSchemaVersion();
70 const listSchemaVersions = yield* IoTManagedIntegrations.ListSchemaVersions();
71 const getCustomEndpoint = yield* IoTManagedIntegrations.GetCustomEndpoint();
72 const sendConnectorEvent = yield* IoTManagedIntegrations.SendConnectorEvent();
73
74 const bound = {
75 sendCommand,
76 getState,
77 getCapabilities,
78 getCertificate,
79 getConnectivity,
80 getMetaData,
81 listThingSchemas,
82 startDiscovery,
83 getDiscovery,
84 listDiscoveries,
85 listDiscovered,
86 getSchemaVersion,
87 listSchemaVersions,
88 getCustomEndpoint,
89 sendConnectorEvent,
90 };
91
92 return {
93 fetch: Effect.gen(function* () {
94 const request = yield* HttpServerRequest;
95 const url = new URL(request.originalUrl);
96 const pathname = url.pathname;
97
98 if (pathname === "/bindings") {
99 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
100 }
101
102 // -- account-level ops (Resource "*") ------------------------------
103 if (pathname === "/schema-versions") {
104 const result = yield* errorTagged(
105 listSchemaVersions({ Type: "capability", MaxResults: 3 }),
106 );
107 return yield* HttpServerResponse.json(
108 "errorTag" in result
109 ? result
110 : {
111 count: (result.Items ?? []).length,
112 first: result.Items?.[0],
113 },
114 );
115 }
116 if (pathname === "/schema-version") {
117 const id = url.searchParams.get("id") ?? "";
118 const result = yield* errorTagged(
119 getSchemaVersion({ Type: "capability", SchemaVersionedId: id }),
120 );
121 return yield* HttpServerResponse.json(
122 "errorTag" in result ? result : { schemaId: result.SchemaId },
123 );
124 }
125 if (pathname === "/custom-endpoint") {
126 const result = yield* errorTagged(getCustomEndpoint());
127 return yield* HttpServerResponse.json(
128 "errorTag" in result ? result : { endpointAddress: result.EndpointAddress },
129 );
130 }
131 if (pathname === "/discovery") {
132 // No live controller in the fixture — expect a TYPED rejection
133 // (never AccessDenied), which still proves wiring + IAM.
134 const result = yield* errorTagged(
135 startDiscovery({
136 DiscoveryType: "ZWAVE",
137 ControllerIdentifier: "alchemy-nonexistent-controller",
138 }),
139 );
140 return yield* HttpServerResponse.json("errorTag" in result ? result : { id: result.Id });
141 }
142 if (pathname === "/discoveries") {
143 const result = yield* errorTagged(listDiscoveries({ StatusFilter: "RUNNING" }));
144 return yield* HttpServerResponse.json(
145 "errorTag" in result ? result : { count: (result.Items ?? []).length },
146 );
147 }
148 if (pathname === "/get-discovery") {
149 const result = yield* errorTagged(
150 getDiscovery({ Identifier: "alchemynonexistentdiscovery" }),
151 );
152 return yield* HttpServerResponse.json(
153 "errorTag" in result ? result : { status: result.Status },
154 );
155 }
156 if (pathname === "/discovered") {
157 const result = yield* errorTagged(
158 listDiscovered({ Identifier: "alchemynonexistentdiscovery" }),
159 );
160 return yield* HttpServerResponse.json(
161 "errorTag" in result ? result : { count: (result.Items ?? []).length },
162 );
163 }
164 if (pathname === "/connector-event") {
165 const result = yield* errorTagged(
166 sendConnectorEvent({
167 ConnectorId: "alchemynonexistentconnector",
168 Operation: "DEVICE_EVENT",
169 }),
170 );
171 return yield* HttpServerResponse.json(
172 "errorTag" in result ? result : { connectorId: result.ConnectorId },
173 );
174 }
175
176 // -- managed-thing-scoped ops (grant on the thing ARN) --------------
177 if (pathname === "/metadata") {
178 const result = yield* errorTagged(getMetaData());
179 return yield* HttpServerResponse.json(
180 "errorTag" in result ? result : { managedThingId: result.ManagedThingId },
181 );
182 }
183 if (pathname === "/capabilities") {
184 const result = yield* errorTagged(getCapabilities());
185 return yield* HttpServerResponse.json(
186 "errorTag" in result ? result : { managedThingId: result.ManagedThingId },
187 );
188 }
189 if (pathname === "/certificate") {
190 const result = yield* errorTagged(getCertificate());
191 return yield* HttpServerResponse.json(
192 "errorTag" in result ? result : { hasPem: result.CertificatePem !== undefined },
193 );
194 }
195 if (pathname === "/connectivity") {
196 const result = yield* errorTagged(getConnectivity());
197 return yield* HttpServerResponse.json(
198 "errorTag" in result ? result : { connected: result.Connected },
199 );
200 }
201 if (pathname === "/state") {
202 const result = yield* errorTagged(getState());
203 return yield* HttpServerResponse.json(
204 "errorTag" in result ? result : { endpoints: result.Endpoints.length },
205 );
206 }
207 if (pathname === "/thing-schemas") {
208 const result = yield* errorTagged(listThingSchemas());
209 return yield* HttpServerResponse.json(
210 "errorTag" in result ? result : { count: (result.Items ?? []).length },
211 );
212 }
213 if (pathname === "/command") {
214 // Unprovisioned device — expect a TYPED rejection (never
215 // AccessDenied), which still proves wiring + IAM.
216 const result = yield* errorTagged(
217 sendCommand({
218 Endpoints: [
219 {
220 endpointId: "1",
221 capabilities: [
222 {
223 id: "aws.OnOff",
224 name: "On/Off",
225 version: "1",
226 actions: [{ name: "activate" }],
227 },
228 ],
229 },
230 ],
231 }),
232 );
233 return yield* HttpServerResponse.json(
234 "errorTag" in result ? result : { traceId: result.TraceId },
235 );
236 }
237
238 return yield* HttpServerResponse.json({ error: "Not found", pathname }, { status: 404 });
239 }).pipe(Effect.orDie),
240 };
241 }).pipe(
242 Effect.provide(
243 Layer.mergeAll(
244 IoTManagedIntegrations.SendManagedThingCommandHttp,
245 IoTManagedIntegrations.GetManagedThingStateHttp,
246 IoTManagedIntegrations.GetManagedThingCapabilitiesHttp,
247 IoTManagedIntegrations.GetManagedThingCertificateHttp,
248 IoTManagedIntegrations.GetManagedThingConnectivityDataHttp,
249 IoTManagedIntegrations.GetManagedThingMetaDataHttp,
250 IoTManagedIntegrations.ListManagedThingSchemasHttp,
251 IoTManagedIntegrations.StartDeviceDiscoveryHttp,
252 IoTManagedIntegrations.GetDeviceDiscoveryHttp,
253 IoTManagedIntegrations.ListDeviceDiscoveriesHttp,
254 IoTManagedIntegrations.ListDiscoveredDevicesHttp,
255 IoTManagedIntegrations.GetSchemaVersionHttp,
256 IoTManagedIntegrations.ListSchemaVersionsHttp,
257 IoTManagedIntegrations.GetCustomEndpointHttp,
258 IoTManagedIntegrations.SendConnectorEventHttp,
259 ),
260 ),
261 ),
262 );