@adaptic/backend 0.0.1055 → 0.0.1057

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 (199) hide show
  1. package/Account.cjs +14 -0
  2. package/AccountLinkingRequest.cjs +14 -0
  3. package/AccountRiskMetrics.cjs +11 -0
  4. package/AdaConversation.cjs +14 -0
  5. package/Alert.cjs +11 -0
  6. package/Allocation.cjs +11 -0
  7. package/AlpacaAccount.cjs +36 -0
  8. package/Authenticator.cjs +14 -0
  9. package/AutoFollowRule.cjs +14 -0
  10. package/BrokerageAccount.cjs +11 -0
  11. package/Customer.cjs +14 -0
  12. package/DeskDecision.cjs +11 -0
  13. package/FeatureFlagOverride.cjs +14 -0
  14. package/Follow.cjs +14 -0
  15. package/Fund.cjs +56 -0
  16. package/FundAssignment.cjs +14 -0
  17. package/Investor.cjs +14 -0
  18. package/LinkedProvider.cjs +14 -0
  19. package/LlmConfiguration.cjs +14 -0
  20. package/Mandate.cjs +14 -0
  21. package/MandateApproval.cjs +14 -0
  22. package/MandateVersion.cjs +14 -0
  23. package/NotificationDelivery.cjs +14 -0
  24. package/NotificationPreference.cjs +14 -0
  25. package/OrgMembership.cjs +14 -0
  26. package/PolicyOverlay.cjs +64 -0
  27. package/PushSubscription.cjs +14 -0
  28. package/RiskEscalationEvent.cjs +33 -0
  29. package/Session.cjs +14 -0
  30. package/Strategy.cjs +28 -0
  31. package/StrategyHealthSnapshot.cjs +11 -0
  32. package/StrategySubscription.cjs +11 -0
  33. package/TradingPolicy.cjs +6 -0
  34. package/User.cjs +11 -0
  35. package/UserTotp.cjs +14 -0
  36. package/WaitlistEntry.cjs +14 -0
  37. package/esm/Account.mjs +14 -0
  38. package/esm/AccountLinkingRequest.mjs +14 -0
  39. package/esm/AccountRiskMetrics.mjs +11 -0
  40. package/esm/AdaConversation.mjs +14 -0
  41. package/esm/Alert.mjs +11 -0
  42. package/esm/Allocation.mjs +11 -0
  43. package/esm/AlpacaAccount.mjs +36 -0
  44. package/esm/Authenticator.mjs +14 -0
  45. package/esm/AutoFollowRule.mjs +14 -0
  46. package/esm/BrokerageAccount.mjs +11 -0
  47. package/esm/Customer.mjs +14 -0
  48. package/esm/DeskDecision.mjs +11 -0
  49. package/esm/FeatureFlagOverride.mjs +14 -0
  50. package/esm/Follow.mjs +14 -0
  51. package/esm/Fund.mjs +56 -0
  52. package/esm/FundAssignment.mjs +14 -0
  53. package/esm/Investor.mjs +14 -0
  54. package/esm/LinkedProvider.mjs +14 -0
  55. package/esm/LlmConfiguration.mjs +14 -0
  56. package/esm/Mandate.mjs +14 -0
  57. package/esm/MandateApproval.mjs +14 -0
  58. package/esm/MandateVersion.mjs +14 -0
  59. package/esm/NotificationDelivery.mjs +14 -0
  60. package/esm/NotificationPreference.mjs +14 -0
  61. package/esm/OrgMembership.mjs +14 -0
  62. package/esm/PolicyOverlay.mjs +64 -0
  63. package/esm/PushSubscription.mjs +14 -0
  64. package/esm/RiskEscalationEvent.mjs +33 -0
  65. package/esm/Session.mjs +14 -0
  66. package/esm/Strategy.mjs +28 -0
  67. package/esm/StrategyHealthSnapshot.mjs +11 -0
  68. package/esm/StrategySubscription.mjs +11 -0
  69. package/esm/TradingPolicy.mjs +6 -0
  70. package/esm/User.mjs +11 -0
  71. package/esm/UserTotp.mjs +14 -0
  72. package/esm/WaitlistEntry.mjs +14 -0
  73. package/esm/auth/membership-write-authority.d.ts +110 -0
  74. package/esm/auth/membership-write-authority.mjs +125 -0
  75. package/esm/auth/mutation-authorization.d.ts +19 -3
  76. package/esm/auth/mutation-authorization.mjs +21 -2
  77. package/esm/auth/nested-write-policy.d.ts +4 -0
  78. package/esm/auth/nested-write-policy.mjs +19 -0
  79. package/esm/auth/tenancy-scope.d.ts +2 -1
  80. package/esm/auth/tenancy-scope.mjs +2 -1
  81. package/esm/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  82. package/esm/generated/typeStrings/PolicyOverlay.mjs +18 -0
  83. package/esm/generated/typeStrings/TradingPolicy.d.ts +1 -1
  84. package/esm/generated/typeStrings/TradingPolicy.mjs +18 -0
  85. package/esm/generated/typeStrings/index.d.ts +2 -2
  86. package/esm/generated/typegraphql-prisma/enhance.mjs +18 -18
  87. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  88. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.mjs +1 -0
  89. package/esm/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  90. package/esm/generated/typegraphql-prisma/models/TradingPolicy.mjs +27 -0
  91. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  92. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  93. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  94. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  95. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  96. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.mjs +7 -0
  97. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  98. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.mjs +7 -0
  99. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  100. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.mjs +7 -0
  101. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  102. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.mjs +7 -0
  103. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  104. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.mjs +7 -0
  105. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  106. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.mjs +7 -0
  107. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  108. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.mjs +7 -0
  109. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  110. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.mjs +7 -0
  111. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  112. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.mjs +7 -0
  113. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  114. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.mjs +7 -0
  115. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  116. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.mjs +7 -0
  117. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  118. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.mjs +7 -0
  119. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  120. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.mjs +7 -0
  121. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  122. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.mjs +7 -0
  123. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  124. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.mjs +7 -0
  125. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  126. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.mjs +7 -0
  127. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  128. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.mjs +7 -0
  129. package/esm/index.d.ts +1 -0
  130. package/esm/index.mjs +2 -0
  131. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +2 -0
  132. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +141 -10
  133. package/esm/middleware/mutation-account-facts.d.ts +3 -0
  134. package/esm/middleware/mutation-account-facts.mjs +2 -0
  135. package/esm/middleware/mutation-auth-guard.d.ts +4 -2
  136. package/esm/middleware/mutation-auth-guard.mjs +20 -2
  137. package/esm/middleware/mutation-membership-facts.d.ts +133 -0
  138. package/esm/middleware/mutation-membership-facts.mjs +271 -0
  139. package/esm/middleware/mutation-tenant-facts.d.ts +4 -2
  140. package/esm/middleware/mutation-tenant-facts.mjs +4 -2
  141. package/esm/middleware/trading-policy-audit.d.ts +16 -4
  142. package/esm/middleware/trading-policy-audit.mjs +40 -11
  143. package/esm/readers/index.d.ts +10 -0
  144. package/esm/readers/index.mjs +10 -0
  145. package/esm/readers/intraday-lane-prefs.d.ts +45 -0
  146. package/esm/readers/intraday-lane-prefs.mjs +71 -0
  147. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.d.ts +14 -0
  148. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.mjs +107 -0
  149. package/generated/typeStrings/PolicyOverlay.cjs +18 -0
  150. package/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  151. package/generated/typeStrings/TradingPolicy.cjs +18 -0
  152. package/generated/typeStrings/TradingPolicy.d.ts +1 -1
  153. package/generated/typeStrings/index.d.ts +2 -2
  154. package/generated/typegraphql-prisma/enhance.cjs +18 -18
  155. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.cjs +1 -0
  156. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  157. package/generated/typegraphql-prisma/models/TradingPolicy.cjs +7 -0
  158. package/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  159. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  160. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  161. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  162. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  163. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.cjs +6 -0
  164. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  165. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.cjs +6 -0
  166. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  167. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.cjs +6 -0
  168. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  169. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.cjs +6 -0
  170. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  171. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.cjs +6 -0
  172. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  173. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.cjs +6 -0
  174. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  175. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.cjs +6 -0
  176. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  177. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.cjs +6 -0
  178. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  179. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.cjs +6 -0
  180. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  181. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.cjs +6 -0
  182. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  183. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.cjs +6 -0
  184. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  185. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.cjs +6 -0
  186. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  187. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.cjs +6 -0
  188. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  189. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.cjs +6 -0
  190. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  191. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.cjs +6 -0
  192. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  193. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.cjs +6 -0
  194. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  195. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.cjs +6 -0
  196. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  197. package/index.cjs +2 -0
  198. package/index.d.ts +1 -0
  199. package/package.json +1 -1
