@adaptic/backend-legacy 0.0.1057 → 0.0.1058

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 (111) 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 +316 -0
  20. package/auth/service-token.d.ts +94 -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 +52 -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/generated/typegraphql-prisma/enhance.cjs +3 -3
  41. package/generated/typegraphql-prisma/index.cjs +6 -6
  42. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  43. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  44. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  45. package/middleware/audit-log-write-redaction.cjs +143 -0
  46. package/middleware/audit-log-write-redaction.d.ts +82 -0
  47. package/middleware/audit-logger.cjs +378 -0
  48. package/middleware/audit-logger.d.ts +158 -0
  49. package/middleware/audit-payload-guard.cjs +107 -0
  50. package/middleware/audit-payload-guard.d.ts +85 -0
  51. package/middleware/auth.cjs +66 -0
  52. package/middleware/auth.d.ts +41 -0
  53. package/middleware/credential-field-guard.cjs +514 -0
  54. package/middleware/credential-field-guard.d.ts +173 -0
  55. package/middleware/generated-type-names.cjs +77 -0
  56. package/middleware/generated-type-names.d.ts +44 -0
  57. package/middleware/graphql-validation-plugin.cjs +310 -0
  58. package/middleware/graphql-validation-plugin.d.ts +98 -0
  59. package/middleware/guard-log-throttle.cjs +89 -0
  60. package/middleware/guard-log-throttle.d.ts +80 -0
  61. package/middleware/index.cjs +57 -0
  62. package/middleware/index.d.ts +14 -0
  63. package/middleware/input-validator.cjs +220 -0
  64. package/middleware/input-validator.d.ts +63 -0
  65. package/middleware/mandate-version-validation.cjs +131 -0
  66. package/middleware/mandate-version-validation.d.ts +41 -0
  67. package/middleware/mutation-account-facts.cjs +223 -0
  68. package/middleware/mutation-account-facts.d.ts +143 -0
  69. package/middleware/mutation-auth-guard.cjs +536 -0
  70. package/middleware/mutation-auth-guard.d.ts +100 -0
  71. package/middleware/mutation-membership-facts.cjs +276 -0
  72. package/middleware/mutation-membership-facts.d.ts +133 -0
  73. package/middleware/mutation-tenant-facts.cjs +132 -0
  74. package/middleware/mutation-tenant-facts.d.ts +81 -0
  75. package/middleware/query-complexity.cjs +182 -0
  76. package/middleware/query-complexity.d.ts +56 -0
  77. package/middleware/rate-limiter.cjs +223 -0
  78. package/middleware/rate-limiter.d.ts +93 -0
  79. package/middleware/rate-tier.cjs +111 -0
  80. package/middleware/rate-tier.d.ts +56 -0
  81. package/middleware/soft-delete.cjs +175 -0
  82. package/middleware/soft-delete.d.ts +146 -0
  83. package/middleware/tenancy-scoping.cjs +229 -0
  84. package/middleware/tenancy-scoping.d.ts +67 -0
  85. package/middleware/trading-policy-audit.cjs +353 -0
  86. package/middleware/trading-policy-audit.d.ts +184 -0
  87. package/middleware/types.cjs +17 -0
  88. package/middleware/types.d.ts +87 -0
  89. package/middleware/validation-examples.cjs +398 -0
  90. package/middleware/validation-examples.d.ts +76 -0
  91. package/package.json +10 -2
  92. package/readers/index.cjs +15 -0
  93. package/readers/index.d.ts +10 -0
  94. package/readers/intraday-lane-prefs.cjs +76 -0
  95. package/readers/intraday-lane-prefs.d.ts +45 -0
  96. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  97. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  98. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  99. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  100. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  101. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  102. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  103. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  104. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  105. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  106. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  107. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  108. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  109. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  110. package/health.cjs +0 -274
  111. package/server.cjs +0 -607
