@adaptic/backend 0.0.1057 → 0.0.1059

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 (114) hide show
  1. package/auth/authorization-map.cjs +306 -0
  2. package/auth/authorization-map.d.ts +143 -0
  3. package/auth/cortex-auth-checker.cjs +172 -0
  4. package/auth/cortex-auth-checker.d.ts +114 -0
  5. package/auth/credential-fields.cjs +51 -0
  6. package/auth/credential-fields.d.ts +19 -0
  7. package/auth/credential-redaction.cjs +134 -0
  8. package/auth/credential-redaction.d.ts +60 -0
  9. package/auth/graphql-auth-shadow.cjs +317 -0
  10. package/auth/graphql-auth-shadow.d.ts +194 -0
  11. package/auth/membership-write-authority.cjs +131 -0
  12. package/auth/membership-write-authority.d.ts +110 -0
  13. package/auth/mutation-authorization.cjs +376 -0
  14. package/auth/mutation-authorization.d.ts +261 -0
  15. package/auth/nested-write-inspector.cjs +189 -0
  16. package/auth/nested-write-inspector.d.ts +94 -0
  17. package/auth/nested-write-policy.cjs +189 -0
  18. package/auth/nested-write-policy.d.ts +99 -0
  19. package/auth/service-token.cjs +339 -0
  20. package/auth/service-token.d.ts +106 -0
  21. package/auth/tenancy-scope.cjs +736 -0
  22. package/auth/tenancy-scope.d.ts +347 -0
  23. package/auth/token-verifier.cjs +451 -0
  24. package/auth/token-verifier.d.ts +153 -0
  25. package/auth/totp.cjs +265 -0
  26. package/auth/totp.d.ts +111 -0
  27. package/auth/user-write-content.cjs +116 -0
  28. package/auth/user-write-content.d.ts +47 -0
  29. package/auth/ws-auth-context.cjs +75 -0
  30. package/auth/ws-auth-context.d.ts +69 -0
  31. package/config/jwtConfig.cjs +57 -0
  32. package/config/jwtConfig.d.ts +16 -0
  33. package/config/metrics.cjs +356 -0
  34. package/config/metrics.d.ts +128 -0
  35. package/config/persisted-queries.cjs +122 -0
  36. package/config/persisted-queries.d.ts +40 -0
  37. package/config/server-only-models.cjs +166 -0
  38. package/config/server-only-models.d.ts +89 -0
  39. package/config/tracing.d.ts +24 -0
  40. package/esm/auth/service-token.d.ts +12 -0
  41. package/esm/auth/service-token.mjs +27 -5
  42. package/esm/config/jwtConfig.mjs +5 -1
  43. package/generated/typegraphql-prisma/enhance.cjs +3 -3
  44. package/generated/typegraphql-prisma/index.cjs +6 -6
  45. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  46. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  47. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  48. package/middleware/audit-log-write-redaction.cjs +143 -0
  49. package/middleware/audit-log-write-redaction.d.ts +82 -0
  50. package/middleware/audit-logger.cjs +378 -0
  51. package/middleware/audit-logger.d.ts +158 -0
  52. package/middleware/audit-payload-guard.cjs +107 -0
  53. package/middleware/audit-payload-guard.d.ts +85 -0
  54. package/middleware/auth.cjs +66 -0
  55. package/middleware/auth.d.ts +41 -0
  56. package/middleware/credential-field-guard.cjs +514 -0
  57. package/middleware/credential-field-guard.d.ts +173 -0
  58. package/middleware/generated-type-names.cjs +77 -0
  59. package/middleware/generated-type-names.d.ts +44 -0
  60. package/middleware/graphql-validation-plugin.cjs +310 -0
  61. package/middleware/graphql-validation-plugin.d.ts +98 -0
  62. package/middleware/guard-log-throttle.cjs +89 -0
  63. package/middleware/guard-log-throttle.d.ts +80 -0
  64. package/middleware/index.cjs +57 -0
  65. package/middleware/index.d.ts +14 -0
  66. package/middleware/input-validator.cjs +220 -0
  67. package/middleware/input-validator.d.ts +63 -0
  68. package/middleware/mandate-version-validation.cjs +131 -0
  69. package/middleware/mandate-version-validation.d.ts +41 -0
  70. package/middleware/mutation-account-facts.cjs +223 -0
  71. package/middleware/mutation-account-facts.d.ts +143 -0
  72. package/middleware/mutation-auth-guard.cjs +536 -0
  73. package/middleware/mutation-auth-guard.d.ts +100 -0
  74. package/middleware/mutation-membership-facts.cjs +276 -0
  75. package/middleware/mutation-membership-facts.d.ts +133 -0
  76. package/middleware/mutation-tenant-facts.cjs +132 -0
  77. package/middleware/mutation-tenant-facts.d.ts +81 -0
  78. package/middleware/query-complexity.cjs +182 -0
  79. package/middleware/query-complexity.d.ts +56 -0
  80. package/middleware/rate-limiter.cjs +223 -0
  81. package/middleware/rate-limiter.d.ts +93 -0
  82. package/middleware/rate-tier.cjs +111 -0
  83. package/middleware/rate-tier.d.ts +56 -0
  84. package/middleware/soft-delete.cjs +175 -0
  85. package/middleware/soft-delete.d.ts +146 -0
  86. package/middleware/tenancy-scoping.cjs +229 -0
  87. package/middleware/tenancy-scoping.d.ts +67 -0
  88. package/middleware/trading-policy-audit.cjs +353 -0
  89. package/middleware/trading-policy-audit.d.ts +184 -0
  90. package/middleware/types.cjs +17 -0
  91. package/middleware/types.d.ts +87 -0
  92. package/middleware/validation-examples.cjs +398 -0
  93. package/middleware/validation-examples.d.ts +76 -0
  94. package/package.json +10 -2
  95. package/readers/index.cjs +15 -0
  96. package/readers/index.d.ts +10 -0
  97. package/readers/intraday-lane-prefs.cjs +76 -0
  98. package/readers/intraday-lane-prefs.d.ts +45 -0
  99. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  100. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  101. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  102. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  103. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  104. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  105. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  106. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  107. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  108. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  109. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  110. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  111. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  112. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  113. package/health.cjs +0 -274
  114. package/server.cjs +0 -607