@@ -0,0 +1,271 @@
1
+ /**
2
+ * The database facts a user principal's OrgMembership or FundAssignment write
3
+ * is decided on (`src/auth/membership-write-authority.ts`).
4
+ *
5
+ * For each row the write reaches — the payload's row for a create, the row the
6
+ * caller's `where` addresses for an update or delete, both for an upsert — it
7
+ * reads the row's organization (and fund), and what the CALLER holds there:
8
+ * their OrgMembership role in that organization and, for a fund assignment,
9
+ * their FundAssignment role on that fund. Roles come from these rows, never
10
+ * from the token's claims, because the token's roles are the platform's
11
+ * persona for the caller and are themselves derived from these rows. Each
12
+ * organization's and fund's standing is read once per mutation.
13
+ *
14
+ * A row that does not exist (an addressed membership, or the fund a payload
15
+ * names) is decided as outside the caller's tenant, the same answer a row in
16
+ * another tenant gets, so the refusal says nothing about which ids exist.
17
+ * Arguments that identify no row at all (no `where`, a payload naming no
18
+ * organization, fund or member) are {@link MembershipFacts} `unresolvable`;
19
+ * a database failure propagates. The guard refuses on both.
20
+ *
21
+ * @module middleware/mutation-membership-facts
22
+ */
23
+ import { ADMITTING_MEMBERSHIP_VERDICTS, decideMembershipWrite, isFirstOwnerCandidate, } from '../auth/membership-write-authority.mjs';
24
+ // Each selection and unique selector is pinned to the generated Prisma types,
25
+ // so a renamed column, relation or compound key fails the build rather than
26
+ // failing every membership write at run time.
27
+ const MEMBERSHIP_SELECT = {
28
+ organizationId: true,
29
+ userId: true,
30
+ role: true,
31
+ };
32
+ const ASSIGNMENT_SELECT = {
33
+ fundId: true,
34
+ userId: true,
35
+ role: true,
36
+ fund: { select: { organizationId: true } },
37
+ };
38
+ const MEMBERSHIP_ROLE_SELECT = {
39
+ role: true,
40
+ };
41
+ const ASSIGNMENT_ROLE_SELECT = {
42
+ role: true,
43
+ };
44
+ const FUND_SELECT = {
45
+ organizationId: true,
46
+ };
47
+ const ORGANIZATION_SELECT = {
48
+ deletedAt: true,
49
+ _count: { select: { members: true, funds: true } },
50
+ };
51
+ /** The caller's own membership in an organization, by its compound unique key. */
52
+ function callerMembershipWhere(organizationId, userId) {
53
+ return { organizationId_userId: { organizationId, userId } };
54
+ }
55
+ /** The caller's own assignment on a fund, by its compound unique key. */
56
+ function callerAssignmentWhere(fundId, userId) {
57
+ return { fundId_userId: { fundId, userId } };
58
+ }
59
+ /** The column default for each model's `role` (`prisma/schema.prisma`). */
60
+ const DEFAULT_ROLE = {
61
+ OrgMembership: 'MEMBER',
62
+ FundAssignment: 'VIEWER',
63
+ };
64
+ function asRecord(value) {
65
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
66
+ ? value
67
+ : undefined;
68
+ }
69
+ /** A foreign key from a create payload, in its scalar or `relation.connect.id` form. */
70
+ function connectIdOf(data, scalar, relation) {
71
+ const direct = data[scalar];
72
+ if (typeof direct === 'string' && direct.length > 0)
73
+ return direct;
74
+ const id = asRecord(asRecord(data[relation])?.connect)?.id;
75
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
76
+ }
77
+ /** An enum value written either bare (`OWNER`) or as `{ set: OWNER }`. */
78
+ function enumValueOf(value) {
79
+ if (typeof value === 'string')
80
+ return value;
81
+ const set = asRecord(value)?.set;
82
+ return typeof set === 'string' ? set : undefined;
83
+ }
84
+ /** Whether a payload writes the `permissions` list at all. */
85
+ function setsPermissions(data) {
86
+ return data.permissions !== undefined && data.permissions !== null;
87
+ }
88
+ /** The row a create payload would write. */
89
+ async function createdRow(prisma, model, payload) {
90
+ const data = asRecord(payload);
91
+ if (!data)
92
+ return 'malformed';
93
+ const memberUserId = connectIdOf(data, 'userId', 'user');
94
+ if (memberUserId === undefined)
95
+ return 'malformed';
96
+ const role = data.role === undefined ? DEFAULT_ROLE[model] : enumValueOf(data.role);
97
+ if (role === undefined)
98
+ return 'malformed';
99
+ const base = {
100
+ side: 'create',
101
+ memberUserId,
102
+ rolesTouched: [role],
103
+ setsPermissions: setsPermissions(data),
104
+ };
105
+ if (model === 'OrgMembership') {
106
+ const organizationId = connectIdOf(data, 'organizationId', 'organization');
107
+ return organizationId === undefined
108
+ ? 'malformed'
109
+ : { ...base, organizationId };
110
+ }
111
+ const fundId = connectIdOf(data, 'fundId', 'fund');
112
+ if (fundId === undefined)
113
+ return 'malformed';
114
+ const fund = await prisma.fund.findUnique({
115
+ where: { id: fundId },
116
+ select: FUND_SELECT,
117
+ });
118
+ return fund
119
+ ? { ...base, organizationId: fund.organizationId, fundId }
120
+ : 'missing';
121
+ }
122
+ /** The row an update, upsert or delete addresses. */
123
+ async function existingRow(prisma, model, where, update) {
124
+ const newRole = update?.role === undefined ? undefined : enumValueOf(update.role);
125
+ const extra = {
126
+ side: 'existing',
127
+ setsPermissions: update !== undefined && setsPermissions(update),
128
+ };
129
+ if (model === 'OrgMembership') {
130
+ const row = await prisma.orgMembership.findUnique({
131
+ where,
132
+ select: MEMBERSHIP_SELECT,
133
+ });
134
+ if (!row?.organizationId || !row.userId)
135
+ return 'missing';
136
+ return {
137
+ ...extra,
138
+ organizationId: row.organizationId,
139
+ memberUserId: row.userId,
140
+ rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
141
+ };
142
+ }
143
+ const row = await prisma.fundAssignment.findUnique({
144
+ where,
145
+ select: ASSIGNMENT_SELECT,
146
+ });
147
+ if (!row?.fundId || !row.userId || !row.fund)
148
+ return 'missing';
149
+ return {
150
+ ...extra,
151
+ organizationId: row.fund.organizationId,
152
+ fundId: row.fundId,
153
+ memberUserId: row.userId,
154
+ rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
155
+ };
156
+ }
157
+ /**
158
+ * The rows a write reaches. An upsert reaches the existing row when there is
159
+ * one (the update branch) and always the create payload's row (the branch
160
+ * taken when there is none).
161
+ */
162
+ async function rowsWritten(prisma, model, target, args) {
163
+ if (target.action === 'create') {
164
+ const row = await createdRow(prisma, model, args.data);
165
+ return row === 'malformed' ? row : [row];
166
+ }
167
+ const where = asRecord(args.where);
168
+ if (!where)
169
+ return 'malformed';
170
+ if (target.action === 'upsert') {
171
+ const created = await createdRow(prisma, model, args.create);
172
+ if (created === 'malformed')
173
+ return created;
174
+ const existing = await existingRow(prisma, model, where, asRecord(args.update));
175
+ return existing === 'missing' ? [created] : [existing, created];
176
+ }
177
+ const update = target.action === 'update' ? asRecord(args.data) : undefined;
178
+ return [await existingRow(prisma, model, where, update)];
179
+ }
180
+ /** Reads what the caller holds in an organization and fund, once each per mutation. */
181
+ function standingReader(prisma, callerId) {
182
+ const orgRoles = new Map();
183
+ const fundRoles = new Map();
184
+ const orgRole = (organizationId) => {
185
+ let role = orgRoles.get(organizationId);
186
+ if (!role) {
187
+ role = prisma.orgMembership
188
+ .findUnique({
189
+ where: callerMembershipWhere(organizationId, callerId),
190
+ select: MEMBERSHIP_ROLE_SELECT,
191
+ })
192
+ .then((row) => row?.role ?? null);
193
+ orgRoles.set(organizationId, role);
194
+ }
195
+ return role;
196
+ };
197
+ const fundRole = (fundId) => {
198
+ let role = fundRoles.get(fundId);
199
+ if (!role) {
200
+ role = prisma.fundAssignment
201
+ .findUnique({
202
+ where: callerAssignmentWhere(fundId, callerId),
203
+ select: ASSIGNMENT_ROLE_SELECT,
204
+ })
205
+ .then((row) => row?.role ?? null);
206
+ fundRoles.set(fundId, role);
207
+ }
208
+ return role;
209
+ };
210
+ return async (write) => {
211
+ const [org, fund] = await Promise.all([
212
+ orgRole(write.organizationId),
213
+ write.fundId === undefined
214
+ ? Promise.resolve(null)
215
+ : fundRole(write.fundId),
216
+ ]);
217
+ return { orgRole: org, fundRole: fund };
218
+ };
219
+ }
220
+ /** The facts a first-owner create is decided on, or `null` when the organization does not exist. */
221
+ async function firstOwnerFactsOf(prisma, organizationId) {
222
+ const organization = await prisma.organization.findUnique({
223
+ where: { id: organizationId },
224
+ select: ORGANIZATION_SELECT,
225
+ });
226
+ if (!organization)
227
+ return null;
228
+ return {
229
+ organizationDeleted: organization.deletedAt !== null,
230
+ organizationMemberCount: organization._count.members,
231
+ organizationFundCount: organization._count.funds,
232
+ };
233
+ }
234
+ /**
235
+ * Decide a user principal's write to an entitlement row from the database.
236
+ * Every row the write reaches must be admitted; the first refusal is returned.
237
+ *
238
+ * @param prisma - A client exposing {@link MembershipFactsPrisma}.
239
+ * @param model - The entitlement model written.
240
+ * @param target - The classified root mutation (`one` cardinality).
241
+ * @param args - The mutation's arguments.
242
+ * @param callerId - The user principal's subject.
243
+ * @throws Whatever the database raised; the caller refuses on it.
244
+ */
245
+ export async function membershipWriteVerdict(prisma, model, target, args, callerId) {
246
+ const rows = await rowsWritten(prisma, model, target, args);
247
+ if (rows === 'malformed')
248
+ return { kind: 'unresolvable' };
249
+ const standingOf = standingReader(prisma, callerId);
250
+ let admitted = null;
251
+ for (const row of rows) {
252
+ if (row === 'missing' || row === 'malformed') {
253
+ return row === 'missing'
254
+ ? { kind: 'decided', verdict: 'tenant_out_of_scope' }
255
+ : { kind: 'unresolvable' };
256
+ }
257
+ const standing = await standingOf(row);
258
+ const firstOwner = isFirstOwnerCandidate(model, row, callerId, standing)
259
+ ? await firstOwnerFactsOf(prisma, row.organizationId)
260
+ : null;
261
+ const verdict = decideMembershipWrite(model, row, callerId, standing, firstOwner);
262
+ if (!ADMITTING_MEMBERSHIP_VERDICTS.has(verdict)) {
263
+ return { kind: 'decided', verdict };
264
+ }
265
+ admitted ??= verdict;
266
+ }
267
+ return admitted === null
268
+ ? { kind: 'unresolvable' }
269
+ : { kind: 'decided', verdict: admitted };
270
+ }
271
+ //# sourceMappingURL=mutation-membership-facts.js.map
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * The mutation guard's own tenancy check for a user principal's write to a
3
- * tenancy-governed model (Organization, OrgMembership, Fund, FundAssignment,
4
- * BrokerageAccount, Notification*).
3
+ * tenancy-governed model (Organization, Fund, BrokerageAccount,
4
+ * Notification*, the desk models). The entitlement rows themselves,
5
+ * OrgMembership and FundAssignment, need more than tenancy: the guard decides
6
+ * them on the caller's role (`./mutation-membership-facts.ts`).
5
7
  *