@@ -0,0 +1,276 @@
1
+ "use strict";
2
+ /**
3
+ * The database facts a user principal's OrgMembership or FundAssignment write
4
+ * is decided on (`src/auth/membership-write-authority.ts`).
5
+ *
6
+ * For each row the write reaches — the payload's row for a create, the row the
7
+ * caller's `where` addresses for an update or delete, both for an upsert — it
8
+ * reads the row's organization (and fund), and what the CALLER holds there:
9
+ * their OrgMembership role in that organization and, for a fund assignment,
10
+ * their FundAssignment role on that fund. Roles come from these rows, never
11
+ * from the token's claims, because the token's roles are the platform's
12
+ * persona for the caller and are themselves derived from these rows. Each
13
+ * organization's and fund's standing is read once per mutation.
14
+ *
15
+ * A row that does not exist (an addressed membership, or the fund a payload
16
+ * names) is decided as outside the caller's tenant, the same answer a row in
17
+ * another tenant gets, so the refusal says nothing about which ids exist.
18
+ * Arguments that identify no row at all (no `where`, a payload naming no
19
+ * organization, fund or member) are {@link MembershipFacts} `unresolvable`;
20
+ * a database failure propagates. The guard refuses on both.
21
+ *
22
+ * @module middleware/mutation-membership-facts
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.membershipWriteVerdict = membershipWriteVerdict;
26
+ const membership_write_authority_1 = require("../auth/membership-write-authority.cjs");
27
+ // Each selection and unique selector is pinned to the generated Prisma types,
28
+ // so a renamed column, relation or compound key fails the build rather than
29
+ // failing every membership write at run time.
30
+ const MEMBERSHIP_SELECT = {
31
+ organizationId: true,
32
+ userId: true,
33
+ role: true,
34
+ };
35
+ const ASSIGNMENT_SELECT = {
36
+ fundId: true,
37
+ userId: true,
38
+ role: true,
39
+ fund: { select: { organizationId: true } },
40
+ };
41
+ const MEMBERSHIP_ROLE_SELECT = {
42
+ role: true,
43
+ };
44
+ const ASSIGNMENT_ROLE_SELECT = {
45
+ role: true,
46
+ };
47
+ const FUND_SELECT = {
48
+ organizationId: true,
49
+ };
50
+ const ORGANIZATION_SELECT = {
51
+ deletedAt: true,
52
+ _count: { select: { members: true, funds: true } },
53
+ };
54
+ /** The caller's own membership in an organization, by its compound unique key. */
55
+ function callerMembershipWhere(organizationId, userId) {
56
+ return { organizationId_userId: { organizationId, userId } };
57
+ }
58
+ /** The caller's own assignment on a fund, by its compound unique key. */
59
+ function callerAssignmentWhere(fundId, userId) {
60
+ return { fundId_userId: { fundId, userId } };
61
+ }
62
+ /** The column default for each model's `role` (`prisma/schema.prisma`). */
63
+ const DEFAULT_ROLE = {
64
+ OrgMembership: 'MEMBER',
65
+ FundAssignment: 'VIEWER',
66
+ };
67
+ function asRecord(value) {
68
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
69
+ ? value
70
+ : undefined;
71
+ }
72
+ /** A foreign key from a create payload, in its scalar or `relation.connect.id` form. */
73
+ function connectIdOf(data, scalar, relation) {
74
+ var _a, _b;
75
+ const direct = data[scalar];
76
+ if (typeof direct === 'string' && direct.length > 0)
77
+ return direct;
78
+ const id = (_b = asRecord((_a = asRecord(data[relation])) === null || _a === void 0 ? void 0 : _a.connect)) === null || _b === void 0 ? void 0 : _b.id;
79
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
80
+ }
81
+ /** An enum value written either bare (`OWNER`) or as `{ set: OWNER }`. */
82
+ function enumValueOf(value) {
83
+ var _a;
84
+ if (typeof value === 'string')
85
+ return value;
86
+ const set = (_a = asRecord(value)) === null || _a === void 0 ? void 0 : _a.set;
87
+ return typeof set === 'string' ? set : undefined;
88
+ }
89
+ /** Whether a payload writes the `permissions` list at all. */
90
+ function setsPermissions(data) {
91
+ return data.permissions !== undefined && data.permissions !== null;
92
+ }
93
+ /** The row a create payload would write. */
94
+ async function createdRow(prisma, model, payload) {
95
+ const data = asRecord(payload);
96
+ if (!data)
97
+ return 'malformed';
98
+ const memberUserId = connectIdOf(data, 'userId', 'user');
99
+ if (memberUserId === undefined)
100
+ return 'malformed';
101
+ const role = data.role === undefined ? DEFAULT_ROLE[model] : enumValueOf(data.role);
102
+ if (role === undefined)
103
+ return 'malformed';
104
+ const base = {
105
+ side: 'create',
106
+ memberUserId,
107
+ rolesTouched: [role],
108
+ setsPermissions: setsPermissions(data),
109
+ };
110
+ if (model === 'OrgMembership') {
111
+ const organizationId = connectIdOf(data, 'organizationId', 'organization');
112
+ return organizationId === undefined
113
+ ? 'malformed'
114
+ : { ...base, organizationId };
115
+ }
116
+ const fundId = connectIdOf(data, 'fundId', 'fund');
117
+ if (fundId === undefined)
118
+ return 'malformed';
119
+ const fund = await prisma.fund.findUnique({
120
+ where: { id: fundId },
121
+ select: FUND_SELECT,
122
+ });
123
+ return fund
124
+ ? { ...base, organizationId: fund.organizationId, fundId }
125
+ : 'missing';
126
+ }
127
+ /** The row an update, upsert or delete addresses. */
128
+ async function existingRow(prisma, model, where, update) {
129
+ const newRole = (update === null || update === void 0 ? void 0 : update.role) === undefined ? undefined : enumValueOf(update.role);
130
+ const extra = {
131
+ side: 'existing',
132
+ setsPermissions: update !== undefined && setsPermissions(update),
133
+ };
134
+ if (model === 'OrgMembership') {
135
+ const row = await prisma.orgMembership.findUnique({
136
+ where,
137
+ select: MEMBERSHIP_SELECT,
138
+ });
139
+ if (!(row === null || row === void 0 ? void 0 : row.organizationId) || !row.userId)
140
+ return 'missing';
141
+ return {
142
+ ...extra,
143
+ organizationId: row.organizationId,
144
+ memberUserId: row.userId,
145
+ rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
146
+ };
147
+ }
148
+ const row = await prisma.fundAssignment.findUnique({
149
+ where,
150
+ select: ASSIGNMENT_SELECT,
151
+ });
152
+ if (!(row === null || row === void 0 ? void 0 : row.fundId) || !row.userId || !row.fund)
153
+ return 'missing';
154
+ return {
155
+ ...extra,
156
+ organizationId: row.fund.organizationId,
157
+ fundId: row.fundId,
158
+ memberUserId: row.userId,
159
+ rolesTouched: newRole === undefined ? [row.role] : [row.role, newRole],
160
+ };
161
+ }
162
+ /**
163
+ * The rows a write reaches. An upsert reaches the existing row when there is
164
+ * one (the update branch) and always the create payload's row (the branch
165
+ * taken when there is none).
166
+ */
167
+ async function rowsWritten(prisma, model, target, args) {
168
+ if (target.action === 'create') {
169
+ const row = await createdRow(prisma, model, args.data);
170
+ return row === 'malformed' ? row : [row];
171
+ }
172
+ const where = asRecord(args.where);
173
+ if (!where)
174
+ return 'malformed';
175
+ if (target.action === 'upsert') {
176
+ const created = await createdRow(prisma, model, args.create);
177
+ if (created === 'malformed')
178
+ return created;
179
+ const existing = await existingRow(prisma, model, where, asRecord(args.update));
180
+ return existing === 'missing' ? [created] : [existing, created];
181
+ }
182
+ const update = target.action === 'update' ? asRecord(args.data) : undefined;
183
+ return [await existingRow(prisma, model, where, update)];
184
+ }
185
+ /** Reads what the caller holds in an organization and fund, once each per mutation. */
186
+ function standingReader(prisma, callerId) {
187
+ const orgRoles = new Map();
188
+ const fundRoles = new Map();
189
+ const orgRole = (organizationId) => {
190
+ let role = orgRoles.get(organizationId);
191
+ if (!role) {
192
+ role = prisma.orgMembership
193
+ .findUnique({
194
+ where: callerMembershipWhere(organizationId, callerId),
195
+ select: MEMBERSHIP_ROLE_SELECT,
196
+ })
197
+ .then((row) => { var _a; return (_a = row === null || row === void 0 ? void 0 : row.role) !== null && _a !== void 0 ? _a : null; });
198
+ orgRoles.set(organizationId, role);
199
+ }
200
+ return role;
201
+ };
202
+ const fundRole = (fundId) => {
203
+ let role = fundRoles.get(fundId);
204
+ if (!role) {
205
+ role = prisma.fundAssignment
206
+ .findUnique({
207
+ where: callerAssignmentWhere(fundId, callerId),
208
+ select: ASSIGNMENT_ROLE_SELECT,
209
+ })
210
+ .then((row) => { var _a; return (_a = row === null || row === void 0 ? void 0 : row.role) !== null && _a !== void 0 ? _a : null; });
211
+ fundRoles.set(fundId, role);
212
+ }
213
+ return role;
214
+ };
215
+ return async (write) => {
216
+ const [org, fund] = await Promise.all([
217
+ orgRole(write.organizationId),
218
+ write.fundId === undefined
219
+ ? Promise.resolve(null)
220
+ : fundRole(write.fundId),
221
+ ]);
222
+ return { orgRole: org, fundRole: fund };
223
+ };
224
+ }
225
+ /** The facts a first-owner create is decided on, or `null` when the organization does not exist. */
226
+ async function firstOwnerFactsOf(prisma, organizationId) {
227
+ const organization = await prisma.organization.findUnique({
228
+ where: { id: organizationId },
229
+ select: ORGANIZATION_SELECT,
230
+ });
231
+ if (!organization)
232
+ return null;
233
+ return {
234
+ organizationDeleted: organization.deletedAt !== null,
235
+ organizationMemberCount: organization._count.members,
236
+ organizationFundCount: organization._count.funds,
237
+ };
238
+ }
239
+ /**
240
+ * Decide a user principal's write to an entitlement row from the database.
241
+ * Every row the write reaches must be admitted; the first refusal is returned.
242
+ *
243
+ * @param prisma - A client exposing {@link MembershipFactsPrisma}.
244
+ * @param model - The entitlement model written.
245
+ * @param target - The classified root mutation (`one` cardinality).
246
+ * @param args - The mutation's arguments.
247
+ * @param callerId - The user principal's subject.
248
+ * @throws Whatever the database raised; the caller refuses on it.
249
+ */
250
+ async function membershipWriteVerdict(prisma, model, target, args, callerId) {
251
+ const rows = await rowsWritten(prisma, model, target, args);
252
+ if (rows === 'malformed')
253
+ return { kind: 'unresolvable' };
254
+ const standingOf = standingReader(prisma, callerId);
255
+ let admitted = null;
256
+ for (const row of rows) {
257
+ if (row === 'missing' || row === 'malformed') {
258
+ return row === 'missing'
259
+ ? { kind: 'decided', verdict: 'tenant_out_of_scope' }
260
+ : { kind: 'unresolvable' };
261
+ }
262
+ const standing = await standingOf(row);
263
+ const firstOwner = (0, membership_write_authority_1.isFirstOwnerCandidate)(model, row, callerId, standing)
264
+ ? await firstOwnerFactsOf(prisma, row.organizationId)
265
+ : null;
266
+ const verdict = (0, membership_write_authority_1.decideMembershipWrite)(model, row, callerId, standing, firstOwner);
267
+ if (!membership_write_authority_1.ADMITTING_MEMBERSHIP_VERDICTS.has(verdict)) {
268
+ return { kind: 'decided', verdict };
269
+ }
270
+ admitted !== null && admitted !== void 0 ? admitted : (admitted = verdict);
271
+ }
272
+ return admitted === null
273
+ ? { kind: 'unresolvable' }
274
+ : { kind: 'decided', verdict: admitted };
275
+ }
276
+ //# sourceMappingURL=mutation-membership-facts.js.map
@@ -0,0 +1,133 @@
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 type { MutationTarget } from '../auth/mutation-authorization';
24
+ import { type MembershipModel, type MembershipVerdict } from '../auth/membership-write-authority';
25
+ type Where = Record<string, unknown>;
26
+ declare const MEMBERSHIP_SELECT: {
27
+ readonly organizationId: true;
28
+ readonly userId: true;
29
+ readonly role: true;
30
+ };
31
+ declare const ASSIGNMENT_SELECT: {
32
+ readonly fundId: true;
33
+ readonly userId: true;
34
+ readonly role: true;
35
+ readonly fund: {
36
+ readonly select: {
37
+ readonly organizationId: true;
38
+ };
39
+ };
40
+ };
41
+ declare const MEMBERSHIP_ROLE_SELECT: {
42
+ readonly role: true;
43
+ };
44
+ declare const ASSIGNMENT_ROLE_SELECT: {
45
+ readonly role: true;
46
+ };
47
+ declare const FUND_SELECT: {
48
+ readonly organizationId: true;
49
+ };
50
+ declare const ORGANIZATION_SELECT: {
51
+ readonly deletedAt: true;
52
+ readonly _count: {
53
+ readonly select: {
54
+ readonly members: true;
55
+ readonly funds: true;
56
+ };
57
+ };
58
+ };
59
+ /**
60
+ * The slice of the Prisma client the facts are read through. Declared
61
+ * structurally so the decision can be exercised against a fake; the guard
62
+ * passes the server's PrismaClient.
63
+ */
64
+ export interface MembershipFactsPrisma {
65
+ orgMembership: {
66
+ findUnique(args: {
67
+ where: Where;
68
+ select: typeof MEMBERSHIP_SELECT | typeof MEMBERSHIP_ROLE_SELECT;
69
+ }): Promise<{
70
+ organizationId?: string;
71
+ userId?: string;
72
+ role: string;
73
+ } | null>;
74
+ };
75
+ fundAssignment: {
76
+ findUnique(args: {
77
+ where: Where;
78
+ select: typeof ASSIGNMENT_SELECT | typeof ASSIGNMENT_ROLE_SELECT;
79
+ }): Promise<{
80
+ fundId?: string;
81
+ userId?: string;
82
+ role: string;
83
+ fund?: {
84
+ organizationId: string;
85
+ };
86
+ } | null>;
87
+ };
88
+ fund: {
89
+ findUnique(args: {
90
+ where: {
91
+ id: string;
92
+ };
93
+ select: typeof FUND_SELECT;
94
+ }): Promise<{
95
+ organizationId: string;
96
+ } | null>;
97
+ };
98
+ organization: {
99
+ findUnique(args: {
100
+ where: {
101
+ id: string;
102
+ };
103
+ select: typeof ORGANIZATION_SELECT;
104
+ }): Promise<{
105
+ deletedAt: Date | null;
106
+ _count: {
107
+ members: number;
108
+ funds: number;
109
+ };
110
+ } | null>;
111
+ };
112
+ }
113
+ /** The outcome of {@link membershipWriteVerdict}. */
114
+ export type MembershipFacts = {
115
+ readonly kind: 'decided';
116
+ readonly verdict: MembershipVerdict;
117
+ } | {
118
+ readonly kind: 'unresolvable';
119
+ };
120
+ /**
121
+ * Decide a user principal's write to an entitlement row from the database.
122
+ * Every row the write reaches must be admitted; the first refusal is returned.
123
+ *
124
+ * @param prisma - A client exposing {@link MembershipFactsPrisma}.
125
+ * @param model - The entitlement model written.
126
+ * @param target - The classified root mutation (`one` cardinality).
127
+ * @param args - The mutation's arguments.
128
+ * @param callerId - The user principal's subject.
129
+ * @throws Whatever the database raised; the caller refuses on it.
130
+ */
131
+ export declare function membershipWriteVerdict(prisma: MembershipFactsPrisma, model: MembershipModel, target: MutationTarget, args: Record<string, unknown>, callerId: string): Promise<MembershipFacts>;
132
+ export {};
133
+ //# sourceMappingURL=mutation-membership-facts.d.ts.map
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ /**
3
+ * The mutation guard's own tenancy check for a user principal's write to a
4
+ * tenancy-governed model (Organization, Fund, BrokerageAccount,
5
+ * Notification*, the desk models). The entitlement rows themselves,
6
+ * OrgMembership and FundAssignment, need more than tenancy: the guard decides
7
+ * them on the caller's role (`./mutation-membership-facts.ts`).
8
+ *
9
+ * The tenancy-scoping middleware applies the same scope, but only as strongly
10
+ * as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
11
+ * guard cannot defer to it: fund entitlement — read from OrgMembership, Fund
12
+ * and FundAssignment — is what admits a user's write to every AlpacaAccount
13
+ * and TradingPolicy bridged to the fund, so an entitlement row a caller could
14
+ * write outside their own tenants would let them mint the access they are
15
+ * then checked against. The decision here is applied at the guard's own mode.
16
+ *
17
+ * - create: the payload's tenant must be one the caller is entitled to
18
+ * (`dataInScope`, the tenancy module's own create rule; for a model whose
19
+ * tenant is a parent row's, such as an Ada message's conversation, the
20
+ * parent is read under the caller's write scope).
21
+ * - update / delete: the addressed row must match the caller's WRITE scope
22
+ * (`findUnique` on the caller's `where` AND the write-scope fragment).
23
+ * - upsert: if the row exists it must be in scope; if it does not, the
24
+ * create payload must be.
25
+ *
26
+ * @module middleware/mutation-tenant-facts
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.tenantScopeOf = tenantScopeOf;
30
+ exports.mandateVersionScopeOf = mandateVersionScopeOf;
31
+ const tenancy_scope_1 = require("../auth/tenancy-scope.cjs");
32
+ function readerFor(prisma, model) {
33
+ switch (model) {
34
+ case 'Organization':
35
+ return prisma.organization;
36
+ case 'OrgMembership':
37
+ return prisma.orgMembership;
38
+ case 'Fund':
39
+ return prisma.fund;
40
+ case 'FundAssignment':
41
+ return prisma.fundAssignment;
42
+ case 'BrokerageAccount':
43
+ return prisma.brokerageAccount;
44
+ case 'NotificationEvent':
45
+ return prisma.notificationEvent;
46
+ case 'NotificationDelivery':
47
+ return prisma.notificationDelivery;
48
+ case 'NotificationPreference':
49
+ return prisma.notificationPreference;
50
+ case 'Follow':
51
+ return prisma.follow;
52
+ case 'AutoFollowRule':
53
+ return prisma.autoFollowRule;
54
+ case 'PushSubscription':
55
+ return prisma.pushSubscription;
56
+ case 'AdaConversation':
57
+ return prisma.adaConversation;
58
+ case 'AdaMessage':
59
+ return prisma.adaMessage;
60
+ case 'UserTotp':
61
+ return prisma.userTotp;
62
+ case 'DeskDecision':
63
+ return prisma.deskDecision;
64
+ case 'FeatureFlagOverride':
65
+ return prisma.featureFlagOverride;
66
+ }
67
+ }
68
+ /** Whether a create (or upsert's create) payload lands in the caller's scope. */
69
+ async function createInScope(prisma, model, data, entitlement) {
70
+ if ((0, tenancy_scope_1.dataInScope)(model, data, entitlement))
71
+ return true;
72
+ return (0, tenancy_scope_1.hasCreateParent)(model) ? (0, tenancy_scope_1.parentScopedCreateInScope)(prisma, model, data, entitlement) : false;
73
+ }
74
+ function asRecord(value) {
75
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
76
+ }
77
+ const ID_ONLY = { id: true };
78
+ /**
79
+ * Whether a user's write to a governed model stays inside their entitlement.
80
+ *
81
+ * @throws Whatever the database raised; the caller fails closed on it.
82
+ */
83
+ async function tenantScopeOf(prisma, model, target, args, userId) {
84
+ const entitlement = await (0, tenancy_scope_1.resolveEntitlement)(prisma, userId);
85
+ if (target.action === 'create') {
86
+ return (await createInScope(prisma, model, args.data, entitlement)) ? 'in_scope' : 'out_of_scope';
87
+ }
88
+ const where = asRecord(args.where);
89
+ if (!where)
90
+ return 'out_of_scope';
91
+ const reader = readerFor(prisma, model);
92
+ const scoped = await reader.findUnique({
93
+ where: (0, tenancy_scope_1.injectScopeWhere)(where, (0, tenancy_scope_1.buildWriteScopeWhere)(model, entitlement)),
94
+ select: ID_ONLY,
95
+ });
96
+ if (scoped)
97
+ return 'in_scope';
98
+ if (target.action !== 'upsert')
99
+ return 'out_of_scope';
100
+ const existing = await reader.findUnique({ where, select: ID_ONLY });
101
+ if (existing)
102
+ return 'out_of_scope';
103
+ return (await createInScope(prisma, model, args.create, entitlement)) ? 'in_scope' : 'out_of_scope';
104
+ }
105
+ /**
106
+ * Whether a user's update of a MandateVersion addresses a version whose
107
+ * mandate lies in the caller's entitlement: the mandate's organization is one
108
+ * they are a member of, or its fund one they are entitled to. A user may only
109
+ * update a version (`MODEL_WRITE_RULES`), so the addressed row is all there
110
+ * is to check.
111
+ *
112
+ * @throws Whatever the database raised; the caller fails closed on it.
113
+ */
114
+ async function mandateVersionScopeOf(prisma, args, userId) {
115
+ const where = asRecord(args.where);
116
+ if (!where)
117
+ return 'out_of_scope';
118
+ const entitlement = await (0, tenancy_scope_1.resolveEntitlement)(prisma, userId);
119
+ const scoped = await prisma.mandateVersion.findUnique({
120
+ where: (0, tenancy_scope_1.injectScopeWhere)(where, {
121
+ mandate: {
122
+ OR: [
123
+ { organizationId: { in: [...entitlement.orgIds] } },
124
+ { fundId: { in: [...entitlement.fundIds] } },
125
+ ],
126
+ },
127
+ }),
128
+ select: ID_ONLY,
129
+ });
130
+ return scoped ? 'in_scope' : 'out_of_scope';
131
+ }
132
+ //# sourceMappingURL=mutation-tenant-facts.js.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The mutation guard's own tenancy check for a user principal's write to a
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`).
7
+ *
8
+ * The tenancy-scoping middleware applies the same scope, but only as strongly
9
+ * as `TENANCY_SCOPING_MODE` (default `shadow`) and only on root fields. The
10
+ * guard cannot defer to it: fund entitlement — read from OrgMembership, Fund
11
+ * and FundAssignment — is what admits a user's write to every AlpacaAccount
12
+ * and TradingPolicy bridged to the fund, so an entitlement row a caller could
13
+ * write outside their own tenants would let them mint the access they are
14
+ * then checked against. The decision here is applied at the guard's own mode.
15
+ *
16
+ * - create: the payload's tenant must be one the caller is entitled to
17
+ * (`dataInScope`, the tenancy module's own create rule; for a model whose
18
+ * tenant is a parent row's, such as an Ada message's conversation, the
19
+ * parent is read under the caller's write scope).
20
+ * - update / delete: the addressed row must match the caller's WRITE scope
21
+ * (`findUnique` on the caller's `where` AND the write-scope fragment).
22
+ * - upsert: if the row exists it must be in scope; if it does not, the
23
+ * create payload must be.
24
+ *
25
+ * @module middleware/mutation-tenant-facts
26
+ */
27
+ import type { MutationTarget, TenantScope } from '../auth/mutation-authorization';
28
+ import { type EntitlementPrismaClient, type GovernedModel, type ParentScopeReader } from '../auth/tenancy-scope';
29
+ type Where = Record<string, unknown>;
30
+ /** A delegate that can say whether one row matching a unique `where` exists. */
31
+ export interface ScopedRowReader {
32
+ findUnique(args: {
33
+ where: Where;
34
+ select: {
35
+ id: true;
36
+ };
37
+ }): Promise<{
38
+ id: string;
39
+ } | null>;
40
+ }
41
+ /**
42
+ * The slice of the Prisma client the tenancy check reads. Declared
43
+ * structurally so the guard can be exercised against a fake.
44
+ */
45
+ export interface TenantScopePrisma extends EntitlementPrismaClient {
46
+ organization: ScopedRowReader;
47
+ orgMembership: EntitlementPrismaClient['orgMembership'] & ScopedRowReader;
48
+ fund: EntitlementPrismaClient['fund'] & ScopedRowReader;
49
+ fundAssignment: EntitlementPrismaClient['fundAssignment'] & ScopedRowReader;
50
+ brokerageAccount: ScopedRowReader;
51
+ notificationEvent: ScopedRowReader;
52
+ notificationDelivery: ScopedRowReader;
53
+ notificationPreference: ScopedRowReader;
54
+ follow: ScopedRowReader;
55
+ autoFollowRule: ScopedRowReader;
56
+ pushSubscription: ScopedRowReader;
57
+ adaConversation: ScopedRowReader & ParentScopeReader;
58
+ adaMessage: ScopedRowReader;
59
+ userTotp: ScopedRowReader;
60
+ deskDecision: ScopedRowReader;
61
+ featureFlagOverride: ScopedRowReader;
62
+ mandateVersion: ScopedRowReader;
63
+ }
64
+ /**
65
+ * Whether a user's write to a governed model stays inside their entitlement.
66
+ *
67
+ * @throws Whatever the database raised; the caller fails closed on it.
68
+ */
69
+ export declare function tenantScopeOf(prisma: TenantScopePrisma, model: GovernedModel, target: MutationTarget, args: Record<string, unknown>, userId: string): Promise<TenantScope>;
70
+ /**
71
+ * Whether a user's update of a MandateVersion addresses a version whose
72
+ * mandate lies in the caller's entitlement: the mandate's organization is one
73
+ * they are a member of, or its fund one they are entitled to. A user may only
74
+ * update a version (`MODEL_WRITE_RULES`), so the addressed row is all there
75
+ * is to check.
76
+ *
77
+ * @throws Whatever the database raised; the caller fails closed on it.
78
+ */
79
+ export declare function mandateVersionScopeOf(prisma: TenantScopePrisma, args: Record<string, unknown>, userId: string): Promise<TenantScope>;
80
+ export {};
81
+ //# sourceMappingURL=mutation-tenant-facts.d.ts.map