@adaptic/backend 0.0.1038 → 0.0.1039

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/esm/auth/credential-fields.d.ts +19 -0
  2. package/esm/auth/credential-fields.d.ts.map +1 -0
  3. package/esm/auth/credential-fields.js.map +1 -0
  4. package/esm/auth/credential-fields.mjs +42 -0
  5. package/esm/auth/credential-redaction.d.ts +56 -0
  6. package/esm/auth/credential-redaction.d.ts.map +1 -0
  7. package/esm/auth/credential-redaction.js.map +1 -0
  8. package/esm/auth/credential-redaction.mjs +99 -0
  9. package/esm/auth/mutation-authorization.d.ts +206 -0
  10. package/esm/auth/mutation-authorization.d.ts.map +1 -0
  11. package/esm/auth/mutation-authorization.js.map +1 -0
  12. package/esm/auth/mutation-authorization.mjs +271 -0
  13. package/esm/auth/nested-write-inspector.d.ts +94 -0
  14. package/esm/auth/nested-write-inspector.d.ts.map +1 -0
  15. package/esm/auth/nested-write-inspector.js.map +1 -0
  16. package/esm/auth/nested-write-inspector.mjs +185 -0
  17. package/esm/auth/nested-write-policy.d.ts +95 -0
  18. package/esm/auth/nested-write-policy.d.ts.map +1 -0
  19. package/esm/auth/nested-write-policy.js.map +1 -0
  20. package/esm/auth/nested-write-policy.mjs +154 -0
  21. package/esm/auth/service-token.d.ts +11 -1
  22. package/esm/auth/service-token.d.ts.map +1 -1
  23. package/esm/auth/service-token.js.map +1 -1
  24. package/esm/auth/service-token.mjs +31 -5
  25. package/esm/auth/token-verifier.d.ts +9 -1
  26. package/esm/auth/token-verifier.d.ts.map +1 -1
  27. package/esm/auth/token-verifier.js.map +1 -1
  28. package/esm/auth/user-write-content.d.ts +41 -0
  29. package/esm/auth/user-write-content.d.ts.map +1 -0
  30. package/esm/auth/user-write-content.js.map +1 -0
  31. package/esm/auth/user-write-content.mjs +100 -0
  32. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +55 -0
  33. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts.map +1 -0
  34. package/esm/middleware/__tests__/credential-field-coverage.harness.js.map +1 -0
  35. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +438 -0
  36. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
  37. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
  38. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
  39. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
  40. package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
  41. package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
  42. package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
  43. package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
  44. package/esm/middleware/audit-logger.d.ts +18 -1
  45. package/esm/middleware/audit-logger.d.ts.map +1 -1
  46. package/esm/middleware/audit-logger.js.map +1 -1
  47. package/esm/middleware/audit-logger.mjs +36 -13
  48. package/esm/middleware/audit-payload-guard.d.ts +85 -0
  49. package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
  50. package/esm/middleware/audit-payload-guard.js.map +1 -0
  51. package/esm/middleware/audit-payload-guard.mjs +97 -0
  52. package/esm/middleware/credential-field-guard.d.ts +55 -7
  53. package/esm/middleware/credential-field-guard.d.ts.map +1 -1
  54. package/esm/middleware/credential-field-guard.js.map +1 -1
  55. package/esm/middleware/credential-field-guard.mjs +275 -106
  56. package/esm/middleware/generated-type-names.d.ts +44 -0
  57. package/esm/middleware/generated-type-names.d.ts.map +1 -0
  58. package/esm/middleware/generated-type-names.js.map +1 -0
  59. package/esm/middleware/generated-type-names.mjs +73 -0
  60. package/esm/middleware/guard-log-throttle.d.ts +80 -0
  61. package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
  62. package/esm/middleware/guard-log-throttle.js.map +1 -0
  63. package/esm/middleware/guard-log-throttle.mjs +87 -0
  64. package/esm/middleware/mutation-account-facts.d.ts +140 -0
  65. package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
  66. package/esm/middleware/mutation-account-facts.js.map +1 -0
  67. package/esm/middleware/mutation-account-facts.mjs +212 -0
  68. package/esm/middleware/mutation-auth-guard.d.ts +82 -0
  69. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
  70. package/esm/middleware/mutation-auth-guard.js.map +1 -0
  71. package/esm/middleware/mutation-auth-guard.mjs +425 -0
  72. package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
  73. package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
  74. package/esm/middleware/mutation-tenant-facts.js.map +1 -0
  75. package/esm/middleware/mutation-tenant-facts.mjs +75 -0
  76. package/esm/middleware/trading-policy-audit.d.ts +172 -0
  77. package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
  78. package/esm/middleware/trading-policy-audit.js.map +1 -0
  79. package/esm/middleware/trading-policy-audit.mjs +309 -0
  80. package/package.json +1 -1
  81. package/server.cjs +27 -2
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Mutation authorization — pure decision logic.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * The `/graphql` context admits a request with no bearer token as a null
7
+ * principal (context-level enforcement is staged per
8
+ * `docs/security/2026-08-23-graphql-auth-enforcement-runbook.md`), and the
9
+ * generated typegraphql-prisma resolvers expose a create / update / upsert /
10
+ * delete mutation for every model. Together that let any caller who can reach
11
+ * the endpoint rewrite the system of record — including the
12
+ * `TradingPolicy.realtimeTradingEnabled` flag that arms a LIVE brokerage
13
+ * account — with nothing recording who did it.
14
+ *
15
+ * A write is authorised by WHO is asking and WHAT they are writing, so the
16
+ * decision needs both the verified principal and the model the mutation lands
17
+ * on. This module owns that decision; `src/middleware/mutation-auth-guard.ts`
18
+ * wires it into the request lifecycle and supplies the database facts
19
+ * (account ownership) the decision needs.
20
+ *
21
+ * ## Who may write what
22
+ *
23
+ * - `server` (the engine's service JWT, or the static server token) and
24
+ * `admin` may run every mutation. The engine is the system's own writer.
25
+ * - `user` may write only where the product has an ownership model:
26
+ * - `account_owned` — `TradingPolicy` and `AlpacaAccount`: the account must
27
+ * belong to the caller, or be bound to a fund the caller is entitled to
28
+ * (the same OrgMembership / FundAssignment entitlement the tenancy scoping
29
+ * uses). Bulk actions are never user-writable: a `where` filter over many
30
+ * accounts has no single owner to check.
31
+ * - `self` — `User`: only the caller's own row, and only its profile and
32
+ * onboarding fields (`./user-write-content.ts`).
33
+ * - `tenant_scoped` — the tenancy-governed models: the row (for an update,
34
+ * upsert or delete) or the payload's tenant (for a create) must lie in the
35
+ * caller's OrgMembership / FundAssignment entitlement. The guard checks
36
+ * this itself, whatever `TENANCY_SCOPING_MODE` says, because fund
37
+ * entitlement is what authorises `account_owned` writes on fund-bridged
38
+ * accounts: a scope that only observes would let a caller mint the
39
+ * entitlement it is then checked against.
40
+ * - `authenticated` — user-authored content with no finer ownership model
41
+ * yet, restricted per model to the actions the platform performs, and for
42
+ * `AuditLog` and `Configuration` to content a user may author
43
+ * (`./user-write-content.ts`).
44
+ * - `resolver_authorized` — custom mutations whose resolver performs its own
45
+ * authorization.
46
+ * - everything else is `service_only`.
47
+ * - no principal may run no mutation.
48
+ *
49
+ * Nested relation writes are decided hop by hop in `./nested-write-policy.ts`.
50
+ *
51
+ * ## Modes
52
+ *
53
+ * `MUTATION_AUTH_MODE`: `shadow` (count, log and audit what enforcement would
54
+ * deny, change nothing) is the value an UNSET variable resolves to, so the
55
+ * first deploy changes no behaviour and the would-deny series can be read
56
+ * before anything is refused. `enforce` refuses. `off` disables the decision.
57
+ * A value that is SET but unrecognised resolves to `enforce`: an operator who
58
+ * tried to configure the guard and mistyped it must get a guard that refuses,
59
+ * not one that silently observes.
60
+ *
61
+ * `MUTATION_AUTH_ENFORCE_MODELS` (comma-separated model names) escalates the
62
+ * listed models to `enforce` while the global mode is `shadow`, so the
63
+ * capital-bearing models can be contained before every browser-side platform
64
+ * write has migrated to a verified principal. Two rules keep an escalation
65
+ * from being bypassed:
66
+ *
67
+ * - a mutation is decided at the STRICTEST mode among its root model and
68
+ * every model its nested writes reach, so `updateOneUser → alpacaAccounts →
69
+ * tradingPolicy` is enforced when TradingPolicy is;
70
+ * - escalating an account model (`TradingPolicy`, `AlpacaAccount`) escalates
71
+ * the entitlement-source models (`OrgMembership`, `FundAssignment`, `Fund`,
72
+ * `BrokerageAccount`) with it, because the account rule admits a caller on
73
+ * fund entitlement read from those rows.
74
+ *
75
+ * @module auth/mutation-authorization
76
+ */
77
+ import { GOVERNED_MODELS } from './tenancy-scope.mjs';
78
+ /** Environment variable selecting the global mode. */
79
+ export const MUTATION_AUTH_MODE_ENV = 'MUTATION_AUTH_MODE';
80
+ /** Environment variable listing models escalated to `enforce`. */
81
+ export const MUTATION_AUTH_ENFORCE_MODELS_ENV = 'MUTATION_AUTH_ENFORCE_MODELS';
82
+ /**
83
+ * Resolve the global mode. Unset or blank → `shadow`; a recognised value →
84
+ * itself; anything else → `enforce`.
85
+ *
86
+ * @param env - Environment source; injectable for tests.
87
+ * @returns The resolved {@link MutationAuthMode}.
88
+ */
89
+ export function getMutationAuthMode(env = process.env) {
90
+ const raw = (env[MUTATION_AUTH_MODE_ENV] ?? '').trim().toLowerCase();
91
+ if (raw.length === 0)
92
+ return 'shadow';
93
+ if (raw === 'off' || raw === 'shadow' || raw === 'enforce')
94
+ return raw;
95
+ return 'enforce';
96
+ }
97
+ /**
98
+ * The models escalated to `enforce` by {@link MUTATION_AUTH_ENFORCE_MODELS_ENV}.
99
+ *
100
+ * @param env - Environment source; injectable for tests.
101
+ * @returns The set of model names (exact, case-sensitive Prisma names).
102
+ */
103
+ export function getEnforcedModels(env = process.env) {
104
+ const raw = env[MUTATION_AUTH_ENFORCE_MODELS_ENV] ?? '';
105
+ return new Set(raw
106
+ .split(',')
107
+ .map((m) => m.trim())
108
+ .filter((m) => m.length > 0));
109
+ }
110
+ /** The models whose user writes are authorised by row ownership or fund entitlement. */
111
+ export const ACCOUNT_MODELS = ['TradingPolicy', 'AlpacaAccount'];
112
+ /**
113
+ * The models fund entitlement and the fund-to-account bridge are read from:
114
+ * `resolveEntitlement` reads OrgMembership, Fund and FundAssignment, and a
115
+ * BrokerageAccount binds an AlpacaAccount to its fund.
116
+ */
117
+ export const ENTITLEMENT_SOURCE_MODELS = [
118
+ 'OrgMembership',
119
+ 'FundAssignment',
120
+ 'Fund',
121
+ 'BrokerageAccount',
122
+ ];
123
+ /**
124
+ * The escalation list with its implied members: an escalated account model
125
+ * brings every entitlement-source model with it.
126
+ */
127
+ export function expandEnforcedModels(enforcedModels) {
128
+ if (!ACCOUNT_MODELS.some((model) => enforcedModels.has(model)))
129
+ return enforcedModels;
130
+ return new Set([...enforcedModels, ...ENTITLEMENT_SOURCE_MODELS]);
131
+ }
132
+ /**
133
+ * The mode a mutation is decided in. `off` is a kill switch and wins; a
134
+ * global `enforce` covers every model; under `shadow`, the mutation enforces
135
+ * when ANY model it writes — the root or one reached by a nested write — is
136
+ * escalated (directly, or through {@link expandEnforcedModels}).
137
+ *
138
+ * @param models - The root model and every nested write's model.
139
+ * @param mode - The global mode.
140
+ * @param enforcedModels - The escalation list as configured.
141
+ */
142
+ export function effectiveModeFor(models, mode, enforcedModels) {
143
+ if (mode === 'off' || mode === 'enforce')
144
+ return mode;
145
+ const escalated = expandEnforcedModels(enforcedModels);
146
+ return models.some((model) => escalated.has(model)) ? 'enforce' : 'shadow';
147
+ }
148
+ /**
149
+ * Generated mutation prefixes, longest first so `createManyAndReturn` is not
150
+ * read as `createMany` + a model named `AndReturn…`.
151
+ */
152
+ const GENERATED_PREFIXES = [
153
+ ['createManyAndReturn', 'create', 'many'],
154
+ ['updateManyAndReturn', 'update', 'many'],
155
+ ['createMany', 'create', 'many'],
156
+ ['updateMany', 'update', 'many'],
157
+ ['deleteMany', 'delete', 'many'],
158
+ ['createOne', 'create', 'one'],
159
+ ['updateOne', 'update', 'one'],
160
+ ['upsertOne', 'upsert', 'one'],
161
+ ['deleteOne', 'delete', 'one'],
162
+ ];
163
+ /**
164
+ * Resolve a root mutation field name onto its model and action. A field that
165
+ * is not `<prefix><KnownModel>` is a custom mutation.
166
+ *
167
+ * @param fieldName - `info.fieldName` of a root Mutation field.
168
+ * @param models - Every Prisma model name.
169
+ */
170
+ export function classifyMutationField(fieldName, models) {
171
+ for (const [prefix, action, cardinality] of GENERATED_PREFIXES) {
172
+ if (!fieldName.startsWith(prefix))
173
+ continue;
174
+ const model = fieldName.slice(prefix.length);
175
+ if (models.has(model))
176
+ return { model, action, cardinality, fieldName };
177
+ }
178
+ return { model: `custom:${fieldName}`, action: 'custom', cardinality: 'one', fieldName };
179
+ }
180
+ const ONLY = (...actions) => new Set(actions);
181
+ /**
182
+ * Explicit user-write rules. Every model absent here is `service_only`.
183
+ *
184
+ * The `authenticated` rows are the writes the platform's server routes make
185
+ * as the signed-in user today (see the caller inventory in
186
+ * `docs/security/2026-09-24-mutation-authorization-runbook.md`), narrowed to
187
+ * the actions those routes perform. Each is a model with no finer ownership
188
+ * model yet; tightening one to an ownership rule is a follow-up, never a
189
+ * reason to widen another.
190
+ */
191
+ export const MODEL_WRITE_RULES = new Map([
192
+ ['TradingPolicy', { policy: 'account_owned', userActions: ONLY('create', 'update', 'upsert') }],
193
+ ['AlpacaAccount', { policy: 'account_owned', userActions: ONLY('create', 'update') }],
194
+ ['User', { policy: 'self', userActions: ONLY('update') }],
195
+ ...GOVERNED_MODELS.map((model) => [model, { policy: 'tenant_scoped' }]),
196
+ ['Configuration', { policy: 'authenticated', userActions: ONLY('upsert') }],
197
+ ['DashboardLayout', { policy: 'authenticated', userActions: ONLY('upsert') }],
198
+ ['Mandate', { policy: 'authenticated', userActions: ONLY('create', 'update') }],
199
+ ['MandateVersion', { policy: 'authenticated', userActions: ONLY('update') }],
200
+ ['MandateApproval', { policy: 'authenticated', userActions: ONLY('create') }],
201
+ ['Alert', { policy: 'authenticated', userActions: ONLY('update') }],
202
+ ['AuditLog', { policy: 'authenticated', userActions: ONLY('create') }],
203
+ ['Customer', { policy: 'authenticated', userActions: ONLY('update') }],
204
+ ['InvestorTransaction', { policy: 'authenticated', userActions: ONLY('update') }],
205
+ ['custom:updateOrgTradingDefaults', { policy: 'resolver_authorized' }],
206
+ ['custom:updateFundTradingOverrides', { policy: 'resolver_authorized' }],
207
+ ]);
208
+ const SERVICE_ONLY = { policy: 'service_only' };
209
+ /** The write rule for a model. */
210
+ export function ruleFor(model) {
211
+ return MODEL_WRITE_RULES.get(model) ?? SERVICE_ONLY;
212
+ }
213
+ const allow = (reason) => ({ allowed: true, reason });
214
+ const forbid = (reason) => ({
215
+ allowed: false,
216
+ reason,
217
+ refusal: 'forbidden',
218
+ });
219
+ /**
220
+ * Decide whether a principal may run a mutation. Pure; performs no I/O.
221
+ *
222
+ * @param principal - The verified principal, or `null` for none.
223
+ * @param target - The classified root mutation field.
224
+ * @param facts - Ownership facts resolved by the caller (user principals only).
225
+ */
226
+ export function evaluateMutationAccess(principal, target, facts = {}) {
227
+ if (!principal) {
228
+ return { allowed: false, reason: 'unauthenticated', refusal: 'unauthenticated' };
229
+ }
230
+ if (principal.kind === 'server')
231
+ return allow('service_principal');
232
+ if (principal.kind === 'admin')
233
+ return allow('admin_principal');
234
+ const rule = ruleFor(target.model);
235
+ if (rule.policy === 'service_only')
236
+ return forbid('model_not_user_writable');
237
+ if (rule.userActions && !rule.userActions.has(target.action)) {
238
+ return forbid('action_not_user_writable');
239
+ }
240
+ if (target.cardinality === 'many')
241
+ return forbid('bulk_not_user_writable');
242
+ if (facts.nestedRefusal)
243
+ return forbid(facts.nestedRefusal);
244
+ if (facts.contentRefusal)
245
+ return forbid(facts.contentRefusal);
246
+ switch (rule.policy) {
247
+ case 'account_owned': {
248
+ const ownership = facts.ownership ?? { kind: 'unresolved' };
249
+ if (ownership.kind === 'owner')
250
+ return allow('account_owner');
251
+ if (ownership.kind === 'fund_entitled')
252
+ return allow('account_fund_entitled');
253
+ if (ownership.kind === 'other')
254
+ return forbid('not_account_owner');
255
+ return forbid('account_unresolved');
256
+ }
257
+ case 'self':
258
+ return facts.targetsSelf === true ? allow('self') : forbid('not_self');
259
+ case 'tenant_scoped':
260
+ if (facts.tenantScope === 'in_scope')
261
+ return allow('tenant_scoped');
262
+ if (facts.tenantScope === 'out_of_scope')
263
+ return forbid('tenant_out_of_scope');
264
+ return forbid('tenant_unresolved');
265
+ case 'authenticated':
266
+ return allow('authenticated_user_model');
267
+ case 'resolver_authorized':
268
+ return allow('resolver_authorized');
269
+ }
270
+ }
271
+ //# sourceMappingURL=mutation-authorization.js.map
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Find the relation writes nested inside a mutation's arguments.
3
+ *
4
+ * A generated mutation writes more than its root model: `updateOneAlpacaAccount`
5
+ * can carry `data: { tradingPolicy: { update: { realtimeTradingEnabled: … } } }`,
6
+ * and `updateOneUser` can `connect` someone else's account onto the caller.
7
+ * Authorization and the TradingPolicy audit trail therefore have to see every
8
+ * nested write, not just the root field — otherwise the LIVE flag is one
9
+ * nesting level away from both.
10
+ *
11
+ * The walk is TYPE-directed: typegraphql-prisma names every nested relation
12
+ * container `<Model>CreateNested…Input` or `<Model>Update…NestedInput`, and
13
+ * the value's GraphQL input type is known at every step, so a key that merely
14
+ * happens to be called `update` in a JSON scalar is never mistaken for one.
15
+ *
16
+ * Each container is recorded with its parent context — the model holding the
17
+ * relation, the relation name, whether that parent row is being created or
18
+ * updated, its depth, and the parent row's unique selector when the
19
+ * arguments name it — because both authorization
20
+ * (`./nested-write-policy.ts`) and the audit trail decide each hop on its own
21
+ * parent, never on the root.
22
+ *
23
+ * @module auth/nested-write-inspector
24
+ */
25
+ import { type GraphQLResolveInfo } from 'graphql';
26
+ /**
27
+ * Whether the row a data object describes is being created, updated, or only
28
+ * selected (`where`, `connect`, …). A relation container's semantics depend on
29
+ * it: `connect` under a row being created assigns that new row, `connect`
30
+ * under an existing row re-points it.
31
+ */
32
+ export type WriteMode = 'create' | 'update' | 'filter';
33
+ /** One nested relation container found in the arguments. */
34
+ export interface NestedWrite {
35
+ /** The model the nested container writes. */
36
+ readonly model: string;
37
+ /** The operation keys present on the container (`create`, `connect`, …). */
38
+ readonly operations: readonly string[];
39
+ /** The argument path to the container, for audit context. */
40
+ readonly path: string;
41
+ /**
42
+ * The `id` of every row the container `connect`s, or `null` when any
43
+ * connect entry selects its row by something other than `id` (and so
44
+ * cannot be compared with a principal's subject).
45
+ */
46
+ readonly connectIds: readonly string[] | null;
47
+ /**
48
+ * The model whose relation field holds this container: the root model for a
49
+ * direct relation, otherwise the model of the enclosing container. A nested
50
+ * write is authorised against THIS model, never against the root, because a
51
+ * walk that has crossed into another model's rows no longer carries the
52
+ * root's ownership proof.
53
+ */
54
+ readonly parentModel: string;
55
+ /** The relation field on {@link parentModel} (`tradingPolicy`, `fund`, …). */
56
+ readonly relation: string;
57
+ /** Whether the parent row is being created or updated by this mutation. */
58
+ readonly parentMode: WriteMode;
59
+ /** 1 for a relation of the root row, 2 for a relation of a row one level down, … */
60
+ readonly depth: number;
61
+ /**
62
+ * The unique selector of the parent row when the arguments name it: the
63
+ * root `where` for a depth-1 container under an update, or the `where` of a
64
+ * to-many `update` / `upsert` entry. `null` when the parent is being
65
+ * created, or was reached through a to-one relation (whose row is "the
66
+ * related one", which the arguments do not identify).
67
+ */
68
+ readonly parentRowWhere: Readonly<Record<string, unknown>> | null;
69
+ }
70
+ /**
71
+ * The model a nested-container input type writes, or `undefined` when the
72
+ * type is not a nested relation container.
73
+ *
74
+ * @param typeName - The GraphQL input type name.
75
+ * @param modelsLongestFirst - Model names sorted longest first, so
76
+ * `AccountLinkingRequest…` is never attributed to `Account`.
77
+ */
78
+ export declare function nestedContainerModel(typeName: string, modelsLongestFirst: readonly string[]): string | undefined;
79
+ /** The root of the walk: the mutation's own model and what it does to it. */
80
+ export interface NestedWriteRoot {
81
+ readonly model: string;
82
+ readonly action: 'create' | 'update' | 'upsert' | 'delete' | 'custom';
83
+ }
84
+ /**
85
+ * Every nested relation container in a root field's arguments.
86
+ *
87
+ * @param info - The resolver info of the root mutation field.
88
+ * @param args - The field's arguments.
89
+ * @param modelsLongestFirst - Model names sorted longest first.
90
+ * @param root - The root mutation's model and action.
91
+ * @returns The nested writes, outermost first.
92
+ */
93
+ export declare function findNestedWrites(info: Pick<GraphQLResolveInfo, 'parentType' | 'fieldName'>, args: Record<string, unknown>, modelsLongestFirst: readonly string[], root: NestedWriteRoot): NestedWrite[];
94
+ //# sourceMappingURL=nested-write-inspector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nested-write-inspector.d.ts","sourceRoot":"","sources":["../../../src/auth/nested-write-inspector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAKL,KAAK,kBAAkB,EACxB,MAAM,SAAS,CAAC;AAEjB;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAEvD,4DAA4D;AAC5D,MAAM,WAAW,WAAW;IAC1B,6CAA6C;IAC7C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,4EAA4E;IAC5E,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,6DAA6D;IAC7D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IAC9C;;;;;;OAMG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,8EAA8E;IAC9E,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,2EAA2E;IAC3E,QAAQ,CAAC,UAAU,EAAE,SAAS,CAAC;IAC/B,oFAAoF;IACpF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,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C,IAAI,EACX,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EACjB,MAAM,CAAC,IAAI,EACX,MAAM,CAAC,IAAI,EACX,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,EACpC,kBAAkB,EAClB,KAAK,CACN,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Find the relation writes nested inside a mutation's arguments.
3
+ *
4
+ * A generated mutation writes more than its root model: `updateOneAlpacaAccount`
5
+ * can carry `data: { tradingPolicy: { update: { realtimeTradingEnabled: … } } }`,
6
+ * and `updateOneUser` can `connect` someone else's account onto the caller.
7
+ * Authorization and the TradingPolicy audit trail therefore have to see every
8
+ * nested write, not just the root field — otherwise the LIVE flag is one
9
+ * nesting level away from both.
10
+ *
11
+ * The walk is TYPE-directed: typegraphql-prisma names every nested relation
12
+ * container `<Model>CreateNested…Input` or `<Model>Update…NestedInput`, and
13
+ * the value's GraphQL input type is known at every step, so a key that merely
14
+ * happens to be called `update` in a JSON scalar is never mistaken for one.
15
+ *
16
+ * Each container is recorded with its parent context — the model holding the
17
+ * relation, the relation name, whether that parent row is being created or
18
+ * updated, its depth, and the parent row's unique selector when the
19
+ * arguments name it — because both authorization
20
+ * (`./nested-write-policy.ts`) and the audit trail decide each hop on its own
21
+ * parent, never on the root.
22
+ *
23
+ * @module auth/nested-write-inspector
24
+ */
25
+ import { GraphQLInputObjectType, GraphQLList, getNullableType, } from 'graphql';
26
+ /** The ids a nested `connect` selects, or `null` when any entry is not by `id`. */
27
+ function connectIdsOf(connect) {
28
+ if (connect === undefined)
29
+ return [];
30
+ const entries = Array.isArray(connect) ? connect : [connect];
31
+ const ids = [];
32
+ for (const entry of entries) {
33
+ const id = entry !== null && typeof entry === 'object' ? entry.id : undefined;
34
+ if (typeof id !== 'string')
35
+ return null;
36
+ ids.push(id);
37
+ }
38
+ return ids;
39
+ }
40
+ function asRecord(value) {
41
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
42
+ ? value
43
+ : null;
44
+ }
45
+ /**
46
+ * The model a nested-container input type writes, or `undefined` when the
47
+ * type is not a nested relation container.
48
+ *
49
+ * @param typeName - The GraphQL input type name.
50
+ * @param modelsLongestFirst - Model names sorted longest first, so
51
+ * `AccountLinkingRequest…` is never attributed to `Account`.
52
+ */
53
+ export function nestedContainerModel(typeName, modelsLongestFirst) {
54
+ const isContainer = typeName.endsWith('NestedInput') || /CreateNested(?:One|Many)Without\w+Input$/.test(typeName);
55
+ if (!isContainer)
56
+ return undefined;
57
+ for (const model of modelsLongestFirst) {
58
+ if (!typeName.startsWith(model))
59
+ continue;
60
+ const rest = typeName.slice(model.length);
61
+ if (rest.startsWith('Create') || rest.startsWith('Update'))
62
+ return model;
63
+ }
64
+ return undefined;
65
+ }
66
+ /** The mode a relation container's operation puts its payload in. */
67
+ function modeForContainerOperation(operation) {
68
+ if (operation === 'create' || operation === 'createMany')
69
+ return 'create';
70
+ if (operation === 'update' || operation === 'updateMany' || operation === 'upsert')
71
+ return 'update';
72
+ return 'filter';
73
+ }
74
+ /**
75
+ * The context a field of a (non-container) input object is read in. Inside
76
+ * the operation wrappers typegraphql-prisma generates (`{ where, data }`,
77
+ * `{ where, create, update }`), the key names the branch; a model's own data
78
+ * fields keep the context they are in.
79
+ */
80
+ function contextForField(ctx, key, uniqueWhere) {
81
+ if (key === 'where')
82
+ return { ...ctx, mode: 'filter' };
83
+ if (key === 'create')
84
+ return { ...ctx, mode: 'create', rowWhere: null };
85
+ if (key === 'update' || key === 'data') {
86
+ return { ...ctx, mode: key === 'update' ? 'update' : ctx.mode, rowWhere: uniqueWhere ?? ctx.rowWhere };
87
+ }
88
+ return ctx;
89
+ }
90
+ /** The value of a `where` field typed as a unique selector, if the object has one. */
91
+ function uniqueWhereOf(type, record) {
92
+ const whereField = type.getFields().where;
93
+ if (!whereField)
94
+ return null;
95
+ const whereType = getNullableType(whereField.type);
96
+ if (!(whereType instanceof GraphQLInputObjectType) || !whereType.name.endsWith('WhereUniqueInput')) {
97
+ return null;
98
+ }
99
+ return asRecord(record.where);
100
+ }
101
+ function walk(type, value, path, relation, ctx, modelsLongestFirst, found) {
102
+ if (value === null || value === undefined)
103
+ return;
104
+ const nullable = getNullableType(type);
105
+ if (nullable instanceof GraphQLList) {
106
+ const inner = nullable.ofType;
107
+ const items = Array.isArray(value) ? value : [value];
108
+ items.forEach((item, index) => walk(inner, item, `${path}[${index}]`, relation, ctx, modelsLongestFirst, found));
109
+ return;
110
+ }
111
+ if (!(nullable instanceof GraphQLInputObjectType) || typeof value !== 'object')
112
+ return;
113
+ const record = value;
114
+ const fields = nullable.getFields();
115
+ const model = nestedContainerModel(nullable.name, modelsLongestFirst);
116
+ if (model) {
117
+ const operations = Object.keys(record).filter((key) => record[key] !== undefined);
118
+ found.push({
119
+ model,
120
+ operations,
121
+ path,
122
+ connectIds: connectIdsOf(record.connect),
123
+ parentModel: ctx.model,
124
+ relation,
125
+ parentMode: ctx.mode,
126
+ depth: ctx.depth + 1,
127
+ parentRowWhere: ctx.rowWhere,
128
+ });
129
+ for (const operation of operations) {
130
+ const def = fields[operation];
131
+ if (!def)
132
+ continue;
133
+ const inner = {
134
+ model,
135
+ mode: modeForContainerOperation(operation),
136
+ depth: ctx.depth + 1,
137
+ rowWhere: null,
138
+ };
139
+ walk(def.type, record[operation], `${path}.${operation}`, relation, inner, modelsLongestFirst, found);
140
+ }
141
+ return;
142
+ }
143
+ const uniqueWhere = uniqueWhereOf(nullable, record);
144
+ for (const [key, child] of Object.entries(record)) {
145
+ const def = fields[key];
146
+ if (!def || child === undefined)
147
+ continue;
148
+ walk(def.type, child, `${path}.${key}`, key, contextForField(ctx, key, uniqueWhere), modelsLongestFirst, found);
149
+ }
150
+ }
151
+ /** The context a root argument is read in. */
152
+ function rootContext(root, argName, args) {
153
+ const where = root.action === 'update' || root.action === 'upsert' ? asRecord(args.where) : null;
154
+ const base = { model: root.model, depth: 0 };
155
+ if (argName === 'create')
156
+ return { ...base, mode: 'create', rowWhere: null };
157
+ if (argName === 'update')
158
+ return { ...base, mode: 'update', rowWhere: where };
159
+ if (argName === 'data') {
160
+ return root.action === 'create'
161
+ ? { ...base, mode: 'create', rowWhere: null }
162
+ : { ...base, mode: 'update', rowWhere: where };
163
+ }
164
+ return { ...base, mode: 'filter', rowWhere: null };
165
+ }
166
+ /**
167
+ * Every nested relation container in a root field's arguments.
168
+ *
169
+ * @param info - The resolver info of the root mutation field.
170
+ * @param args - The field's arguments.
171
+ * @param modelsLongestFirst - Model names sorted longest first.
172
+ * @param root - The root mutation's model and action.
173
+ * @returns The nested writes, outermost first.
174
+ */
175
+ export function findNestedWrites(info, args, modelsLongestFirst, root) {
176
+ const found = [];
177
+ const fieldDef = info.parentType.getFields()[info.fieldName];
178
+ if (!fieldDef || !args)
179
+ return found;
180
+ for (const argDef of fieldDef.args) {
181
+ walk(argDef.type, args[argDef.name], argDef.name, argDef.name, rootContext(root, argDef.name, args), modelsLongestFirst, found);
182
+ }
183
+ return found;
184
+ }
185
+ //# sourceMappingURL=nested-write-inspector.js.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Which nested relation writes a `user` principal may make. Pure; no I/O.
3
+ *
4
+ * ## Why each hop is judged on its own
5
+ *
6
+ * A root mutation's authorization proves one thing: the caller may write THAT
7
+ * row (they own the account, it is their user row, it sits in a tenant they
8
+ * are entitled to). A nested write walks from that row along a relation into
9
+ * another model's rows, and from there into another's. Nothing about the
10
+ * root's proof survives the first hop into rows the caller does not own:
11
+ * `updateOneUser(self) → managedFunds → operator.update` edits a different
12
+ * person's user row, and `updateOneAlpacaAccount(own) → brokerageAccount →
13
+ * fund → …` reaches every account the fund is bridged to.
14
+ *
15
+ * So each nested container is decided against the model that HOLDS the
16
+ * relation (its parent), the relation itself, whether the parent row is being
17
+ * created or updated, and its depth — never against the root. The rule is an
18
+ * allowlist; everything not named here is refused:
19
+ *
20
+ * - **Entitlement rows are never written nested.** `OrgMembership`,
21
+ * `FundAssignment` and a fund's `manager` / `operator` relations are what
22
+ * fund entitlement is read from (`resolveEntitlement`), and fund
23
+ * entitlement authorises writes to every account bridged to the fund. A
24
+ * nested write to them has no scope check of its own, so it would let a
25
+ * caller mint the entitlement it is then checked against.
26
+ * - **`connect` may only move the parent row, never the connected one.** When
27
+ * the foreign key sits on the parent (`FundAssignment.fund`), a `connect`
28
+ * writes only the parent; when it sits on the connected row
29
+ * (`Organization.funds`, `User.alpacaAccounts`), the connected row — someone
30
+ * else's — is re-pointed. Only the first kind is admitted, and then only:
31
+ * - into a user-authored (`authenticated`) model;
32
+ * - into a tenant-scoped model while the parent row is being CREATED (the
33
+ * root's tenant check reads exactly that connect); re-tenanting an
34
+ * existing row is refused;
35
+ * - into the caller's own `User` row while the parent is being created;
36
+ * - into `AlpacaAccount` only as the policy's own account on a root
37
+ * TradingPolicy create, whose ownership check reads that connect.
38
+ * - **Content writes into an owned model** (account, policy, user row) are
39
+ * admitted only on the three edges whose target row is the ROOT row's own
40
+ * counterpart, and only at depth 1: an account's own policy, a policy's own
41
+ * account, and a brokerage binding's own engine account. The root decision
42
+ * has already authorised that exact account.
43
+ * - **New user-authored rows** (`create` into an `authenticated` model) may be
44
+ * attached anywhere the walk is otherwise admitted.
45
+ * - `set`, `disconnect`, `delete`, `deleteMany`, `updateMany`,
46
+ * `connectOrCreate` and `createMany` are never admitted nested.
47
+ *
48
+ * @module auth/nested-write-policy
49
+ */
50
+ import { type MutationAuthReason } from './mutation-authorization';
51
+ import type { NestedWrite } from './nested-write-inspector';
52
+ /** Where a relation's foreign key lives, as the Prisma data model states it. */
53
+ export interface RelationFacts {
54
+ /**
55
+ * Whether `model.relation` holds the foreign key (Prisma
56
+ * `relationFromFields` is non-empty on that side). `undefined` for a
57
+ * relation the facts do not know, which every rule treats as "not on the
58
+ * parent" — the refusing answer.
59
+ */
60
+ fkOnParent(model: string, relation: string): boolean | undefined;
61
+ }
62
+ /** The models fund entitlement is read from. */
63
+ export declare const ENTITLEMENT_MODELS: ReadonlySet<string>;
64
+ /** The relations that name a fund's manager or operator, from either side. */
65
+ export declare const ENTITLEMENT_RELATIONS: ReadonlySet<string>;
66
+ /** Why a nested write was refused (a bounded metric label). */
67
+ export type NestedWriteRefusal = Extract<MutationAuthReason, 'nested_write_not_user_writable' | 'nested_entitlement_write'>;
68
+ /**
69
+ * Whether a user principal may make one nested write.
70
+ *
71
+ * @param write - The nested container, with its parent context.
72
+ * @param callerId - The user principal's subject (`User.id`).
73
+ * @param relations - Foreign-key placement per relation.
74
+ * @returns `null` when the write is admitted, otherwise the refusal reason.
75
+ */
76
+ export declare function nestedWriteRefusalForUser(write: NestedWrite, callerId: string, relations: RelationFacts): NestedWriteRefusal | null;
77
+ /**
78
+ * Whether a nested container writes rows of its OWN model. A container whose
79
+ * only operation is `connect` over a relation whose foreign key sits on the
80
+ * parent writes only the parent row (it sets the parent's key); anything else
81
+ * — a create, an update, a connect that re-points the connected row, a
82
+ * disconnect — writes the nested model. The guard decides a mutation at the
83
+ * strictest mode among the models it writes, so this is what decides whether
84
+ * an escalated nested model governs the mutation.
85
+ *
86
+ * @param write - The nested container.
87
+ * @param relations - Foreign-key placement per relation.
88
+ */
89
+ export declare function writesNestedModelRows(write: NestedWrite, relations: RelationFacts): boolean;
90
+ /**
91
+ * The first refusal among a mutation's nested writes, entitlement refusals
92
+ * first (they are the more specific signal), or `null` when all are admitted.
93
+ */
94
+ export declare function firstNestedRefusal(writes: readonly NestedWrite[], callerId: string, relations: RelationFacts): NestedWriteRefusal | null;
95
+ //# sourceMappingURL=nested-write-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nested-write-policy.d.ts","sourceRoot":"","sources":["../../../src/auth/nested-write-policy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AAEH,OAAO,EAAW,KAAK,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAE5D,gFAAgF;AAChF,MAAM,WAAW,aAAa;IAC5B;;;;;OAKG;IACH,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;CAClE;AAED,gDAAgD;AAChD,eAAO,MAAM,kBAAkB,EAAE,WAAW,CAAC,MAAM,CAAgD,CAAC;AAEpG,8EAA8E;AAC9E,eAAO,MAAM,qBAAqB,EAAE,WAAW,CAAC,MAAM,CAKpD,CAAC;AAaH,+DAA+D;AAC/D,MAAM,MAAM,kBAAkB,GAAG,OAAO,CACtC,kBAAkB,EAClB,gCAAgC,GAAG,0BAA0B,CAC9D,CAAC;AAmCF;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,aAAa,GACvB,kBAAkB,GAAG,IAAI,CAiB3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,aAAa,GAAG,OAAO,CAG3F;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,SAAS,WAAW,EAAE,EAC9B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,aAAa,GACvB,kBAAkB,GAAG,IAAI,CAQ3B"}