6
8
  * The tenancy-scoping middleware applies the same scope, but only as strongly
7
9
  * as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * The mutation guard's own tenancy check for a user principal's write to a
3
- * tenancy-governed model (Organization, OrgMembership, Fund, FundAssignment,
4
- * BrokerageAccount, Notification*).
3
+ * tenancy-governed model (Organization, Fund, BrokerageAccount,
4
+ * Notification*, the desk models). The entitlement rows themselves,
5
+ * OrgMembership and FundAssignment, need more than tenancy: the guard decides
6
+ * them on the caller's role (`./mutation-membership-facts.ts`).
5
7
  *
6
8
  * The tenancy-scoping middleware applies the same scope, but only as strongly
7
9
  * as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
@@ -40,15 +40,27 @@
40
40
  *
41
41
  * @module middleware/trading-policy-audit
42
42
  */
43
+ import type { Prisma } from '@prisma/client';
43
44
  import { Counter } from 'prom-client';
44
45
  import type { MutationAction, MutationAuthReason } from '../auth/mutation-authorization';
45
46
  import type { BackendPrincipal } from '../auth/token-verifier';
46
47
  /** Header a caller uses to state why it is changing a policy. */
47
48
  export declare const CHANGE_REASON_HEADER = "x-adaptic-change-reason";
