@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,110 @@
1
+ /**
2
+ * Who may write an entitlement row — pure decision logic.
3
+ *
4
+ * `OrgMembership.role` and `FundAssignment.role` are the authority the rest of
5
+ * the system reads: the platform derives a person's personas from them at
6
+ * sign-in, the tenancy scope derives which organizations and funds they reach,
7
+ * and fund entitlement admits writes to every brokerage account bridged to a
8
+ * fund. Being inside a tenant is therefore not enough to write one of these
9
+ * rows. A plain member who could write them could make themselves OWNER of
10
+ * their organization, or MANAGER of any fund in it, and every downstream
11
+ * authority would follow.
12
+ *
13
+ * A user principal may write an entitlement row only with authority over the
14
+ * tenant the row belongs to:
15
+ *
16
+ * - **OrgMembership** — the caller holds OWNER or ADMIN in that organization.
17
+ * A row whose role is OWNER, before or after the write, needs OWNER: an
18
+ * ADMIN who could grant OWNER could grant it to themselves, and an ADMIN who
19
+ * could demote or remove an OWNER could take the organization from them.
20
+ * - **FundAssignment** — the caller holds OWNER or ADMIN in the fund's
21
+ * organization, or a MANAGER assignment on that same fund. MANAGER is the
22
+ * highest fund role and is the role that runs the fund's team, so admitting
23
+ * it lets no one rise above what they already hold, and it confers nothing
24
+ * on any other fund.
25
+ *
26
+ * One self-service write is admitted without that authority, because the
27
+ * backend can prove from its own rows that nothing is being taken from
28
+ * anyone: the **first owner**. A caller makes themselves OWNER of an
29
+ * organization that is not deleted and has no members and no funds. That is
30
+ * the state an organization is in the moment its creator has written it; once
31
+ * anyone holds a membership, or the organization holds a fund, the exception
32
+ * closes, and an organization with neither has nothing in it to claim.
33
+ *
34
+ * Joining an organization any other way (an invitation, an email-domain
35
+ * match) rests on proof the backend cannot verify from rows the caller is
36
+ * unable to write — an invitation is a single-use token, and a user's email
37
+ * address is a column of their own row — so those memberships are written by
38
+ * a service principal after the platform has checked the proof.
39
+ *
40
+ * Everything here is decided from facts read from the database for this
41
+ * mutation (`src/middleware/mutation-membership-facts.ts`), never from the
42
+ * token's claims.
43
+ *
44
+ * @module auth/membership-write-authority
45
+ */
46
+ /** An entitlement model. */
47
+ export type MembershipModel = 'OrgMembership' | 'FundAssignment';
48
+ /** Whether a model is one of the entitlement models this module decides. */
49
+ export declare function isMembershipModel(model: string): model is MembershipModel;
50
+ /** The organization role that owns an organization. */
51
+ export declare const ORG_OWNER_ROLE = "OWNER";
52
+ /** Organization roles that may manage memberships and fund assignments. */
53
+ export declare const ORG_MANAGEMENT_ROLES: ReadonlySet<string>;
54
+ /** The fund role that may manage its own fund's assignments. */
55
+ export declare const FUND_MANAGER_ROLE = "MANAGER";
56
+ /** What one side of an entitlement write does to one row. */
57
+ export interface MembershipRowWrite {
58
+ /** Whether the row is being created, or an existing row changed or removed. */
59
+ readonly side: 'create' | 'existing';
60
+ /** The organization the row belongs to (for a fund assignment, its fund's). */
61
+ readonly organizationId: string;
62
+ /** For a fund assignment: the fund. */
63
+ readonly fundId?: string;
64
+ /** The person the row is for. */
65
+ readonly memberUserId: string;
66
+ /**
67
+ * Every role the row holds before or after the write: the payload's role
68
+ * (or the column default) for a create; the stored role, and the new one
69
+ * if the write sets it, for an existing row.
70
+ */
71
+ readonly rolesTouched: readonly string[];
72
+ /** Whether the write sets the row's free-form `permissions`. */
73
+ readonly setsPermissions: boolean;
74
+ }
75
+ /** What the caller holds in the row's tenant, read from the database. */
76
+ export interface CallerStanding {
77
+ /** The caller's OrgMembership role in the row's organization, or `null`. */
78
+ readonly orgRole: string | null;
79
+ /** For a fund assignment: the caller's FundAssignment role on that fund, or `null`. */
80
+ readonly fundRole: string | null;
81
+ }
82
+ /** The facts a first-owner OrgMembership create is decided on. */
83
+ export interface FirstOwnerFacts {
84
+ readonly organizationDeleted: boolean;
85
+ readonly organizationMemberCount: number;
86
+ readonly organizationFundCount: number;
87
+ }
88
+ /** Why an entitlement write was admitted or refused. */
89
+ export type MembershipVerdict = 'membership_org_admin' | 'membership_fund_manager' | 'membership_first_owner' | 'tenant_out_of_scope' | 'membership_role_insufficient' | 'membership_owner_requires_owner';
90
+ /** The verdicts that admit the write. */
91
+ export declare const ADMITTING_MEMBERSHIP_VERDICTS: ReadonlySet<MembershipVerdict>;
92
+ /**
93
+ * Whether a write could be a first-owner create: the caller making
94
+ * themselves a member of an organization they do not belong to. The
95
+ * first-owner facts are read only for this shape.
96
+ */
97
+ export declare function isFirstOwnerCandidate(model: MembershipModel, write: MembershipRowWrite, callerId: string, standing: CallerStanding): boolean;
98
+ /**
99
+ * Decide one side of an entitlement write. Pure; performs no I/O.
100
+ *
101
+ * @param model - The entitlement model written.
102
+ * @param write - What the write does to the row.
103
+ * @param callerId - The user principal's subject.
104
+ * @param standing - What the caller holds in the row's tenant.
105
+ * @param firstOwner - The first-owner facts, read only for an
106
+ * {@link isFirstOwnerCandidate} write; `null` otherwise.
107
+ * @returns The verdict.
108
+ */
109
+ export declare function decideMembershipWrite(model: MembershipModel, write: MembershipRowWrite, callerId: string, standing: CallerStanding, firstOwner: FirstOwnerFacts | null): MembershipVerdict;
110
+ //# sourceMappingURL=membership-write-authority.d.ts.map
@@ -0,0 +1,376 @@
1
+ "use strict";
2
+ /**
3
+ * Mutation authorization — pure decision logic.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * The `/graphql` context admits a request with no bearer token as a null
8
+ * principal (context-level enforcement is staged per
9
+ * `docs/security/2026-08-23-graphql-auth-enforcement-runbook.md`), and the
10
+ * generated typegraphql-prisma resolvers expose a create / update / upsert /
11
+ * delete mutation for every model. Together that let any caller who can reach
12
+ * the endpoint rewrite the system of record — including the
13
+ * `TradingPolicy.realtimeTradingEnabled` flag that arms a LIVE brokerage
14
+ * account — with nothing recording who did it.
15
+ *
16
+ * A write is authorised by WHO is asking and WHAT they are writing, so the
17
+ * decision needs both the verified principal and the model the mutation lands
18
+ * on. This module owns that decision; `src/middleware/mutation-auth-guard.ts`
19
+ * wires it into the request lifecycle and supplies the database facts
20
+ * (account ownership) the decision needs.
21
+ *
22
+ * ## Who may write what
23
+ *
24
+ * - `server` (the engine's service JWT, or the static server token) and
25
+ * `admin` may run every mutation. The engine is the system's own writer.
26
+ * - `user` may write only where the product has an ownership model:
27
+ * - `account_owned` — `TradingPolicy` and `AlpacaAccount`: the account must
28
+ * belong to the caller, or be bound to a fund the caller is entitled to
29
+ * (the same OrgMembership / FundAssignment entitlement the tenancy scoping
30
+ * uses). Bulk actions are never user-writable: a `where` filter over many
31
+ * accounts has no single owner to check.
32
+ * - `self` — `User`: only the caller's own row, and only its profile and
33
+ * onboarding fields (`./user-write-content.ts`).
34
+ * - `membership_authority` — `OrgMembership` and `FundAssignment`, the rows
35
+ * every other entitlement is read from: the caller must hold OWNER or
36
+ * ADMIN in the row's organization (OWNER for a row whose role is OWNER),
37
+ * or MANAGER on the assignment's own fund; or the write makes the caller
38
+ * the first owner of an empty organization, the one self-service create
39
+ * the backend can verify from rows the caller cannot write
40
+ * (`./membership-write-authority.ts`). Roles are read from the database
41
+ * for the mutation, never from the token.
42
+ * - `tenant_scoped` — the other tenancy-governed models: the row (for an update,
43
+ * upsert or delete) or the payload's tenant (for a create) must lie in the
44
+ * caller's OrgMembership / FundAssignment entitlement. The guard checks
45
+ * this itself, whatever `TENANCY_SCOPING_MODE` says, because fund
46
+ * entitlement is what authorises `account_owned` writes on fund-bridged
47
+ * accounts: a scope that only observes would let a caller mint the
48
+ * entitlement it is then checked against.
49
+ * - `authenticated` — user-authored content with no finer ownership model
50
+ * yet, restricted per model to the actions the platform performs, and for
51
+ * `AuditLog` and `Configuration` to content a user may author
52
+ * (`./user-write-content.ts`).
53
+ * - `mandate_tenant` — `MandateVersion`: the addressed version's mandate
54
+ * must belong to an organization the caller is a member of or a fund they
55
+ * are entitled to. Nested writes treat it as `authenticated`, as before.
56
+ * - `resolver_authorized` — custom mutations whose resolver performs its own
57
+ * authorization, among them the strategy-draft mutations: the only user
58
+ * writes to `Strategy`, which is otherwise `service_only`.
59
+ * - everything else is `service_only`.
60
+ * - `UserTotp` and the TOTP custom mutations are service-principal only:
61
+ * not even an admin may write a user's second factor through GraphQL
62
+ * ({@link SERVICE_PRINCIPAL_ONLY_MODELS}).
63
+ * - no principal may run no mutation.
64
+ *
65
+ * Nested relation writes are decided hop by hop in `./nested-write-policy.ts`.
66
+ *
67
+ * ## Modes
68
+ *
69
+ * `MUTATION_AUTH_MODE`: `shadow` (count, log and audit what enforcement would
70
+ * deny, change nothing) is the value an UNSET variable resolves to, so the
71
+ * first deploy changes no behaviour and the would-deny series can be read
72
+ * before anything is refused. `enforce` refuses. `off` disables the decision.
73
+ * A value that is SET but unrecognised resolves to `enforce`: an operator who
74
+ * tried to configure the guard and mistyped it must get a guard that refuses,
75
+ * not one that silently observes.
76
+ *
77
+ * `MUTATION_AUTH_ENFORCE_MODELS` (comma-separated model names) escalates the
78
+ * listed models to `enforce` while the global mode is `shadow`, so the
79
+ * capital-bearing models can be contained before every browser-side platform
80
+ * write has migrated to a verified principal. Two rules keep an escalation
81
+ * from being bypassed:
82
+ *
83
+ * - a mutation is decided at the STRICTEST mode among its root model and
84
+ * every model its nested writes reach, so `updateOneUser → alpacaAccounts →
85
+ * tradingPolicy` is enforced when TradingPolicy is;
86
+ * - escalating an account model (`TradingPolicy`, `AlpacaAccount`) escalates
87
+ * the entitlement-source models (`OrgMembership`, `FundAssignment`, `Fund`,
88
+ * `BrokerageAccount`) with it, because the account rule admits a caller on
89
+ * fund entitlement read from those rows.
90
+ *
91
+ * @module auth/mutation-authorization
92
+ */
93
+ Object.defineProperty(exports, "__esModule", { value: true });
94
+ exports.MODEL_WRITE_RULES = exports.STRATEGY_DRAFT_MUTATIONS = exports.ALWAYS_ENFORCED_MUTATION_MODELS = exports.SERVICE_PRINCIPAL_ONLY_MODELS = exports.TOTP_CUSTOM_MUTATIONS = exports.ENTITLEMENT_SOURCE_MODELS = exports.ACCOUNT_MODELS = exports.MUTATION_AUTH_ENFORCE_MODELS_ENV = exports.MUTATION_AUTH_MODE_ENV = void 0;
95
+ exports.getMutationAuthMode = getMutationAuthMode;
96
+ exports.getEnforcedModels = getEnforcedModels;
97
+ exports.expandEnforcedModels = expandEnforcedModels;
98
+ exports.touchesAlwaysEnforced = touchesAlwaysEnforced;
99
+ exports.effectiveModeFor = effectiveModeFor;
100
+ exports.classifyMutationField = classifyMutationField;
101
+ exports.ruleFor = ruleFor;
102
+ exports.evaluateMutationAccess = evaluateMutationAccess;
103
+ const membership_write_authority_1 = require("./membership-write-authority.cjs");
104
+ const tenancy_scope_1 = require("./tenancy-scope.cjs");
105
+ /** Environment variable selecting the global mode. */
106
+ exports.MUTATION_AUTH_MODE_ENV = 'MUTATION_AUTH_MODE';
107
+ /** Environment variable listing models escalated to `enforce`. */
108
+ exports.MUTATION_AUTH_ENFORCE_MODELS_ENV = 'MUTATION_AUTH_ENFORCE_MODELS';
109
+ /**
110
+ * Resolve the global mode. Unset or blank → `shadow`; a recognised value →
111
+ * itself; anything else → `enforce`.
112
+ *
113
+ * @param env - Environment source; injectable for tests.
114
+ * @returns The resolved {@link MutationAuthMode}.
115
+ */
116
+ function getMutationAuthMode(env = process.env) {
117
+ var _a;
118
+ const raw = ((_a = env[exports.MUTATION_AUTH_MODE_ENV]) !== null && _a !== void 0 ? _a : '').trim().toLowerCase();
119
+ if (raw.length === 0)
120
+ return 'shadow';
121
+ if (raw === 'off' || raw === 'shadow' || raw === 'enforce')
122
+ return raw;
123
+ return 'enforce';
124
+ }
125
+ /**
126
+ * The models escalated to `enforce` by {@link MUTATION_AUTH_ENFORCE_MODELS_ENV}.
127
+ *
128
+ * @param env - Environment source; injectable for tests.
129
+ * @returns The set of model names (exact, case-sensitive Prisma names).
130
+ */
131
+ function getEnforcedModels(env = process.env) {
132
+ var _a;
133
+ const raw = (_a = env[exports.MUTATION_AUTH_ENFORCE_MODELS_ENV]) !== null && _a !== void 0 ? _a : '';
134
+ return new Set(raw
135
+ .split(',')
136
+ .map((m) => m.trim())
137
+ .filter((m) => m.length > 0));
138
+ }
139
+ /** The models whose user writes are authorised by row ownership or fund entitlement. */
140
+ exports.ACCOUNT_MODELS = ['TradingPolicy', 'AlpacaAccount'];
141
+ /**
142
+ * The models fund entitlement and the fund-to-account bridge are read from:
143
+ * `resolveEntitlement` reads OrgMembership, Fund and FundAssignment, and a
144
+ * BrokerageAccount binds an AlpacaAccount to its fund.
145
+ */
146
+ exports.ENTITLEMENT_SOURCE_MODELS = [
147
+ 'OrgMembership',
148
+ 'FundAssignment',
149
+ 'Fund',
150
+ 'BrokerageAccount',
151
+ ];
152
+ /**
153
+ * The escalation list with its implied members: an escalated account model
154
+ * brings every entitlement-source model with it.
155
+ */
156
+ function expandEnforcedModels(enforcedModels) {
157
+ if (!exports.ACCOUNT_MODELS.some((model) => enforcedModels.has(model)))
158
+ return enforcedModels;
159
+ return new Set([...enforcedModels, ...exports.ENTITLEMENT_SOURCE_MODELS]);
160
+ }
161
+ /** The TOTP custom mutations (`src/resolvers/custom/UserTotpResolver.ts`), as classified targets. */
162
+ exports.TOTP_CUSTOM_MUTATIONS = [
163
+ 'custom:enrollUserTotp',
164
+ 'custom:confirmUserTotp',
165
+ 'custom:verifyUserTotp',
166
+ 'custom:disableUserTotp',
167
+ ];
168
+ /**
169
+ * Targets only the service principal may write: a user's second factor. An
170
+ * admin principal is a signed-in person, and a person who can rewrite another
171
+ * person's second factor has defeated it, so admin is refused here too.
172
+ */
173
+ exports.SERVICE_PRINCIPAL_ONLY_MODELS = new Set([
174
+ 'UserTotp',
175
+ ...exports.TOTP_CUSTOM_MUTATIONS,
176
+ ]);
177
+ /**
178
+ * Targets decided at `enforce` in every mode, `off` included, whatever the
179
+ * environment says: the desk models and the TOTP mutations.
180
+ *
181
+ * `MUTATION_AUTH_MODE` stages the guard for models that had live writers
182
+ * before it existed — shadow proves no legitimate writer is refused, `off`
183
+ * restores the unguarded behaviour. These targets were born after the guard
184
+ * and have never been written unguarded, so there is no writer for shadow to
185
+ * protect and nothing for `off` to restore; holding them in shadow would let
186
+ * anyone write a user's push endpoints, feature overrides or second factor
187
+ * while the would-deny series accumulated.
188
+ */
189
+ exports.ALWAYS_ENFORCED_MUTATION_MODELS = new Set([
190
+ ...tenancy_scope_1.DESK_MODELS,
191
+ ...exports.TOTP_CUSTOM_MUTATIONS,
192
+ ]);
193
+ /** Whether any of a mutation's written models is always enforced. */
194
+ function touchesAlwaysEnforced(models) {
195
+ return models.some((model) => exports.ALWAYS_ENFORCED_MUTATION_MODELS.has(model));
196
+ }
197
+ /**
198
+ * The mode a mutation is decided in. A mutation writing an always-enforced
199
+ * target ({@link ALWAYS_ENFORCED_MUTATION_MODELS}) is enforced in every mode.
200
+ * Otherwise `off` is a kill switch and wins; a global `enforce` covers every
201
+ * model; under `shadow`, the mutation enforces when ANY model it writes — the
202
+ * root or one reached by a nested write — is escalated (directly, or through
203
+ * {@link expandEnforcedModels}).
204
+ *
205
+ * @param models - The root model and every nested write's model.
206
+ * @param mode - The global mode.
207
+ * @param enforcedModels - The escalation list as configured.
208
+ */
209
+ function effectiveModeFor(models, mode, enforcedModels) {
210
+ if (touchesAlwaysEnforced(models))
211
+ return 'enforce';
212
+ if (mode === 'off' || mode === 'enforce')
213
+ return mode;
214
+ const escalated = expandEnforcedModels(enforcedModels);
215
+ return models.some((model) => escalated.has(model)) ? 'enforce' : 'shadow';
216
+ }
217
+ /**
218
+ * Generated mutation prefixes, longest first so `createManyAndReturn` is not
219
+ * read as `createMany` + a model named `AndReturn…`.
220
+ */
221
+ const GENERATED_PREFIXES = [
222
+ ['createManyAndReturn', 'create', 'many'],
223
+ ['updateManyAndReturn', 'update', 'many'],
224
+ ['createMany', 'create', 'many'],
225
+ ['updateMany', 'update', 'many'],
226
+ ['deleteMany', 'delete', 'many'],
227
+ ['createOne', 'create', 'one'],
228
+ ['updateOne', 'update', 'one'],
229
+ ['upsertOne', 'upsert', 'one'],
230
+ ['deleteOne', 'delete', 'one'],
231
+ ];
232
+ /**
233
+ * Resolve a root mutation field name onto its model and action. A field that
234
+ * is not `<prefix><KnownModel>` is a custom mutation.
235
+ *
236
+ * @param fieldName - `info.fieldName` of a root Mutation field.
237
+ * @param models - Every Prisma model name.
238
+ */
239
+ function classifyMutationField(fieldName, models) {
240
+ for (const [prefix, action, cardinality] of GENERATED_PREFIXES) {
241
+ if (!fieldName.startsWith(prefix))
242
+ continue;
243
+ const model = fieldName.slice(prefix.length);
244
+ if (models.has(model))
245
+ return { model, action, cardinality, fieldName };
246
+ }
247
+ return { model: `custom:${fieldName}`, action: 'custom', cardinality: 'one', fieldName };
248
+ }
249
+ /** The strategy-draft custom mutations (`src/resolvers/custom/StrategyDraftResolver.ts`), as classified targets. */
250
+ exports.STRATEGY_DRAFT_MUTATIONS = [
251
+ 'custom:createStrategyDraft',
252
+ 'custom:saveStrategyDraft',
253
+ 'custom:deleteStrategyDraft',
254
+ 'custom:recordStrategyDraftBacktest',
255
+ ];
256
+ const ONLY = (...actions) => new Set(actions);
257
+ /**
258
+ * Explicit user-write rules. Every model absent here is `service_only`.
259
+ *
260
+ * The `authenticated` rows are the writes the platform's server routes make
261
+ * as the signed-in user today (see the caller inventory in
262
+ * `docs/security/2026-09-24-mutation-authorization-runbook.md`), narrowed to
263
+ * the actions those routes perform. Each is a model with no finer ownership
264
+ * model yet; tightening one to an ownership rule is a follow-up, never a
265
+ * reason to widen another.
266
+ */
267
+ exports.MODEL_WRITE_RULES = new Map([
268
+ ['TradingPolicy', { policy: 'account_owned', userActions: ONLY('create', 'update', 'upsert') }],
269
+ ['AlpacaAccount', { policy: 'account_owned', userActions: ONLY('create', 'update') }],
270
+ ['User', { policy: 'self', userActions: ONLY('update') }],
271
+ ...tenancy_scope_1.GOVERNED_MODELS.filter((model) => !(0, membership_write_authority_1.isMembershipModel)(model)).map((model) => [model, { policy: 'tenant_scoped' }]),
272
+ // The entitlement rows: being inside the tenant is not enough to write the
273
+ // role that decides what everyone in it may do.
274
+ ['OrgMembership', { policy: 'membership_authority' }],
275
+ ['FundAssignment', { policy: 'membership_authority' }],
276
+ ['Configuration', { policy: 'authenticated', userActions: ONLY('upsert') }],
277
+ ['DashboardLayout', { policy: 'authenticated', userActions: ONLY('upsert') }],
278
+ ['Mandate', { policy: 'authenticated', userActions: ONLY('create', 'update') }],
279
+ // A version is the mandate's charter: a user may edit one only inside the
280
+ // tenant (organization or fund) of the mandate it belongs to.
281
+ ['MandateVersion', { policy: 'mandate_tenant', userActions: ONLY('update') }],
282
+ // Desk models with no user writer: overrides are set by operators, and a
283
+ // second factor only by the backend's own TOTP mutations.
284
+ ['FeatureFlagOverride', { policy: 'service_only' }],
285
+ ['UserTotp', { policy: 'service_only' }],
286
+ ['MandateApproval', { policy: 'authenticated', userActions: ONLY('create') }],
287
+ ['Alert', { policy: 'authenticated', userActions: ONLY('update') }],
288
+ ['AuditLog', { policy: 'authenticated', userActions: ONLY('create') }],
289
+ ['Customer', { policy: 'authenticated', userActions: ONLY('update') }],
290
+ ['InvestorTransaction', { policy: 'authenticated', userActions: ONLY('update') }],
291
+ ['custom:updateOrgTradingDefaults', { policy: 'resolver_authorized' }],
292
+ ['custom:updateFundTradingOverrides', { policy: 'resolver_authorized' }],
293
+ // Strategy itself stays service_only: its generated inputs carry the
294
+ // operator-governed columns (desk, lifecycleState, origin). A user writes
295
+ // only their own DRAFT through these, which take no such column and
296
+ // enforce author + state + revision in one statement
297
+ // (`src/resolvers/custom/strategy-draft-service.ts`).
298
+ ...exports.STRATEGY_DRAFT_MUTATIONS.map((field) => [field, { policy: 'resolver_authorized' }]),
299
+ ]);
300
+ const SERVICE_ONLY = { policy: 'service_only' };
301
+ /** The write rule for a model. */
302
+ function ruleFor(model) {
303
+ var _a;
304
+ return (_a = exports.MODEL_WRITE_RULES.get(model)) !== null && _a !== void 0 ? _a : SERVICE_ONLY;
305
+ }
306
+ const allow = (reason) => ({ allowed: true, reason });
307
+ const forbid = (reason) => ({
308
+ allowed: false,
309
+ reason,
310
+ refusal: 'forbidden',
311
+ });
312
+ /**
313
+ * Decide whether a principal may run a mutation. Pure; performs no I/O.
314
+ *
315
+ * @param principal - The verified principal, or `null` for none.
316
+ * @param target - The classified root mutation field.
317
+ * @param facts - Ownership facts resolved by the caller (user principals only).
318
+ */
319
+ function evaluateMutationAccess(principal, target, facts = {}) {
320
+ var _a, _b;
321
+ if (!principal) {
322
+ return { allowed: false, reason: 'unauthenticated', refusal: 'unauthenticated' };
323
+ }
324
+ if (principal.kind === 'server')
325
+ return allow('service_principal');
326
+ const written = [target.model, ...((_a = facts.nestedModels) !== null && _a !== void 0 ? _a : [])];
327
+ if (written.some((model) => exports.SERVICE_PRINCIPAL_ONLY_MODELS.has(model))) {
328
+ return forbid('service_principal_only');
329
+ }
330
+ if (principal.kind === 'admin')
331
+ return allow('admin_principal');
332
+ const rule = ruleFor(target.model);
333
+ if (rule.policy === 'service_only')
334
+ return forbid('model_not_user_writable');
335
+ if (rule.userActions && !rule.userActions.has(target.action)) {
336
+ return forbid('action_not_user_writable');
337
+ }
338
+ if (target.cardinality === 'many')
339
+ return forbid('bulk_not_user_writable');
340
+ if (facts.nestedRefusal)
341
+ return forbid(facts.nestedRefusal);
342
+ if (facts.contentRefusal)
343
+ return forbid(facts.contentRefusal);
344
+ switch (rule.policy) {
345
+ case 'account_owned': {
346
+ const ownership = (_b = facts.ownership) !== null && _b !== void 0 ? _b : { kind: 'unresolved' };
347
+ if (ownership.kind === 'owner')
348
+ return allow('account_owner');
349
+ if (ownership.kind === 'fund_entitled')
350
+ return allow('account_fund_entitled');
351
+ if (ownership.kind === 'other')
352
+ return forbid('not_account_owner');
353
+ return forbid('account_unresolved');
354
+ }
355
+ case 'self':
356
+ return facts.targetsSelf === true ? allow('self') : forbid('not_self');
357
+ case 'membership_authority': {
358
+ const authority = facts.membershipAuthority;
359
+ if (authority === undefined || authority === 'unresolved')
360
+ return forbid('membership_authority_unresolved');
361
+ return membership_write_authority_1.ADMITTING_MEMBERSHIP_VERDICTS.has(authority) ? allow(authority) : forbid(authority);
362
+ }
363
+ case 'tenant_scoped':
364
+ case 'mandate_tenant':
365
+ if (facts.tenantScope === 'in_scope')
366
+ return allow('tenant_scoped');
367
+ if (facts.tenantScope === 'out_of_scope')
368
+ return forbid('tenant_out_of_scope');
369
+ return forbid('tenant_unresolved');
370
+ case 'authenticated':
371
+ return allow('authenticated_user_model');
372
+ case 'resolver_authorized':
373
+ return allow('resolver_authorized');
374
+ }
375
+ }
376
+ //# sourceMappingURL=mutation-authorization.js.map