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

main
mdx 229 lines 8.47 KB
Raw
1 ---
2 title: Views as security boundaries
3 description: Decide who may read each view, keep watches honest as data changes hands, and give each audience a view of its own.
4 ---
5
6 A view is a security boundary, like a command. Its `validate` decides whether the person asking may read the key they asked for, on every read and on every change while they watch.
7
8 ## Write the rule once
9
10 Write who may read an account's data as one function, and use it in every view of an account.
11
12 ```typescript
13 // packages/domain/src/Account/mustOwn.ts
14 import * as Effect from "effect/Effect";
15 import { CurrentActor } from "../CurrentActor.context.ts";
16 import type { CustomerId } from "../Customer/Customer.id.ts";
17 import { NotOwner } from "./NotOwner.rejection.ts";
18
19 /**
20 * Who may read an account's data: any agent, or the customer who owns the
21 * account right now. An account that doesn't exist yet reads as empty, so a
22 * client can watch for it to appear; someone else's is rejected.
23 */
24 export const mustOwn = Effect.fn(function* (owner: CustomerId | null) {
25 const actor = yield* CurrentActor;
26 if (actor._tag === "Agent" || owner === null) return;
27 if (actor._tag !== "Customer" || owner !== actor.customerId) return yield* new NotOwner();
28 });
29 ```
30
31 `validate` gets the request and the key's state. It succeeds to allow the read, or fails with a rejection the view declares.
32
33 ```typescript
34 // packages/domain/src/Account/AccountSummary.view.ts
35 import * as Domain from "@alchemy.run/domain";
36 import * as Effect from "effect/Effect";
37 import * as Schema from "effect/Schema";
38 import { CustomerId } from "../Customer/Customer.id.ts";
39 import { Cents } from "../Money.ts";
40 import { Session } from "../Session.middleware.ts";
41 import { Account } from "./Account.aggregate.ts";
42 import { mustOwn } from "./mustOwn.ts";
43 import { NotOwner } from "./NotOwner.rejection.ts";
44
45 const setBalance = <V extends { balance: number }>(
46 v: V,
47 e: { readonly balanceAfter: number },
48 ): V => ({
49 ...v,
50 balance: e.balanceAfter,
51 });
52
53 /**
54 * The current balance and status of one account. It declares no events, so
55 * it emits every event it applies, each with the summary after it.
56 */
57 export class AccountSummary extends Domain.View("AccountSummary", {
58 from: [Account],
59 key: Account,
60 middleware: [Session],
61 rejects: [NotOwner],
62 state: Schema.Struct({
63 customerId: Schema.NullOr(CustomerId),
64 owner: Schema.NullOr(Schema.String),
65 balance: Cents,
66 frozen: Schema.Boolean,
67 closed: Schema.Boolean,
68 }),
69 initial: { customerId: null, owner: null, balance: 0, frozen: false, closed: false },
70 evolve: {
71 AccountOpened: (v, e) => ({ ...v, customerId: e.customerId, owner: e.owner }),
72 OwnerChanged: (v, e) => ({ ...v, customerId: e.customerId }),
73 MoneyDeposited: setBalance,
74 MoneyWithdrawn: setBalance,
75 TransferDebited: setBalance,
76 TransferCredited: setBalance,
77 TransferRefunded: setBalance,
78 SettlementReceived: setBalance,
79 AccountFrozen: (v) => ({ ...v, frozen: true }),
80 AccountClosed: (v) => ({ ...v, closed: true }),
81 },
82 // Re-run on every change while watched: a reassigned account ends the watch with NotOwner.
83 validate: Effect.fn(function* (_request, summary) {
84 yield* mustOwn(summary?.customerId ?? null);
85 }),
86 }) {}
87 ```
88
89 The `Account` aggregate's `read` contract and the `Statement` view use the same rule, so the account reads the same everywhere.
90
91 ## Rule by key
92
93 When the key itself says whose data it is, judge the key. A dashboard is keyed by customer, so only that customer, or an agent, may read it.
94
95 ```typescript
96 // packages/domain/src/Customer/CustomerDashboard.view.ts
97 import * as Domain from "@alchemy.run/domain";
98 import * as Effect from "effect/Effect";
99 import * as Schema from "effect/Schema";
100 import { AccountId } from "../Account/Account.id.ts";
101 import { AccountSummary } from "../Account/AccountSummary.view.ts";
102 import { CurrentActor } from "../CurrentActor.context.ts";
103 import { Forbidden } from "../Forbidden.rejection.ts";
104 import { Cents } from "../Money.ts";
105 import { Session } from "../Session.middleware.ts";
106 import { Customer } from "./Customer.aggregate.ts";
107
108 type Balances = Readonly<Record<AccountId, number>>;
109
110 const without = (balances: Balances, id: AccountId): Balances => {
111 const { [id]: _removed, ...rest } = balances;
112 return rest;
113 };
114
115 /**
116 * A customer's accounts and balances, built from AccountSummary's events and
117 * the summary after each. An ownership change moves the account between
118 * dashboards.
119 */
120 export class CustomerDashboard extends Domain.View("CustomerDashboard", {
121 from: [Customer, AccountSummary],
122 key: Customer,
123 middleware: [Session],
124 rejects: [Forbidden],
125 keyOf: {
126 AccountSummary: ({ state }) => (state?.customerId ? Customer.ref(state.customerId) : undefined),
127 OwnerChanged: {
128 previous: ({ event }) => Customer.ref(event.previous),
129 current: ({ event }) => Customer.ref(event.customerId),
130 },
131 },
132 state: Schema.Struct({
133 name: Schema.NullOr(Schema.String),
134 balances: Schema.Record(AccountId, Cents),
135 }),
136 initial: { name: null, balances: {} },
137 evolve: {
138 CustomerRegistered: (d, e) => ({ ...d, name: e.name }),
139 OwnerChanged: {
140 previous: (d, _, { source }) => ({ ...d, balances: without(d.balances, source.id) }),
141 current: (d, _, { source, state }) => ({
142 ...d,
143 balances: { ...d.balances, [source.id]: state?.balance ?? 0 },
144 }),
145 },
146 AccountSummary: (d, _, { source, state }) => ({
147 ...d,
148 balances:
149 state && !state.closed
150 ? { ...d.balances, [source.id]: state.balance }
151 : without(d.balances, source.id),
152 }),
153 },
154 // Keyed by customer, so the key alone decides who may read it.
155 validate: Effect.fn(function* (request) {
156 const actor = yield* CurrentActor;
157 if (actor._tag === "Agent") return;
158 if (actor._tag !== "Customer" || request.key.id !== actor.customerId) {
159 return yield* new Forbidden({ reason: "that is not your dashboard" });
160 }
161 }),
162 computed: {
163 totalBalance: (d) => Object.values<number>(d.balances).reduce((a, b) => a + b, 0),
164 },
165 }) {}
166 ```
167
168 ## Give each audience its own view
169
170 A view decides who may read it, not which parts they may see. To show an audience different data, make another view. Support agents see an account's operational events; customers can't read them at all.
171
172 ```typescript
173 // packages/domain/src/Account/AccountActivity.view.ts
174 import * as Domain from "@alchemy.run/domain";
175 import * as Effect from "effect/Effect";
176 import { CurrentActor } from "../CurrentActor.context.ts";
177 import { Forbidden } from "../Forbidden.rejection.ts";
178 import { Session } from "../Session.middleware.ts";
179 import { Account } from "./Account.aggregate.ts";
180 import { OwnerChanged } from "./ChangeOwner.command.ts";
181 import { AccountClosed } from "./CloseAccount.command.ts";
182 import { AccountFrozen } from "./FreezeAccount.command.ts";
183 import { SettlementOnClosedAccount } from "./RecordSettlement.command.ts";
184 import { RefundStranded } from "./RefundTransfer.command.ts";
185
186 /** Operational events for support tooling, passed through unchanged. Agents only. */
187 export class AccountActivity extends Domain.View("AccountActivity", {
188 from: [Account],
189 key: Account,
190 middleware: [Session],
191 rejects: [Forbidden],
192 validate: Effect.fn(function* (request) {
193 const actor = yield* CurrentActor;
194 if (actor._tag !== "Agent") {
195 return yield* new Forbidden({ reason: `${request.mode} of account activity is for agents` });
196 }
197 }),
198 events: [AccountFrozen, AccountClosed, OwnerChanged, RefundStranded, SettlementOnClosedAccount],
199 }) {}
200 ```
201
202 Expose it in the agents' Api only.
203
204 ```typescript
205 // packages/domain/src/SupportApi.api.ts
206 import * as Domain from "@alchemy.run/domain";
207 import { Bank } from "./Bank.model.ts";
208
209 /** What the support console reaches, over the same Bank. */
210 export class SupportApi extends Domain.Api("SupportApi", {
211 model: Bank,
212 commands: ["FreezeAccount", "ChangeOwner", "ApproveTransfer"],
213 views: ["AccountSummary", "AccountActivity"],
214 streams: [],
215 aggregates: [],
216 }) {}
217 ```
218
219 ## Re-check every change
220
221 `validate` runs again on every change while a client watches. When support moves an account to another customer, the old owner's watch ends with `NotOwner` at that change. See the test in [Testing an Api](/domain/testing-apis#test-in-process).
222
223 ## Filter only what's allowed
224
225 A client's `where` filter narrows a read it's already allowed to make, and never grants one. `validate` doesn't look at filters, so a filter can't widen what someone sees.
226
227 :::note
228 Authenticate the person asking with [Sessions and middleware](/domain/sessions).
229 :::