48
- /** The switches whose change arms or disarms an account. */
49
- export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode"];
50
- /** The switch values of one policy as they stood before the write. */
51
- export type TradingSwitches = Partial<Record<(typeof TRADING_SWITCH_FIELDS)[number], boolean | string | null>>;
49
+ /**
50
+ * The switches whose change arms or disarms an account. `intradayLanePrefs`
51
+ * is the single carrier of the account's multi-lane opt-in (its `armed`
52
+ * member), so a write to it can arm the lanes exactly as a write to
53
+ * `realtimeTradingEnabled` can arm the account: it is audited, warned on and
54
+ * classified as a switch like the others.
55
+ */
56
+ export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode", "intradayLanePrefs"];
57
+ /** One trading switch's name. */
58
+ export type TradingSwitchField = (typeof TRADING_SWITCH_FIELDS)[number];
59
+ /**
60
+ * The switch values of one policy as they stood before the write. A JSON
61
+ * switch (`intradayLanePrefs`) is recorded as its stored value.
62
+ */
63
+ export type TradingSwitches = Partial<Record<TradingSwitchField, boolean | string | Prisma.JsonValue | null>>;
52
64
  /**
53
65
  * How a touched policy's account was identified: read from the database
54
66
  * (`resolved`), created by this same mutation (`new_account`), or not
@@ -49,12 +49,19 @@ export const CHANGE_REASON_HEADER = 'x-adaptic-change-reason';
49
49
  const MAX_CHANGE_REASON_LENGTH = 500;
50
50
  /** Longest free-text header value (user agent, origin) recorded. */