@@ -0,0 +1,261 @@
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
+ * - `membership_authority` — `OrgMembership` and `FundAssignment`, the rows
34
+ * every other entitlement is read from: the caller must hold OWNER or
35
+ * ADMIN in the row's organization (OWNER for a row whose role is OWNER),
36
+ * or MANAGER on the assignment's own fund; or the write makes the caller
37
+ * the first owner of an empty organization, the one self-service create
38
+ * the backend can verify from rows the caller cannot write
39
+ * (`./membership-write-authority.ts`). Roles are read from the database
40
+ * for the mutation, never from the token.
41
+ * - `tenant_scoped` — the other tenancy-governed models: the row (for an update,
42
+ * upsert or delete) or the payload's tenant (for a create) must lie in the
43
+ * caller's OrgMembership / FundAssignment entitlement. The guard checks
44
+ * this itself, whatever `TENANCY_SCOPING_MODE` says, because fund
45
+ * entitlement is what authorises `account_owned` writes on fund-bridged
46
+ * accounts: a scope that only observes would let a caller mint the
47
+ * entitlement it is then checked against.
48
+ * - `authenticated` — user-authored content with no finer ownership model
49
+ * yet, restricted per model to the actions the platform performs, and for
50
+ * `AuditLog` and `Configuration` to content a user may author
51
+ * (`./user-write-content.ts`).
52
+ * - `mandate_tenant` — `MandateVersion`: the addressed version's mandate
53
+ * must belong to an organization the caller is a member of or a fund they
54
+ * are entitled to. Nested writes treat it as `authenticated`, as before.
55
+ * - `resolver_authorized` — custom mutations whose resolver performs its own
56
+ * authorization, among them the strategy-draft mutations: the only user
57
+ * writes to `Strategy`, which is otherwise `service_only`.
58
+ * - everything else is `service_only`.
59
+ * - `UserTotp` and the TOTP custom mutations are service-principal only:
60
+ * not even an admin may write a user's second factor through GraphQL
61
+ * ({@link SERVICE_PRINCIPAL_ONLY_MODELS}).
62
+ * - no principal may run no mutation.
63
+ *
64
+ * Nested relation writes are decided hop by hop in `./nested-write-policy.ts`.
65
+ *
66
+ * ## Modes
67
+ *
68
+ * `MUTATION_AUTH_MODE`: `shadow` (count, log and audit what enforcement would
69
+ * deny, change nothing) is the value an UNSET variable resolves to, so the
70
+ * first deploy changes no behaviour and the would-deny series can be read
71
+ * before anything is refused. `enforce` refuses. `off` disables the decision.
72
+ * A value that is SET but unrecognised resolves to `enforce`: an operator who
73
+ * tried to configure the guard and mistyped it must get a guard that refuses,
74
+ * not one that silently observes.
75
+ *
76
+ * `MUTATION_AUTH_ENFORCE_MODELS` (comma-separated model names) escalates the
77
+ * listed models to `enforce` while the global mode is `shadow`, so the
78
+ * capital-bearing models can be contained before every browser-side platform
79
+ * write has migrated to a verified principal. Two rules keep an escalation
80
+ * from being bypassed:
81
+ *
82
+ * - a mutation is decided at the STRICTEST mode among its root model and
83
+ * every model its nested writes reach, so `updateOneUser → alpacaAccounts →
84
+ * tradingPolicy` is enforced when TradingPolicy is;
85
+ * - escalating an account model (`TradingPolicy`, `AlpacaAccount`) escalates
86
+ * the entitlement-source models (`OrgMembership`, `FundAssignment`, `Fund`,
87
+ * `BrokerageAccount`) with it, because the account rule admits a caller on
88
+ * fund entitlement read from those rows.
89
+ *
90
+ * @module auth/mutation-authorization
91
+ */
92
+ import { type MembershipVerdict } from './membership-write-authority';
93
+ import type { BackendPrincipal } from './token-verifier';
94
+ /** Operating mode of the mutation guard. See the module doc. */
95
+ export type MutationAuthMode = 'off' | 'shadow' | 'enforce';
96
+ /** Environment variable selecting the global mode. */
97
+ export declare const MUTATION_AUTH_MODE_ENV = "MUTATION_AUTH_MODE";
98
+ /** Environment variable listing models escalated to `enforce`. */
99
+ export declare const MUTATION_AUTH_ENFORCE_MODELS_ENV = "MUTATION_AUTH_ENFORCE_MODELS";
100
+ /**
101
+ * Resolve the global mode. Unset or blank → `shadow`; a recognised value →
102
+ * itself; anything else → `enforce`.
103
+ *
104
+ * @param env - Environment source; injectable for tests.
105
+ * @returns The resolved {@link MutationAuthMode}.
106
+ */
107
+ export declare function getMutationAuthMode(env?: Record<string, string | undefined>): MutationAuthMode;
108
+ /**
109
+ * The models escalated to `enforce` by {@link MUTATION_AUTH_ENFORCE_MODELS_ENV}.
110
+ *
111
+ * @param env - Environment source; injectable for tests.
112
+ * @returns The set of model names (exact, case-sensitive Prisma names).
113
+ */
114
+ export declare function getEnforcedModels(env?: Record<string, string | undefined>): ReadonlySet<string>;
115
+ /** The models whose user writes are authorised by row ownership or fund entitlement. */
116
+ export declare const ACCOUNT_MODELS: readonly string[];
117
+ /**
118
+ * The models fund entitlement and the fund-to-account bridge are read from:
119
+ * `resolveEntitlement` reads OrgMembership, Fund and FundAssignment, and a
120
+ * BrokerageAccount binds an AlpacaAccount to its fund.
121
+ */
122
+ export declare const ENTITLEMENT_SOURCE_MODELS: readonly string[];
123
+ /**
124
+ * The escalation list with its implied members: an escalated account model
125
+ * brings every entitlement-source model with it.
126
+ */
127
+ export declare function expandEnforcedModels(enforcedModels: ReadonlySet<string>): ReadonlySet<string>;
128
+ /** The TOTP custom mutations (`src/resolvers/custom/UserTotpResolver.ts`), as classified targets. */
129
+ export declare const TOTP_CUSTOM_MUTATIONS: readonly string[];
130
+ /**
131
+ * Targets only the service principal may write: a user's second factor. An
132
+ * admin principal is a signed-in person, and a person who can rewrite another
133
+ * person's second factor has defeated it, so admin is refused here too.
134
+ */
135
+ export declare const SERVICE_PRINCIPAL_ONLY_MODELS: ReadonlySet<string>;
136
+ /**
137
+ * Targets decided at `enforce` in every mode, `off` included, whatever the
138
+ * environment says: the desk models and the TOTP mutations.
139
+ *
140
+ * `MUTATION_AUTH_MODE` stages the guard for models that had live writers
141
+ * before it existed — shadow proves no legitimate writer is refused, `off`
142
+ * restores the unguarded behaviour. These targets were born after the guard
143
+ * and have never been written unguarded, so there is no writer for shadow to
144
+ * protect and nothing for `off` to restore; holding them in shadow would let
145
+ * anyone write a user's push endpoints, feature overrides or second factor
146
+ * while the would-deny series accumulated.
147
+ */
148
+ export declare const ALWAYS_ENFORCED_MUTATION_MODELS: ReadonlySet<string>;
149
+ /** Whether any of a mutation's written models is always enforced. */
150
+ export declare function touchesAlwaysEnforced(models: readonly string[]): boolean;
151
+ /**
152
+ * The mode a mutation is decided in. A mutation writing an always-enforced
153
+ * target ({@link ALWAYS_ENFORCED_MUTATION_MODELS}) is enforced in every mode.
154
+ * Otherwise `off` is a kill switch and wins; a global `enforce` covers every
155
+ * model; under `shadow`, the mutation enforces when ANY model it writes — the
156
+ * root or one reached by a nested write — is escalated (directly, or through
157
+ * {@link expandEnforcedModels}).
158
+ *
159
+ * @param models - The root model and every nested write's model.
160
+ * @param mode - The global mode.
161
+ * @param enforcedModels - The escalation list as configured.
162
+ */
163
+ export declare function effectiveModeFor(models: readonly string[], mode: MutationAuthMode, enforcedModels: ReadonlySet<string>): MutationAuthMode;
164
+ /** What a generated mutation does to its model. */
165
+ export type MutationAction = 'create' | 'update' | 'upsert' | 'delete';
166
+ /** Whether the mutation addresses one row (by a unique `where`) or many. */
167
+ export type MutationCardinality = 'one' | 'many';
168
+ /** A mutation root field resolved onto its model. */
169
+ export interface MutationTarget {
170
+ /** Prisma model name, or `custom:<field>` for a hand-written mutation. */
171
+ readonly model: string;
172
+ readonly action: MutationAction | 'custom';
173
+ readonly cardinality: MutationCardinality;
174
+ readonly fieldName: string;
175
+ }
176
+ /**
177
+ * Resolve a root mutation field name onto its model and action. A field that
178
+ * is not `<prefix><KnownModel>` is a custom mutation.
179
+ *
180
+ * @param fieldName - `info.fieldName` of a root Mutation field.
181
+ * @param models - Every Prisma model name.
182
+ */
183
+ export declare function classifyMutationField(fieldName: string, models: ReadonlySet<string>): MutationTarget;
184
+ /** How a `user` principal may write a model. See the module doc. */
185
+ export type UserWritePolicy = 'service_only' | 'account_owned' | 'self' | 'tenant_scoped' | 'membership_authority' | 'mandate_tenant' | 'authenticated' | 'resolver_authorized';
186
+ /** A model's user policy plus the actions a user may perform under it. */
187
+ export interface ModelWriteRule {
188
+ readonly policy: UserWritePolicy;
189
+ /** Actions a user may perform; absent means every action. */
190
+ readonly userActions?: ReadonlySet<MutationAction | 'custom'>;
191
+ }
192
+ /** The strategy-draft custom mutations (`src/resolvers/custom/StrategyDraftResolver.ts`), as classified targets. */
193
+ export declare const STRATEGY_DRAFT_MUTATIONS: readonly string[];
194
+ /**
195
+ * Explicit user-write rules. Every model absent here is `service_only`.
196
+ *
197
+ * The `authenticated` rows are the writes the platform's server routes make
198
+ * as the signed-in user today (see the caller inventory in
199
+ * `docs/security/2026-09-24-mutation-authorization-runbook.md`), narrowed to
200
+ * the actions those routes perform. Each is a model with no finer ownership
201
+ * model yet; tightening one to an ownership rule is a follow-up, never a
202
+ * reason to widen another.
203
+ */
204
+ export declare const MODEL_WRITE_RULES: ReadonlyMap<string, ModelWriteRule>;
205
+ /** The write rule for a model. */
206
+ export declare function ruleFor(model: string): ModelWriteRule;
207
+ /** Why a mutation was admitted or refused. A bounded metric label. */
208
+ export type MutationAuthReason = 'guard_off' | 'guard_error' | 'service_principal' | 'admin_principal' | 'account_owner' | 'account_fund_entitled' | 'self' | 'tenant_scoped' | 'authenticated_user_model' | 'resolver_authorized' | 'unauthenticated' | 'service_principal_only' | 'model_not_user_writable' | 'action_not_user_writable' | 'bulk_not_user_writable' | 'not_account_owner' | 'account_unresolved' | 'not_self' | 'tenant_out_of_scope' | 'tenant_unresolved' | 'membership_org_admin' | 'membership_fund_manager' | 'membership_first_owner' | 'membership_role_insufficient' | 'membership_owner_requires_owner' | 'membership_authority_unresolved' | 'field_not_user_writable' | 'reserved_audit_source' | 'audit_actor_mismatch' | 'ledger_fund_reserved' | 'config_key_not_user_scoped' | 'nested_write_not_user_writable' | 'nested_entitlement_write';
209
+ /** Ownership facts the middleware resolved for an `account_owned` write. */
210
+ export type AccountOwnership = {
211
+ readonly kind: 'owner';
212
+ } | {
213
+ readonly kind: 'fund_entitled';
214
+ } | {
215
+ readonly kind: 'other';
216
+ } | {
217
+ readonly kind: 'unresolved';
218
+ };
219
+ /** For a `tenant_scoped` write: whether the row or payload lies in the caller's entitlement. */
220
+ export type TenantScope = 'in_scope' | 'out_of_scope';
221
+ /**
222
+ * For a `membership_authority` write: the verdict read from the database, or
223
+ * `unresolved` when the rows it reaches could not be identified or read.
224
+ */
225
+ export type MembershipAuthority = MembershipVerdict | 'unresolved';
226
+ /** Everything the decision needs beyond the principal and target. */
227
+ export interface MutationFacts {
228
+ /** For `account_owned`: whether the caller owns every account touched. */
229
+ readonly ownership?: AccountOwnership;
230
+ /** For `self`: whether the `where` names the caller's own row. */
231
+ readonly targetsSelf?: boolean;
232
+ /** For `tenant_scoped`: the guard's own scope check; absent = not yet resolved. */
233
+ readonly tenantScope?: TenantScope;
234
+ /** For `membership_authority`: the caller's authority over the row; absent = not yet resolved. */
235
+ readonly membershipAuthority?: MembershipAuthority;
236
+ /**
237
+ * Every model the mutation's nested writes reach. A non-service principal is
238
+ * refused when one is service-principal only, whatever its root.
239
+ */
240
+ readonly nestedModels?: readonly string[];
241
+ /** The refusal from `./nested-write-policy.ts`, if any nested write is refused. */
242
+ readonly nestedRefusal?: 'nested_write_not_user_writable' | 'nested_entitlement_write' | null;
243
+ /** The refusal from `./user-write-content.ts`, if the payload's content is refused. */
244
+ readonly contentRefusal?: 'field_not_user_writable' | 'reserved_audit_source' | 'audit_actor_mismatch' | 'ledger_fund_reserved' | 'config_key_not_user_scoped' | null;
245
+ }
246
+ /** The decision for one mutation, before the mode is applied. */
247
+ export interface MutationAuthEvaluation {
248
+ readonly allowed: boolean;
249
+ readonly reason: MutationAuthReason;
250
+ /** HTTP-shaped class of a refusal: no principal (401) or wrong one (403). */
251
+ readonly refusal?: 'unauthenticated' | 'forbidden';
252
+ }
253
+ /**
254
+ * Decide whether a principal may run a mutation. Pure; performs no I/O.
255
+ *
256
+ * @param principal - The verified principal, or `null` for none.
257
+ * @param target - The classified root mutation field.
258
+ * @param facts - Ownership facts resolved by the caller (user principals only).
259
+ */
260
+ export declare function evaluateMutationAccess(principal: BackendPrincipal | null, target: MutationTarget, facts?: MutationFacts): MutationAuthEvaluation;
261
+ //# sourceMappingURL=mutation-authorization.d.ts.map
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ /**
3
+ * Find the relation writes nested inside a mutation's arguments.
4
+ *
5
+ * A generated mutation writes more than its root model: `updateOneAlpacaAccount`
6
+ * can carry `data: { tradingPolicy: { update: { realtimeTradingEnabled: … } } }`,
7
+ * and `updateOneUser` can `connect` someone else's account onto the caller.
8
+ * Authorization and the TradingPolicy audit trail therefore have to see every
9
+ * nested write, not just the root field — otherwise the LIVE flag is one
10
+ * nesting level away from both.
11
+ *
12
+ * The walk is TYPE-directed: typegraphql-prisma names every nested relation
13
+ * container `<Model>CreateNested…Input` or `<Model>Update…NestedInput`, and
14
+ * the value's GraphQL input type is known at every step, so a key that merely
15
+ * happens to be called `update` in a JSON scalar is never mistaken for one.
16
+ *
17
+ * Each container is recorded with its parent context — the model holding the
18
+ * relation, the relation name, whether that parent row is being created or
19
+ * updated, its depth, and the parent row's unique selector when the
20
+ * arguments name it — because both authorization
21
+ * (`./nested-write-policy.ts`) and the audit trail decide each hop on its own
22
+ * parent, never on the root.
23
+ *
24
+ * @module auth/nested-write-inspector
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.nestedContainerModel = nestedContainerModel;
28
+ exports.findNestedWrites = findNestedWrites;
29
+ const graphql_1 = require("graphql");
30
+ /** The ids a nested `connect` selects, or `null` when any entry is not by `id`. */
31
+ function connectIdsOf(connect) {
32
+ if (connect === undefined)
33
+ return [];
34
+ const entries = Array.isArray(connect) ? connect : [connect];
35
+ const ids = [];
36
+ for (const entry of entries) {
37
+ const id = entry !== null && typeof entry === 'object' ? entry.id : undefined;
38
+ if (typeof id !== 'string')
39
+ return null;
40
+ ids.push(id);
41
+ }
42
+ return ids;
43
+ }
44
+ function asRecord(value) {
45
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
46
+ ? value
47
+ : null;
48
+ }
49
+ /**
50
+ * The model a nested-container input type writes, or `undefined` when the
51
+ * type is not a nested relation container.
52
+ *
53
+ * @param typeName - The GraphQL input type name.
54
+ * @param modelsLongestFirst - Model names sorted longest first, so
55
+ * `AccountLinkingRequest…` is never attributed to `Account`.
56
+ */
57
+ function nestedContainerModel(typeName, modelsLongestFirst) {
58
+ const isContainer = typeName.endsWith('NestedInput') || /CreateNested(?:One|Many)Without\w+Input$/.test(typeName);
59
+ if (!isContainer)
60
+ return undefined;
61
+ for (const model of modelsLongestFirst) {
62
+ if (!typeName.startsWith(model))
63
+ continue;
64
+ const rest = typeName.slice(model.length);
65
+ if (rest.startsWith('Create') || rest.startsWith('Update'))
66
+ return model;
67
+ }
68
+ return undefined;
69
+ }
70
+ /** The mode a relation container's operation puts its payload in. */
71
+ function modeForContainerOperation(operation) {
72
+ if (operation === 'create' || operation === 'createMany')
73
+ return 'create';
74
+ if (operation === 'update' || operation === 'updateMany' || operation === 'upsert')
75
+ return 'update';
76
+ return 'filter';
77
+ }
78
+ /**
79
+ * The context a field of a (non-container) input object is read in. Inside
80
+ * the operation wrappers typegraphql-prisma generates (`{ where, data }`,
81
+ * `{ where, create, update }`), the key names the branch; a model's own data
82
+ * fields keep the context they are in.
83
+ */
84
+ function contextForField(ctx, key, uniqueWhere) {
85
+ if (key === 'where')
86
+ return { ...ctx, mode: 'filter' };
87
+ if (key === 'create')
88
+ return { ...ctx, mode: 'create', rowWhere: null };
89
+ if (key === 'update' || key === 'data') {
90
+ return { ...ctx, mode: key === 'update' ? 'update' : ctx.mode, rowWhere: uniqueWhere !== null && uniqueWhere !== void 0 ? uniqueWhere : ctx.rowWhere };
91
+ }
92
+ return ctx;
93
+ }
94
+ /** The value of a `where` field typed as a unique selector, if the object has one. */
95
+ function uniqueWhereOf(type, record) {
96
+ const whereField = type.getFields().where;
97
+ if (!whereField)
98
+ return null;
99
+ const whereType = (0, graphql_1.getNullableType)(whereField.type);
100
+ if (!(whereType instanceof graphql_1.GraphQLInputObjectType) || !whereType.name.endsWith('WhereUniqueInput')) {
101
+ return null;
102
+ }
103
+ return asRecord(record.where);
104
+ }
105
+ function walk(type, value, path, relation, ctx, modelsLongestFirst, found) {
106
+ if (value === null || value === undefined)
107
+ return;
108
+ const nullable = (0, graphql_1.getNullableType)(type);
109
+ if (nullable instanceof graphql_1.GraphQLList) {
110
+ const inner = nullable.ofType;
111
+ const items = Array.isArray(value) ? value : [value];
112
+ items.forEach((item, index) => walk(inner, item, `${path}[${index}]`, relation, ctx, modelsLongestFirst, found));
113
+ return;
114
+ }
115
+ if (!(nullable instanceof graphql_1.GraphQLInputObjectType) || typeof value !== 'object')
116
+ return;
117
+ const record = value;
118
+ const fields = nullable.getFields();
119
+ const model = nestedContainerModel(nullable.name, modelsLongestFirst);
120
+ if (model) {
121
+ const operations = Object.keys(record).filter((key) => record[key] !== undefined);
122
+ found.push({
123
+ model,
124
+ operations,
125
+ path,
126
+ connectIds: connectIdsOf(record.connect),
127
+ parentModel: ctx.model,
128
+ relation,
129
+ parentMode: ctx.mode,
130
+ depth: ctx.depth + 1,
131
+ parentRowWhere: ctx.rowWhere,
132
+ });
133
+ for (const operation of operations) {
134
+ const def = fields[operation];
135
+ if (!def)
136
+ continue;
137
+ const inner = {
138
+ model,
139
+ mode: modeForContainerOperation(operation),
140
+ depth: ctx.depth + 1,
141
+ rowWhere: null,
142
+ };
143
+ walk(def.type, record[operation], `${path}.${operation}`, relation, inner, modelsLongestFirst, found);
144
+ }
145
+ return;
146
+ }
147
+ const uniqueWhere = uniqueWhereOf(nullable, record);
148
+ for (const [key, child] of Object.entries(record)) {
149
+ const def = fields[key];
150
+ if (!def || child === undefined)
151
+ continue;
152
+ walk(def.type, child, `${path}.${key}`, key, contextForField(ctx, key, uniqueWhere), modelsLongestFirst, found);
153
+ }
154
+ }
155
+ /** The context a root argument is read in. */
156
+ function rootContext(root, argName, args) {
157
+ const where = root.action === 'update' || root.action === 'upsert' ? asRecord(args.where) : null;
158
+ const base = { model: root.model, depth: 0 };
159
+ if (argName === 'create')
160
+ return { ...base, mode: 'create', rowWhere: null };
161
+ if (argName === 'update')
162
+ return { ...base, mode: 'update', rowWhere: where };
163
+ if (argName === 'data') {
164
+ return root.action === 'create'
165
+ ? { ...base, mode: 'create', rowWhere: null }
166
+ : { ...base, mode: 'update', rowWhere: where };
167
+ }
168
+ return { ...base, mode: 'filter', rowWhere: null };
169
+ }
170
+ /**
171
+ * Every nested relation container in a root field's arguments.
172
+ *
173
+ * @param info - The resolver info of the root mutation field.
174
+ * @param args - The field's arguments.
175
+ * @param modelsLongestFirst - Model names sorted longest first.
176
+ * @param root - The root mutation's model and action.
177
+ * @returns The nested writes, outermost first.
178
+ */
179
+ function findNestedWrites(info, args, modelsLongestFirst, root) {
180
+ const found = [];
181
+ const fieldDef = info.parentType.getFields()[info.fieldName];
182
+ if (!fieldDef || !args)
183
+ return found;
184
+ for (const argDef of fieldDef.args) {
185
+ walk(argDef.type, args[argDef.name], argDef.name, argDef.name, rootContext(root, argDef.name, args), modelsLongestFirst, found);
186
+ }
187
+ return found;
188
+ }
189
+ //# sourceMappingURL=nested-write-inspector.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