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

main
ts 235 lines 9.31 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import { mainAccountId } from "@bank/domain/Account/Account.id";
3 import { agent, customer } from "@bank/domain/Actor";
4 import { Bank, BankHandlers } from "@bank/domain/Bank.model";
5 import { CustomerId } from "@bank/domain/Customer/Customer.id";
6 import { CustomerDashboard } from "@bank/domain/Customer/CustomerDashboard.view";
7 import { Username } from "@bank/domain/Customer/Username";
8 import { CustomerApi } from "@bank/domain/CustomerApi.api";
9 import { MemoryLedgerStore } from "@bank/domain/Ledger/LedgerStore";
10 import { sessionClient } from "@bank/domain/Session.middleware";
11 import { SupportApi } from "@bank/domain/SupportApi.api";
12 import { expect, it } from "@effect/vitest";
13 import * as Effect from "effect/Effect";
14 import * as Fiber from "effect/Fiber";
15 import * as Layer from "effect/Layer";
16 import type * as Scope from "effect/Scope";
17 import * as Stream from "effect/Stream";
18 import { SiftFraudCheck } from "../src/Fraud/SiftFraudCheck.ts";
19 import { MfaChallengeLive } from "../src/MfaChallenge.ts";
20 import { SessionLive, signSession } from "../src/Session.ts";
21 import { StripePayments } from "../src/Settlement/StripePayments.ts";
22 import { mfa, register, transfer } from "./flows.ts";
23 import { SessionKeyTest, signedInAs } from "./session.ts";
24
25 // The whole bank in one process: the same Layers the Worker uses, on the in-memory platform.
26 const Ports = Layer.mergeAll(SiftFraudCheck, StripePayments, MemoryLedgerStore);
27 const BankInMemory = Bank.layer(BankHandlers).pipe(
28 Layer.provide(Layer.mergeAll(Ports, Domain.InMemory)),
29 );
30 const World = Layer.mergeAll(SessionLive, MfaChallengeLive).pipe(
31 Layer.provideMerge(BankInMemory),
32 Layer.provideMerge(SessionKeyTest),
33 );
34
35 const asCustomer = (id: string) =>
36 CustomerApi.clientInProcess.pipe(Effect.provide(signedInAs(customer(id))));
37 const asAgent = (id: string) =>
38 SupportApi.clientInProcess.pipe(Effect.provide(signedInAs(agent(id))));
39
40 /** Each test gets a fresh bank. */
41 const inBank = <A, E>(effect: Effect.Effect<A, E, Scope.Scope | Layer.Success<typeof World>>) =>
42 effect.pipe(Effect.scoped, Effect.provide(World));
43
44 it.live("register, then the live dashboard shows the main account", () =>
45 inBank(
46 Effect.gen(function* () {
47 const sam = yield* asCustomer("c-1");
48 const accountId = yield* register(sam, "c-1", "sam");
49 expect(accountId).toBe(mainAccountId(CustomerId.make("c-1")));
50 const deposited = yield* sam.DepositMoney(accountId, { amount: 250 });
51 expect(deposited).toEqual({
52 reply: { balance: 250 },
53 stream: `Account/${accountId}`,
54 version: 2,
55 });
56 const dashboard = yield* sam.CustomerDashboard.watch(CustomerId.make("c-1")).pipe(
57 Stream.map(({ state }) => state),
58 Stream.filter((d) => d !== null && CustomerDashboard.computed.totalBalance(d) === 250),
59 Stream.runHead,
60 );
61 expect(dashboard).toMatchObject({ _tag: "Some", value: { name: "sam" } });
62 }),
63 ),
64 );
65
66 it.live("withdrawing needs MFA, and only the owner may withdraw", () =>
67 inBank(
68 Effect.gen(function* () {
69 const sam = yield* asCustomer("c-1");
70 const alex = yield* asCustomer("c-2");
71 const accountId = yield* register(sam, "c-1", "sam");
72 yield* sam.DepositMoney(accountId, { amount: 100 });
73
74 const noMfa = yield* sam.WithdrawMoney(accountId, { amount: 10 }).pipe(Effect.flip);
75 expect(noMfa._tag).toBe("MfaRequired");
76
77 const withdrawn = yield* sam.WithdrawMoney(accountId, { amount: 10 }, mfa);
78 expect(withdrawn.reply).toEqual({ balance: 90 });
79
80 const stolen = yield* alex.WithdrawMoney(accountId, { amount: 10 }, mfa).pipe(Effect.flip);
81 expect(stolen._tag).toBe("NotOwner");
82 }),
83 ),
84 );
85
86 it.live("a view is a security boundary: owners and agents read it, others are rejected", () =>
87 inBank(
88 Effect.gen(function* () {
89 const sam = yield* asCustomer("c-1");
90 const alex = yield* asCustomer("c-2");
91 const support = yield* asAgent("support-7");
92 const accountId = yield* register(sam, "c-1", "sam");
93 const receipt = yield* sam.DepositMoney(accountId, { amount: 40 });
94 const atLeast = { stream: receipt.stream, version: receipt.version };
95
96 expect(yield* sam.AccountSummary.get(accountId, { atLeast })).toMatchObject({ balance: 40 });
97 expect((yield* alex.AccountSummary.get(accountId).pipe(Effect.flip))._tag).toBe("NotOwner");
98 expect(yield* support.AccountSummary.get(accountId)).toMatchObject({ balance: 40 });
99 // A filter only narrows what a permitted read returns.
100 expect(
101 yield* sam.AccountSummary.get(accountId, { atLeast, where: { balance: { gt: 100 } } }),
102 ).toBeNull();
103 expect(
104 (yield* alex.CustomerDashboard.get(CustomerId.make("c-1")).pipe(Effect.flip))._tag,
105 ).toBe("Forbidden");
106 }),
107 ),
108 );
109
110 it.live("a customer watches their account's own events; others are rejected", () =>
111 inBank(
112 Effect.gen(function* () {
113 const sam = yield* asCustomer("c-1");
114 const alex = yield* asCustomer("c-2");
115 const accountId = yield* register(sam, "c-1", "sam");
116 yield* sam.DepositMoney(accountId, { amount: 70 });
117
118 const events = yield* sam.Account.events(accountId).pipe(
119 Stream.filter(Domain.Read.isEvent),
120 Stream.take(2),
121 Stream.runCollect,
122 );
123 expect(events.map((e) => e.event._tag)).toEqual(["AccountOpened", "MoneyDeposited"]);
124 expect((yield* sam.Account.get(accountId))._tag).toBe("Open");
125 expect((yield* alex.Account.get(accountId).pipe(Effect.flip))._tag).toBe("NotOwner");
126 }),
127 ),
128 );
129
130 it.live("a customer can only register themselves", () =>
131 inBank(
132 Effect.gen(function* () {
133 const sam = yield* asCustomer("c-1");
134 const error = yield* sam
135 .RegisterCustomer(CustomerId.make("c-2"), {
136 name: "not sam",
137 username: Username.make("not-sam"),
138 })
139 .pipe(Effect.flip);
140 expect(error._tag).toBe("NotTheCustomer");
141 }),
142 ),
143 );
144
145 it.live("a request without a session is unauthorized", () =>
146 inBank(
147 Effect.gen(function* () {
148 const anonymous = yield* CustomerApi.clientInProcess.pipe(
149 Effect.provide(sessionClient("nobody")),
150 );
151 const error = yield* anonymous
152 .RegisterCustomer(CustomerId.make("c-1"), { name: "x", username: Username.make("x") })
153 .pipe(Effect.flip);
154 expect(error._tag).toBe("Unauthorized");
155 }),
156 ),
157 );
158
159 it.live("a session the bank didn't sign is unauthorized", () =>
160 inBank(
161 Effect.gen(function* () {
162 const register = (token: string) =>
163 CustomerApi.clientInProcess.pipe(
164 Effect.provide(sessionClient(token)),
165 Effect.flatMap((client) =>
166 client.RegisterCustomer(CustomerId.make("c-1"), {
167 name: "x",
168 username: Username.make("x"),
169 }),
170 ),
171 Effect.flip,
172 );
173 // A bare actor, as the demo session used to accept.
174 expect((yield* register("customer:c-1"))._tag).toBe("Unauthorized");
175 // A real token for c-2, edited to claim c-1 without re-signing.
176 const real = yield* signSession(customer("c-2"));
177 const [claims, mac] = real.split(".");
178 const forged = Buffer.from(
179 Buffer.from(claims!, "base64url").toString().replace("c-2", "c-1"),
180 ).toString("base64url");
181 expect((yield* register(`${forged}.${mac}`))._tag).toBe("Unauthorized");
182 }),
183 ),
184 );
185
186 it.live(
187 "a transfer completes; the requester follows its status, the recipient sees it arrive",
188 () =>
189 inBank(
190 Effect.gen(function* () {
191 const sam = yield* asCustomer("c-1");
192 const alex = yield* asCustomer("c-2");
193 const from = yield* register(sam, "c-1", "sam");
194 const to = yield* register(alex, "c-2", "alex");
195 yield* sam.DepositMoney(from, { amount: 100 });
196
197 const outcome = yield* transfer(sam, { transferId: "t-1", from, to, amount: 40 });
198 expect(outcome.status).toBe("completed");
199 // The status is the requester's; the recipient follows their own account.
200 expect((yield* alex.TransferStatus.get(outcome.transferId).pipe(Effect.flip))._tag).toBe(
201 "NotOwner",
202 );
203 const incoming = yield* alex.AccountTransfers.list(to);
204 expect(incoming.entries.map((e) => e.event.direction)).toEqual(["in"]);
205
206 const page = yield* sam.Statement.list(from, { order: "desc" });
207 expect(page.entries.map((e) => e.event.kind)).toEqual(["transfer-out", "deposit"]);
208 }),
209 ),
210 );
211
212 it.live("a watch ends with NotOwner when support reassigns the account", () =>
213 inBank(
214 Effect.gen(function* () {
215 const sam = yield* asCustomer("c-1");
216 const alex = yield* asCustomer("c-2");
217 const support = yield* asAgent("support-7");
218 const accountId = yield* register(sam, "c-1", "sam");
219 yield* register(alex, "c-2", "alex");
220
221 const updates = yield* sam.AccountSummary.watch(accountId).pipe(
222 Stream.result,
223 Stream.take(2),
224 Stream.runCollect,
225 Effect.forkChild,
226 );
227 yield* Effect.sleep("50 millis");
228 yield* support.ChangeOwner(accountId, { customerId: CustomerId.make("c-2") });
229
230 const [first, second] = yield* Fiber.join(updates);
231 expect(first).toMatchObject({ _tag: "Success", success: { state: { balance: 0 } } });
232 expect(second).toMatchObject({ _tag: "Failure", failure: { _tag: "NotOwner" } });
233 }),
234 ),
235 );