51
51
  const MAX_HEADER_LENGTH = 300;
52
- /** The switches whose change arms or disarms an account. */
52
+ /**
53
+ * The switches whose change arms or disarms an account. `intradayLanePrefs`
54
+ * is the single carrier of the account's multi-lane opt-in (its `armed`
55
+ * member), so a write to it can arm the lanes exactly as a write to
56
+ * `realtimeTradingEnabled` can arm the account: it is audited, warned on and
57
+ * classified as a switch like the others.
58
+ */
53
59
  export const TRADING_SWITCH_FIELDS = [
54
60
  'realtimeTradingEnabled',
55
61
  'paperTradingOnly',
56
62
  'killSwitchEnabled',
57
63
  'autonomyMode',
64
+ 'intradayLanePrefs',
58
65
  ];
59
66
  /**
60
67
  * Whether a write may touch a LIVE account's switches: a resolved LIVE
@@ -128,7 +135,7 @@ export function touchesTradingSwitch(requested) {
128
135
  if (requested === null || typeof requested !== 'object')
129
136
  return false;
130
137
  for (const [key, child] of Object.entries(requested)) {
131
- if (TRADING_SWITCH_FIELDS.includes(key))
138
+ if (isTradingSwitchField(key))
132
139
  return true;
133
140
  if (touchesTradingSwitch(child))
134
141
  return true;
@@ -215,13 +222,35 @@ export async function writeResultRow(prisma, entry, attemptId, outcome, errorCod
215
222
  throw error;
216
223
  }
217
224
  }
218
- /** The value each trading switch moves to when a write DISARMS it. */
219
- const DISARMED_VALUES = {
220
- realtimeTradingEnabled: new Set([false]),
221
- killSwitchEnabled: new Set([true]),
222
- paperTradingOnly: new Set([true]),
223
- autonomyMode: new Set(['ADVISORY_ONLY', 'EMERGENCY_SAFE_MODE']),
225
+ /**
226
+ * Whether an `intradayLanePrefs` value leaves the account's lanes disarmed:
227
+ * a null (no preferences, which reads as disarmed) or an object whose `armed`
228
+ * member is exactly `false`. Any other value may arm, so it is not a disarm.
229
+ */
230
+ function isDisarmedLanePrefs(value) {
231
+ if (value === null)
232
+ return true;
233
+ if (typeof value !== 'object' || Array.isArray(value))
234
+ return false;
235
+ return value.armed === false;
236
+ }
237
+ /** Whether a value is the one a write DISARMING each trading switch sets. */
238
+ const DISARMS = {
239
+ realtimeTradingEnabled: (value) => value === false,
240
+ killSwitchEnabled: (value) => value === true,
241
+ paperTradingOnly: (value) => value === true,
242
+ autonomyMode: (value) => value === 'ADVISORY_ONLY' || value === 'EMERGENCY_SAFE_MODE',
243
+ intradayLanePrefs: isDisarmedLanePrefs,
224
244
  };
245
+ /**
246
+ * Switches whose generated update input carries the value itself rather than
247
+ * `{ set: value }`: a JSON column is written as its new value.
248
+ */
249
+ const JSON_SWITCH_FIELDS = new Set(['intradayLanePrefs']);
250
+ /** Whether a data key names a trading switch. */
251
+ function isTradingSwitchField(key) {
252
+ return TRADING_SWITCH_FIELDS.includes(key);
253
+ }
225
254
  /** Bookkeeping fields a disarm write may also set. */
226
255
  const DISARM_BOOKKEEPING_FIELDS = new Set(['lastModifiedBy', 'lastModifiedAt', 'version']);
227
256
  /** The value a generated update input sets: `{ set: v }` → `v`; anything else is not a plain set. */
@@ -254,11 +283,11 @@ export function isDisarmOnlyPolicyWrite(target, args) {
254
283
  for (const [key, raw] of Object.entries(data)) {
255
284
  if (raw === undefined)
256
285
  continue;
257
- const set = setValueOf(raw);
286
+ const set = isTradingSwitchField(key) && JSON_SWITCH_FIELDS.has(key) ? { value: raw } : setValueOf(raw);
258
287
  if (!set)
259
288
  return false;
260
- if (key in DISARMED_VALUES) {
261
- if (!DISARMED_VALUES[key].has(set.value))
289
+ if (isTradingSwitchField(key)) {
290
+ if (!DISARMS[key](set.value))
262
291
  return false;
263
292
  disarmed += 1;
264
293
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Narrow, hand-written reads of fields that the generated selection sets
3
+ * deliberately leave out (`GQL.SKIP`). Each read selects only its own field and
4
+ * the row's identity, so it fails alone and cannot take a generated read down
5
+ * with it.
6
+ *
7
+ * @module readers
8
+ */
9
+ export { readIntradayLanePrefs, INTRADAY_LANE_PREFS_SELECTION, type IntradayLanePrefsRow, } from './intraday-lane-prefs';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Narrow, hand-written reads of fields that the generated selection sets
3
+ * deliberately leave out (`GQL.SKIP`). Each read selects only its own field and
4
+ * the row's identity, so it fails alone and cannot take a generated read down
5
+ * with it.
6
+ *
7
+ * @module readers
8
+ */
9
+ export { readIntradayLanePrefs, INTRADAY_LANE_PREFS_SELECTION, } from './intraday-lane-prefs.mjs';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The read of one account's multi-lane intraday preferences
3
+ * (`TradingPolicy.intradayLanePrefs`).
4
+ *
5
+ * The field is excluded from every generated selection set (`GQL.SKIP`). A
6
+ * GraphQL server whose schema predates the column rejects the WHOLE operation
7
+ * that selects it, and the generated TradingPolicy and AlpacaAccount selection
8
+ * sets carry the engine's order-chokepoint policy read and its broker-credential
9
+ * read. Leaving the field out of those reads keeps them working against a
10
+ * server whether or not the migration has run. This read is the only place the
11
+ * field is selected, so a server without the column fails this read alone.
12
+ *
13
+ * The read never turns a failure into a value. A transport or GraphQL error
14
+ * throws, and so does an answer that omits the field. Only a backend that
15
+ * answers "no policy row" yields `null`. The consumer (the engine's lane-arming
16
+ * resolver) maps every one of these outcomes to "lanes disarmed". It never
17
+ * blocks an exit, because the preferences govern entries only.
18
+ *
19
+ * @module readers/intraday-lane-prefs
20
+ */
21
+ import type { TradingPolicy as TradingPolicyType } from '../generated/typegraphql-prisma/models/TradingPolicy';
22
+ import { type ApolloClientType, type NormalizedCacheObject } from '../client';
23
+ /** The fields this read selects, and nothing else. */
24
+ export declare const INTRADAY_LANE_PREFS_SELECTION = "id alpacaAccountId intradayLanePrefs";
25
+ /** One account's lane preferences, as stored. */
26
+ export interface IntradayLanePrefsRow {
27
+ /** The TradingPolicy row id. */
28
+ readonly policyId: string;
29
+ /** The account the policy governs. */
30
+ readonly alpacaAccountId: string;
31
+ /** The stored preferences; `null` when none are set (lanes disarmed). */
32
+ readonly intradayLanePrefs: Exclude<TradingPolicyType['intradayLanePrefs'], undefined>;
33
+ }
34
+ /**
35
+ * Read one account's lane preferences.
36
+ *
37
+ * @param alpacaAccountId - The account whose TradingPolicy to read.
38
+ * @param globalClient - The backend client; the shared client when omitted.
39
+ * @returns The stored preferences, or `null` when the account has no
40
+ * TradingPolicy row.
41
+ * @throws When the backend fails, answers with errors (including a server
42
+ * whose schema predates the column), or answers without the field.
43
+ */
44
+ export declare function readIntradayLanePrefs(alpacaAccountId: string, globalClient?: ApolloClientType<NormalizedCacheObject>): Promise<IntradayLanePrefsRow | null>;
45
+ //# sourceMappingURL=intraday-lane-prefs.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { getApolloClient, getApolloModules } from '../client.mjs';
2
+ /** The fields this read selects, and nothing else. */
3
+ export const INTRADAY_LANE_PREFS_SELECTION = 'id alpacaAccountId intradayLanePrefs';
4
+ /** The backend's error message when no TradingPolicy row matches. */
5
+ const NO_POLICY_MESSAGE = 'No TradingPolicy found';
6
+ /** The shape of the `getTradingPolicy` answer this read accepts. */
7
+ function rowOf(value) {
8
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
9
+ throw new Error('readIntradayLanePrefs: the backend answered with no policy object');
10
+ }
11
+ const record = value;
12
+ if (typeof record.id !== 'string' || typeof record.alpacaAccountId !== 'string') {
13
+ throw new Error('readIntradayLanePrefs: the policy answer has no id or alpacaAccountId');
14
+ }
15
+ if (!('intradayLanePrefs' in record) || record.intradayLanePrefs === undefined) {
16
+ throw new Error('readIntradayLanePrefs: the policy answer omits intradayLanePrefs');
17
+ }
18
+ return {
19
+ policyId: record.id,
20
+ alpacaAccountId: record.alpacaAccountId,
21
+ intradayLanePrefs: record.intradayLanePrefs,
22
+ };
23
+ }
24
+ /**
25
+ * Read one account's lane preferences.
26
+ *
27
+ * @param alpacaAccountId - The account whose TradingPolicy to read.
28
+ * @param globalClient - The backend client; the shared client when omitted.
29
+ * @returns The stored preferences, or `null` when the account has no
30
+ * TradingPolicy row.
31
+ * @throws When the backend fails, answers with errors (including a server
32
+ * whose schema predates the column), or answers without the field.
33
+ */
34
+ export async function readIntradayLanePrefs(alpacaAccountId, globalClient) {
35
+ const [modules, client] = await Promise.all([
36
+ getApolloModules(),
37
+ globalClient ? Promise.resolve(globalClient) : getApolloClient(),
38
+ ]);
39
+ const query = modules.gql `
40
+ query readIntradayLanePrefs($where: TradingPolicyWhereUniqueInput!) {
41
+ getTradingPolicy(where: $where) {
42
+ ${INTRADAY_LANE_PREFS_SELECTION}
43
+ }
44
+ }`;
45
+ let response;
46
+ try {
47
+ response = await client.query({
48
+ query,
49
+ variables: { where: { alpacaAccountId } },
50
+ fetchPolicy: 'network-only',
51
+ });
52
+ }
53
+ catch (error) {
54
+ if (error instanceof Error && error.message === NO_POLICY_MESSAGE)
55
+ return null;
56
+ throw error;
57
+ }
58
+ if (response.errors && response.errors.length > 0) {
59
+ if (response.errors[0].message === NO_POLICY_MESSAGE)
60
+ return null;
61
+ throw new Error(`readIntradayLanePrefs: ${response.errors[0].message}`);
62
+ }
63
+ const policy = response.data?.getTradingPolicy;
64
+ if (policy === null)
65
+ return null;
66
+ if (policy === undefined) {
67
+ throw new Error('readIntradayLanePrefs: the backend answered with no getTradingPolicy field');
68
+ }
69
+ return rowOf(policy);
70
+ }
71
+ //# sourceMappingURL=intraday-lane-prefs.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Exercises the TradingPolicy lane-preferences carrier against a real Postgres
3
+ * built from the migration history: a policy created without it reads back
4
+ * null (disarmed) through the generated GraphQL resolvers, a written value
5
+ * round-trips, it can be set to armed:false and cleared back to null, and the
6
+ * migration's own SQL runs down and up again inside a transaction that is
7
+ * rolled back, leaving the database as it was.
8
+ *
9
+ * Assembled like `desk-attribution-roundtrip.harness.ts`. Needs
10
+ * `LANE_IT_DATABASE_URL` pointing at a disposable migrated database. Output is
11
+ * printed between `<<<RESULTS>>>` and `<<<END>>>`; seeded rows are removed.
12
+ */
13
+ import 'reflect-metadata';
14
+ //# sourceMappingURL=trading-policy-lane-fields-roundtrip.harness.d.ts.map