@adaptic/backend 0.0.1038 → 0.0.1040

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 (85) hide show
  1. package/esm/auth/authorization-map.d.ts +13 -1
  2. package/esm/auth/authorization-map.d.ts.map +1 -1
  3. package/esm/auth/authorization-map.js.map +1 -1
  4. package/esm/auth/authorization-map.mjs +14 -1
  5. package/esm/auth/credential-fields.d.ts +19 -0
  6. package/esm/auth/credential-fields.d.ts.map +1 -0
  7. package/esm/auth/credential-fields.js.map +1 -0
  8. package/esm/auth/credential-fields.mjs +42 -0
  9. package/esm/auth/credential-redaction.d.ts +56 -0
  10. package/esm/auth/credential-redaction.d.ts.map +1 -0
  11. package/esm/auth/credential-redaction.js.map +1 -0
  12. package/esm/auth/credential-redaction.mjs +99 -0
  13. package/esm/auth/mutation-authorization.d.ts +206 -0
  14. package/esm/auth/mutation-authorization.d.ts.map +1 -0
  15. package/esm/auth/mutation-authorization.js.map +1 -0
  16. package/esm/auth/mutation-authorization.mjs +271 -0
  17. package/esm/auth/nested-write-inspector.d.ts +94 -0
  18. package/esm/auth/nested-write-inspector.d.ts.map +1 -0
  19. package/esm/auth/nested-write-inspector.js.map +1 -0
  20. package/esm/auth/nested-write-inspector.mjs +185 -0
  21. package/esm/auth/nested-write-policy.d.ts +95 -0
  22. package/esm/auth/nested-write-policy.d.ts.map +1 -0
  23. package/esm/auth/nested-write-policy.js.map +1 -0
  24. package/esm/auth/nested-write-policy.mjs +154 -0
  25. package/esm/auth/service-token.d.ts +11 -1
  26. package/esm/auth/service-token.d.ts.map +1 -1
  27. package/esm/auth/service-token.js.map +1 -1
  28. package/esm/auth/service-token.mjs +31 -5
  29. package/esm/auth/token-verifier.d.ts +9 -1
  30. package/esm/auth/token-verifier.d.ts.map +1 -1
  31. package/esm/auth/token-verifier.js.map +1 -1
  32. package/esm/auth/user-write-content.d.ts +41 -0
  33. package/esm/auth/user-write-content.d.ts.map +1 -0
  34. package/esm/auth/user-write-content.js.map +1 -0
  35. package/esm/auth/user-write-content.mjs +100 -0
  36. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +55 -0
  37. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts.map +1 -0
  38. package/esm/middleware/__tests__/credential-field-coverage.harness.js.map +1 -0
  39. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +438 -0
  40. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
  41. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
  42. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
  43. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
  44. package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
  45. package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
  46. package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
  47. package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
  48. package/esm/middleware/audit-logger.d.ts +18 -1
  49. package/esm/middleware/audit-logger.d.ts.map +1 -1
  50. package/esm/middleware/audit-logger.js.map +1 -1
  51. package/esm/middleware/audit-logger.mjs +36 -13
  52. package/esm/middleware/audit-payload-guard.d.ts +85 -0
  53. package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
  54. package/esm/middleware/audit-payload-guard.js.map +1 -0
  55. package/esm/middleware/audit-payload-guard.mjs +97 -0
  56. package/esm/middleware/credential-field-guard.d.ts +55 -7
  57. package/esm/middleware/credential-field-guard.d.ts.map +1 -1
  58. package/esm/middleware/credential-field-guard.js.map +1 -1
  59. package/esm/middleware/credential-field-guard.mjs +275 -106
  60. package/esm/middleware/generated-type-names.d.ts +44 -0
  61. package/esm/middleware/generated-type-names.d.ts.map +1 -0
  62. package/esm/middleware/generated-type-names.js.map +1 -0
  63. package/esm/middleware/generated-type-names.mjs +73 -0
  64. package/esm/middleware/guard-log-throttle.d.ts +80 -0
  65. package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
  66. package/esm/middleware/guard-log-throttle.js.map +1 -0
  67. package/esm/middleware/guard-log-throttle.mjs +87 -0
  68. package/esm/middleware/mutation-account-facts.d.ts +140 -0
  69. package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
  70. package/esm/middleware/mutation-account-facts.js.map +1 -0
  71. package/esm/middleware/mutation-account-facts.mjs +212 -0
  72. package/esm/middleware/mutation-auth-guard.d.ts +82 -0
  73. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
  74. package/esm/middleware/mutation-auth-guard.js.map +1 -0
  75. package/esm/middleware/mutation-auth-guard.mjs +425 -0
  76. package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
  77. package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
  78. package/esm/middleware/mutation-tenant-facts.js.map +1 -0
  79. package/esm/middleware/mutation-tenant-facts.mjs +75 -0
  80. package/esm/middleware/trading-policy-audit.d.ts +172 -0
  81. package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
  82. package/esm/middleware/trading-policy-audit.js.map +1 -0
  83. package/esm/middleware/trading-policy-audit.mjs +309 -0
  84. package/package.json +1 -1
  85. package/server.cjs +27 -2
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Out-of-process harness for `mutation-auth-guard.test.ts`.
3
+ *
4
+ * The generated TypeGraphQL resolvers need `emitDecoratorMetadata`, which
5
+ * vitest's esbuild transform does not emit, so a schema built from them cannot
6
+ * be constructed inside the vitest worker. This harness runs under ts-node,
7
+ * builds a schema from the GENERATED TradingPolicy, AlpacaAccount, User,
8
+ * tenancy (Organization, OrgMembership, Fund, FundAssignment,
9
+ * BrokerageAccount), AuditLog and Configuration resolvers with the guard
10
+ * installed exactly as `server.ts` installs it
11
+ * (`installMutationAuthGuard` on the built schema),
12
+ * serves it through a real ApolloServer carrying the production HTTP-status
13
+ * plugin (so a refusal's HTTP status is observed, not assumed), runs every
14
+ * scenario against a recording fake Prisma client, and prints one JSON
15
+ * document the test asserts on.
16
+ *
17
+ * Run directly:
18
+ * npx ts-node --transpile-only src/middleware/__tests__/mutation-auth-guard.harness.ts
19
+ */
20
+ import 'reflect-metadata';
21
+ import { ApolloServer } from '@apollo/server';
22
+ import { buildSchema } from 'type-graphql';
23
+ import { TradingPolicyCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/TradingPolicy/TradingPolicyCrudResolver.mjs';
24
+ import { AlpacaAccountCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/AlpacaAccount/AlpacaAccountCrudResolver.mjs';
25
+ import { UserCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/User/UserCrudResolver.mjs';
26
+ import { OrganizationCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Organization/OrganizationCrudResolver.mjs';
27
+ import { OrgMembershipCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/OrgMembership/OrgMembershipCrudResolver.mjs';
28
+ import { FundCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Fund/FundCrudResolver.mjs';
29
+ import { FundAssignmentCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/FundAssignment/FundAssignmentCrudResolver.mjs';
30
+ import { BrokerageAccountCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/BrokerageAccount/BrokerageAccountCrudResolver.mjs';
31
+ import { AuditLogCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/AuditLog/AuditLogCrudResolver.mjs';
32
+ import { ConfigurationCrudResolver } from '../../generated/typegraphql-prisma/resolvers/crud/Configuration/ConfigurationCrudResolver.mjs';
33
+ import { createHttpStatusMapperPlugin } from '../../plugins/http-status-mapper.mjs';
34
+ import { installMutationAuthGuard, mutationAuthorizationTotal, resetMutationAuthLogThrottle, } from '../mutation-auth-guard.mjs';
35
+ import { mutationAuditBypassedTotal, mutationAuditWriteFailuresTotal } from '../trading-policy-audit.mjs';
36
+ export const API_KEY = 'PKMUTATIONGUARDKEY00000000';
37
+ export const API_SECRET = 'mutation-guard-secret-value-that-must-never-leak';
38
+ const U_OWNER = '11111111-1111-4111-8111-111111111111';
39
+ const U_STRANGER = '22222222-2222-4222-8222-222222222222';
40
+ const U_FUND = '33333333-3333-4333-8333-333333333333';
41
+ const U_OTHER = '44444444-4444-4444-8444-444444444444';
42
+ const FUND_1 = '55555555-5555-4555-8555-555555555555';
43
+ const FUND_2 = '77777777-7777-4777-8777-777777777777';
44
+ const ORG_2 = '88888888-8888-4888-8888-888888888888';
45
+ const ACCOUNTS = {
46
+ a1: { id: 'a1', userId: U_OWNER, type: 'LIVE', brokerageAccount: null },
47
+ a2: { id: 'a2', userId: U_OTHER, type: 'PAPER', brokerageAccount: { fundId: FUND_1 } },
48
+ a3: { id: 'a3', userId: U_OTHER, type: 'LIVE', brokerageAccount: { fundId: FUND_2 } },
49
+ };
50
+ const POLICIES = {
51
+ p1: { id: 'p1', alpacaAccountId: 'a1' },
52
+ p2: { id: 'p2', alpacaAccountId: 'a2' },
53
+ p3: { id: 'p3', alpacaAccountId: 'a3' },
54
+ };
55
+ /** The tenancy rows: U_FUND is assigned FUND_1; FUND_2 (ORG_2) bridges the LIVE account a3. */
56
+ const TENANCY = {
57
+ organization: [{ id: ORG_2 }],
58
+ orgMembership: [{ id: 'om2', organizationId: ORG_2, userId: U_OTHER }],
59
+ fund: [
60
+ { id: FUND_1, organizationId: 'org-1' },
61
+ { id: FUND_2, organizationId: ORG_2 },
62
+ ],
63
+ fundAssignment: [
64
+ { id: 'fa1', fundId: FUND_1, userId: U_FUND },
65
+ { id: 'fa2', fundId: FUND_2, userId: U_OTHER },
66
+ ],
67
+ brokerageAccount: [
68
+ { id: 'ba1', fundId: FUND_1, engineAccountId: 'a2' },
69
+ { id: 'ba2', fundId: FUND_2, engineAccountId: 'a3' },
70
+ ],
71
+ notificationEvent: [],
72
+ notificationDelivery: [],
73
+ notificationPreference: [],
74
+ };
75
+ /** Evaluate the `where` shapes the guard's scope check builds (equality, `in`, `AND`, `OR`). */
76
+ function matches(row, where) {
77
+ return Object.entries(where).every(([key, condition]) => {
78
+ if (key === 'AND')
79
+ return condition.every((c) => matches(row, c));
80
+ if (key === 'OR')
81
+ return condition.some((c) => matches(row, c));
82
+ if (condition !== null && typeof condition === 'object' && 'in' in condition) {
83
+ return condition.in.includes(row[key]);
84
+ }
85
+ return row[key] === condition;
86
+ });
87
+ }
88
+ const PRINCIPALS = {
89
+ none: null,
90
+ server: { kind: 'server', sub: 'adaptic-engine:host-1:42' },
91
+ staticServer: { kind: 'server' },
92
+ admin: { kind: 'admin', sub: '66666666-6666-4666-8666-666666666666', roles: ['admin'] },
93
+ owner: { kind: 'user', sub: U_OWNER, email: 'owner@example.test', roles: [] },
94
+ stranger: { kind: 'user', sub: U_STRANGER, roles: [] },
95
+ fundUser: { kind: 'user', sub: U_FUND, roles: [] },
96
+ };
97
+ const FLIP_LIVE = 'mutation Flip { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: true } }) { id realtimeTradingEnabled } }';
98
+ const FLIP_FUND = 'mutation FlipFund { updateOneTradingPolicy(where: { alpacaAccountId: "a2" }, data: { killSwitchEnabled: { set: true } }) { id } }';
99
+ const ALIASED = 'mutation Batch { a: updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { killSwitchEnabled: { set: true } }) { id } ' +
100
+ 'b: updateOneTradingPolicy(where: { alpacaAccountId: "a2" }, data: { killSwitchEnabled: { set: true } }) { id } }';
101
+ const NESTED_POLICY = 'mutation Nested { updateOneAlpacaAccount(where: { id: "a1" }, data: { tradingPolicy: { update: { data: { realtimeTradingEnabled: { set: true } } } } }) { id } }';
102
+ const STEAL_ACCOUNT = `mutation Steal { updateOneUser(where: { id: "${U_STRANGER}" }, data: { alpacaAccounts: { connect: [{ id: "a1" }] } }) { id } }`;
103
+ const CREATE_WITH_KEYS = `mutation Create { createOneAlpacaAccount(data: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_OWNER}" } } }) { id } }`;
104
+ const SELF_UPDATE = `mutation Self { updateOneUser(where: { id: "${U_OWNER}" }, data: { name: { set: "n" } }) { id } }`;
105
+ const BULK_POLICY = 'mutation Bulk { updateManyTradingPolicy(where: { killSwitchEnabled: { equals: false } }, data: { killSwitchEnabled: { set: true } }) { count } }';
106
+ const DELETE_ACCOUNT = 'mutation Del { deleteOneAlpacaAccount(where: { id: "a1" }) { id } }';
107
+ const ARM = '{ update: { data: { realtimeTradingEnabled: { set: true } } } }';
108
+ // Blocker 1: minting fund entitlement.
109
+ const NESTED_ASSIGNMENT = `mutation { updateOneUser(where: { id: "${U_FUND}" }, data: { fundAssignments: { create: [{ fund: { connect: { id: "${FUND_2}" } } }] } }) { id } }`;
110
+ const NESTED_MEMBERSHIP = `mutation { updateOneUser(where: { id: "${U_STRANGER}" }, data: { orgMemberships: { create: [{ organization: { connect: { id: "${ORG_2}" } } }] } }) { id } }`;
111
+ const ROOT_ASSIGNMENT_OTHER_FUND = `mutation { createOneFundAssignment(data: { fund: { connect: { id: "${FUND_2}" } }, user: { connect: { id: "${U_STRANGER}" } } }) { id } }`;
112
+ const ROOT_ASSIGNMENT_OWN_FUND = `mutation { createOneFundAssignment(data: { fund: { connect: { id: "${FUND_1}" } }, user: { connect: { id: "${U_FUND}" } } }) { id } }`;
113
+ const RETENANT_ASSIGNMENT = `mutation { updateOneFundAssignment(where: { id: "fa1" }, data: { fund: { connect: { id: "${FUND_2}" } } }) { id } }`;
114
+ const BROKER_LABEL = (id) => `mutation { updateOneBrokerageAccount(where: { id: "${id}" }, data: { label: { set: "x" } }) { id } }`;
115
+ const ARM_UNDER_USER = (userId, accountId) => `mutation { updateOneUser(where: { id: "${userId}" }, data: { alpacaAccounts: { update: [{ where: { id: "${accountId}" }, data: { tradingPolicy: ${ARM} } }] } }) { id } }`;
116
+ // Blocker 2: walks that leave the root's rows.
117
+ const ACCOUNT_CHAIN = 'mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { brokerageAccount: { update: { data: { fund: { update: { data: { name: { set: "x" } } } } } } } }) { id } }';
118
+ const MANAGED_FUND_OPERATOR = `mutation { updateOneUser(where: { id: "${U_FUND}" }, data: { managedFunds: { update: [{ where: { id: "${FUND_1}" }, data: { operator: { update: { data: { role: { set: ADMIN } } } } } }] } }) { id } }`;
119
+ const OWNER_ROW_VIA_FUND = 'mutation { updateOneAlpacaAccount(where: { id: "a2" }, data: { user: { update: { data: { email: { set: "taken@example.test" } } } } }) { id } }';
120
+ const REPOINT_BROKER = 'mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { brokerageAccount: { connect: { id: "ba1" } } }) { id } }';
121
+ const NESTED_FUND_POLICY = 'mutation { updateOneAlpacaAccount(where: { id: "a2" }, data: { tradingPolicy: { update: { data: { killSwitchEnabled: { set: true } } } } }) { id } }';
122
+ // Blocker 3: nested policy writes attributed to the account they reach.
123
+ /** Root account a1 → its owner → a fund → that fund's broker ba2 → ba2's engine account (a3, reached to-one) → its policy. */
124
+ const ARM_FAR_FROM_ROOT = `mutation { updateOneAlpacaAccount(where: { id: "a1" }, data: { user: { update: { data: { fundAssignments: { update: [{ where: { id: "fa2" }, data: { fund: { update: { data: { brokerageAccounts: { update: [{ where: { id: "ba2" }, data: { engineAccount: { update: { data: { tradingPolicy: ${ARM} } } } } }] } } } } } }] } } } } }) { id } }`;
125
+ const ARM_VIA_BROKER = `mutation { updateOneBrokerageAccount(where: { id: "ba2" }, data: { engineAccount: { update: { data: { tradingPolicy: ${ARM} } } } }) { id } }`;
126
+ // Majors.
127
+ const SELF_ROLE = `mutation { updateOneUser(where: { id: "${U_OWNER}" }, data: { role: { set: ADMIN } }) { id } }`;
128
+ const AUDIT_ROW = (source) => `mutation { createOneAuditLog(data: { userId: "${U_OWNER}", operationType: UPDATE, modelName: "TradingPolicy", recordId: "p1", changedFields: {}, metadata: { source: "${source}" } }) { id } }`;
129
+ const CONFIG_UPSERT = (key) => `mutation { upsertOneConfiguration(where: { configKey: "${key}" }, create: { configKey: "${key}", configValue: {}, type: USER_PREFERENCE }, update: { configValue: {} }) { id } }`;
130
+ // Controls: the platform's own fund-operator writes stay admitted.
131
+ const BROKER_CREATE = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_FUND}" } } } } }) { id } }`;
132
+ const BROKER_CREATE_OTHER_OWNER = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${U_OTHER}" } } } } }) { id } }`;
133
+ const BROKER_BRIDGE_FOREIGN = `mutation { createOneBrokerageAccount(data: { fund: { connect: { id: "${FUND_1}" } }, engineAccount: { connect: { id: "a3" } } }) { id } }`;
134
+ /** The platform broker-credentials route's update branch: rotate keys on the fund's bound engine account. */
135
+ const BROKER_ROTATE = (userId) => `mutation { updateOneBrokerageAccount(where: { id: "ba1" }, data: { label: { set: "rotated" }, engineAccount: { upsert: { create: { APIKey: "${API_KEY}", APISecret: "${API_SECRET}", user: { connect: { id: "${userId}" } } }, update: { APIKey: { set: "${API_KEY}" } } } } }) { id } }`;
136
+ const SUSPEND_UPSERT = 'mutation { upsertOneTradingPolicy(where: { alpacaAccountId: "a2" }, create: { alpacaAccount: { connect: { id: "a2" } } }, update: { killSwitchEnabled: { set: true } }) { id } }';
137
+ const DISARM_LIVE = 'mutation Disarm { updateOneTradingPolicy(where: { alpacaAccountId: "a1" }, data: { realtimeTradingEnabled: { set: false } }) { id } }';
138
+ export const SCENARIOS = [
139
+ { name: 'flip/none/enforce', query: FLIP_LIVE, principal: 'none', mode: 'enforce' },
140
+ { name: 'flip/none/shadow', query: FLIP_LIVE, principal: 'none', mode: 'shadow' },
141
+ { name: 'flip/none/shadow+escalated', query: FLIP_LIVE, principal: 'none', mode: 'shadow', enforcedModels: ['TradingPolicy'] },
142
+ { name: 'flip/none/shadow+other-escalated', query: FLIP_LIVE, principal: 'none', mode: 'shadow', enforcedModels: ['User'] },
143
+ { name: 'flip/none/off', query: FLIP_LIVE, principal: 'none', mode: 'off' },
144
+ { name: 'flip/server/enforce', query: FLIP_LIVE, principal: 'server', mode: 'enforce' },
145
+ { name: 'flip/staticServer/enforce', query: FLIP_LIVE, principal: 'staticServer', mode: 'enforce' },
146
+ { name: 'flip/admin/enforce', query: FLIP_LIVE, principal: 'admin', mode: 'enforce' },
147
+ { name: 'flip/owner/enforce', query: FLIP_LIVE, principal: 'owner', mode: 'enforce' },
148
+ { name: 'flip/stranger/enforce', query: FLIP_LIVE, principal: 'stranger', mode: 'enforce' },
149
+ { name: 'flip/stranger/shadow', query: FLIP_LIVE, principal: 'stranger', mode: 'shadow' },
150
+ { name: 'flipFund/fundUser/enforce', query: FLIP_FUND, principal: 'fundUser', mode: 'enforce' },
151
+ { name: 'flipFund/stranger/enforce', query: FLIP_FUND, principal: 'stranger', mode: 'enforce' },
152
+ { name: 'aliased/none/enforce', query: ALIASED, principal: 'none', mode: 'enforce' },
153
+ { name: 'aliased/owner/enforce', query: ALIASED, principal: 'owner', mode: 'enforce' },
154
+ { name: 'nested/none/enforce', query: NESTED_POLICY, principal: 'none', mode: 'enforce' },
155
+ { name: 'nested/owner/enforce', query: NESTED_POLICY, principal: 'owner', mode: 'enforce' },
156
+ { name: 'nested/stranger/enforce', query: NESTED_POLICY, principal: 'stranger', mode: 'enforce' },
157
+ { name: 'steal/stranger/enforce', query: STEAL_ACCOUNT, principal: 'stranger', mode: 'enforce' },
158
+ { name: 'createKeys/none/enforce', query: CREATE_WITH_KEYS, principal: 'none', mode: 'enforce' },
159
+ { name: 'createKeys/stranger/enforce', query: CREATE_WITH_KEYS, principal: 'stranger', mode: 'enforce' },
160
+ { name: 'createKeys/owner/enforce', query: CREATE_WITH_KEYS, principal: 'owner', mode: 'enforce' },
161
+ { name: 'self/owner/enforce', query: SELF_UPDATE, principal: 'owner', mode: 'enforce' },
162
+ { name: 'self/stranger/enforce', query: SELF_UPDATE, principal: 'stranger', mode: 'enforce' },
163
+ { name: 'bulk/owner/enforce', query: BULK_POLICY, principal: 'owner', mode: 'enforce' },
164
+ { name: 'bulk/server/enforce', query: BULK_POLICY, principal: 'server', mode: 'enforce' },
165
+ { name: 'delete/owner/enforce', query: DELETE_ACCOUNT, principal: 'owner', mode: 'enforce' },
166
+ { name: 'auditDown/server/enforce', query: FLIP_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
167
+ { name: 'auditDown/server/shadow', query: FLIP_LIVE, principal: 'server', mode: 'shadow', auditDown: true },
168
+ { name: 'b1/nestedAssignment/fundUser/enforce', query: NESTED_ASSIGNMENT, principal: 'fundUser', mode: 'enforce' },
169
+ { name: 'b1/nestedMembership/stranger/enforce', query: NESTED_MEMBERSHIP, principal: 'stranger', mode: 'enforce' },
170
+ { name: 'b1/rootAssignment/stranger/enforce', query: ROOT_ASSIGNMENT_OTHER_FUND, principal: 'stranger', mode: 'enforce' },
171
+ {
172
+ name: 'b1/rootAssignment/stranger/shadow+accounts',
173
+ query: ROOT_ASSIGNMENT_OTHER_FUND,
174
+ principal: 'stranger',
175
+ mode: 'shadow',
176
+ enforcedModels: ['TradingPolicy', 'AlpacaAccount'],
177
+ },
178
+ { name: 'b1/rootAssignment/fundUser/enforce', query: ROOT_ASSIGNMENT_OWN_FUND, principal: 'fundUser', mode: 'enforce' },
179
+ { name: 'b1/retenantAssignment/fundUser/enforce', query: RETENANT_ASSIGNMENT, principal: 'fundUser', mode: 'enforce' },
180
+ { name: 'b1/crossTenantBroker/stranger/enforce', query: BROKER_LABEL('ba2'), principal: 'stranger', mode: 'enforce' },
181
+ { name: 'b1/tenantBroker/fundUser/enforce', query: BROKER_LABEL('ba1'), principal: 'fundUser', mode: 'enforce' },
182
+ {
183
+ name: 'b1/armUnderUser/none/shadow+policy',
184
+ query: ARM_UNDER_USER(U_OTHER, 'a3'),
185
+ principal: 'none',
186
+ mode: 'shadow',
187
+ enforcedModels: ['TradingPolicy'],
188
+ },
189
+ {
190
+ name: 'b1/stealAccountUnderUser/none/shadow+accounts',
191
+ query: `mutation { updateOneUser(where: { id: "${U_STRANGER}" }, data: { alpacaAccounts: { connect: [{ id: "a3" }] } }) { id } }`,
192
+ principal: 'none',
193
+ mode: 'shadow',
194
+ enforcedModels: ['AlpacaAccount'],
195
+ },
196
+ {
197
+ name: 'b1/connectAccountOntoPolicy/none/shadow+accounts',
198
+ query: 'mutation { createOneTradingPolicy(data: { alpacaAccount: { connect: { id: "a3" } } }) { id } }',
199
+ principal: 'none',
200
+ mode: 'shadow',
201
+ enforcedModels: ['AlpacaAccount'],
202
+ },
203
+ { name: 'b2/accountChain/owner/enforce', query: ACCOUNT_CHAIN, principal: 'owner', mode: 'enforce' },
204
+ { name: 'b2/managedFundOperator/fundUser/enforce', query: MANAGED_FUND_OPERATOR, principal: 'fundUser', mode: 'enforce' },
205
+ { name: 'b2/ownerRowViaFund/fundUser/enforce', query: OWNER_ROW_VIA_FUND, principal: 'fundUser', mode: 'enforce' },
206
+ { name: 'b2/armUnderUser/fundUser/enforce', query: ARM_UNDER_USER(U_FUND, 'a3'), principal: 'fundUser', mode: 'enforce' },
207
+ { name: 'b2/repointBroker/owner/enforce', query: REPOINT_BROKER, principal: 'owner', mode: 'enforce' },
208
+ { name: 'b2/nestedFundPolicy/fundUser/enforce', query: NESTED_FUND_POLICY, principal: 'fundUser', mode: 'enforce' },
209
+ { name: 'b3/armUnderUser/server/enforce', query: ARM_UNDER_USER(U_OTHER, 'a3'), principal: 'server', mode: 'enforce' },
210
+ { name: 'b3/armFarFromRoot/server/enforce', query: ARM_FAR_FROM_ROOT, principal: 'server', mode: 'enforce' },
211
+ { name: 'b3/armViaBroker/server/enforce', query: ARM_VIA_BROKER, principal: 'server', mode: 'enforce' },
212
+ { name: 'b3/armUnderUser/owner/enforce', query: ARM_UNDER_USER(U_OWNER, 'a1'), principal: 'owner', mode: 'enforce' },
213
+ { name: 'm/selfRole/owner/enforce', query: SELF_ROLE, principal: 'owner', mode: 'enforce' },
214
+ { name: 'm/forgedAudit/owner/enforce', query: AUDIT_ROW('mutation-auth-guard'), principal: 'owner', mode: 'enforce' },
215
+ { name: 'm/audit/owner/enforce', query: AUDIT_ROW('platform'), principal: 'owner', mode: 'enforce' },
216
+ { name: 'm/systemConfig/owner/enforce', query: CONFIG_UPSERT('llm.alias.routing'), principal: 'owner', mode: 'enforce' },
217
+ {
218
+ name: 'm/ownConfig/owner/enforce',
219
+ query: CONFIG_UPSERT(`platform.web.chart-preferences.user.${U_OWNER}`),
220
+ principal: 'owner',
221
+ mode: 'enforce',
222
+ },
223
+ { name: 'm/disarmAuditDown/server/enforce', query: DISARM_LIVE, principal: 'server', mode: 'enforce', auditDown: true },
224
+ { name: 'ctl/brokerCreate/fundUser/enforce', query: BROKER_CREATE, principal: 'fundUser', mode: 'enforce' },
225
+ { name: 'ctl/brokerCreateOtherOwner/fundUser/enforce', query: BROKER_CREATE_OTHER_OWNER, principal: 'fundUser', mode: 'enforce' },
226
+ { name: 'ctl/brokerBridgeForeign/fundUser/enforce', query: BROKER_BRIDGE_FOREIGN, principal: 'fundUser', mode: 'enforce' },
227
+ { name: 'ctl/suspendUpsert/fundUser/enforce', query: SUSPEND_UPSERT, principal: 'fundUser', mode: 'enforce' },
228
+ { name: 'ctl/brokerRotate/fundUser/enforce', query: BROKER_ROTATE(U_FUND), principal: 'fundUser', mode: 'enforce' },
229
+ { name: 'ctl/brokerRotate/stranger/enforce', query: BROKER_ROTATE(U_STRANGER), principal: 'stranger', mode: 'enforce' },
230
+ ];
231
+ async function counterSnapshot() {
232
+ const metric = await mutationAuthorizationTotal.get();
233
+ const out = {};
234
+ for (const v of metric.values) {
235
+ const key = `${v.labels.mutation}|${v.labels.principal_kind}|${v.labels.decision}|${v.labels.reason}`;
236
+ out[key] = (out[key] ?? 0) + v.value;
237
+ }
238
+ return out;
239
+ }
240
+ async function auditFailures() {
241
+ const metric = await mutationAuditWriteFailuresTotal.get();
242
+ return metric.values.reduce((sum, v) => sum + v.value, 0);
243
+ }
244
+ async function auditBypasses() {
245
+ const metric = await mutationAuditBypassedTotal.get();
246
+ return metric.values.reduce((sum, v) => sum + v.value, 0);
247
+ }
248
+ function policyBy(where) {
249
+ return Object.values(POLICIES).find((p) => (where.id !== undefined && p.id === where.id) || (where.alpacaAccountId !== undefined && p.alpacaAccountId === where.alpacaAccountId));
250
+ }
251
+ function policyFacts(p) {
252
+ return {
253
+ ...p,
254
+ realtimeTradingEnabled: false,
255
+ paperTradingOnly: false,
256
+ killSwitchEnabled: false,
257
+ autonomyMode: 'ADVISORY_ONLY',
258
+ alpacaAccount: ACCOUNTS[p.alpacaAccountId],
259
+ };
260
+ }
261
+ /**
262
+ * Fake delegates for the tenancy models: `findMany` / `findUnique` over the
263
+ * fixture rows (the entitlement read and the guard's scope check), and
264
+ * recording writes.
265
+ */
266
+ function tenancyDelegates(write) {
267
+ const out = {};
268
+ for (const [delegate, rows] of Object.entries(TENANCY)) {
269
+ out[delegate] = {
270
+ findMany: ({ where }) => Promise.resolve(rows.filter((r) => matches(r, where))),
271
+ findUnique: ({ where }) => {
272
+ const row = rows.find((r) => matches(r, where));
273
+ return Promise.resolve(row ? { id: row.id } : null);
274
+ },
275
+ create: () => write(`${delegate}.create`, { id: `${delegate}-new` }),
276
+ update: ({ where }) => write(`${delegate}.update`, { id: where.id }),
277
+ upsert: ({ where }) => write(`${delegate}.upsert`, { id: where.id }),
278
+ delete: ({ where }) => write(`${delegate}.delete`, { id: where.id }),
279
+ };
280
+ }
281
+ return out;
282
+ }
283
+ async function main() {
284
+ let mode = 'enforce';
285
+ let enforcedModels = new Set();
286
+ let auditDown = false;
287
+ let writes = [];
288
+ let audit = [];
289
+ const write = (name, value) => {
290
+ writes.push(name);
291
+ return Promise.resolve(value);
292
+ };
293
+ const prisma = {
294
+ tradingPolicy: {
295
+ findUnique: ({ where }) => {
296
+ const p = policyBy(where);
297
+ return Promise.resolve(p ? policyFacts(p) : null);
298
+ },
299
+ findMany: () => Promise.resolve(Object.values(POLICIES).map(policyFacts)),
300
+ update: ({ where }) => write('tradingPolicy.update', { ...policyBy(where), realtimeTradingEnabled: true }),
301
+ updateMany: () => write('tradingPolicy.updateMany', { count: 2 }),
302
+ upsert: ({ where }) => write('tradingPolicy.upsert', { ...policyBy(where) }),
303
+ },
304
+ alpacaAccount: {
305
+ findUnique: ({ where }) => Promise.resolve(typeof where.id === 'string' ? (ACCOUNTS[where.id] ?? null) : null),
306
+ update: () => write('alpacaAccount.update', { id: 'a1', type: 'LIVE' }),
307
+ create: () => write('alpacaAccount.create', { id: 'a9', type: 'PAPER' }),
308
+ delete: () => write('alpacaAccount.delete', { id: 'a1', type: 'LIVE' }),
309
+ },
310
+ user: {
311
+ update: ({ where }) => write('user.update', { id: where.id }),
312
+ },
313
+ ...tenancyDelegates(write),
314
+ auditLog: {
315
+ create: ({ data }) => {
316
+ if (auditDown)
317
+ return Promise.reject(new Error('audit table unavailable'));
318
+ audit.push(data);
319
+ if (data.metadata === null || typeof data.metadata !== 'object' || data.metadata.source !== 'mutation-auth-guard') {
320
+ writes.push('auditLog.create');
321
+ }
322
+ return Promise.resolve({ id: `audit-${audit.length}` });
323
+ },
324
+ },
325
+ configuration: {
326
+ upsert: ({ where }) => write('configuration.upsert', { id: `c-${String(where.configKey)}` }),
327
+ },
328
+ };
329
+ const schema = await buildSchema({
330
+ resolvers: [
331
+ TradingPolicyCrudResolver,
332
+ AlpacaAccountCrudResolver,
333
+ UserCrudResolver,
334
+ OrganizationCrudResolver,
335
+ OrgMembershipCrudResolver,
336
+ FundCrudResolver,
337
+ FundAssignmentCrudResolver,
338
+ BrokerageAccountCrudResolver,
339
+ AuditLogCrudResolver,
340
+ ConfigurationCrudResolver,
341
+ ],
342
+ validate: false,
343
+ });
344
+ const guardedMutations = installMutationAuthGuard(schema, {
345
+ modeProvider: () => mode,
346
+ enforcedModelsProvider: () => enforcedModels,
347
+ });
348
+ // Installing twice must not double-guard (each decision would count twice).
349
+ installMutationAuthGuard(schema, { modeProvider: () => mode, enforcedModelsProvider: () => enforcedModels });
350
+ const mutationFieldCount = Object.keys(schema.getMutationType()?.getFields() ?? {}).length;
351
+ const server = new ApolloServer({ schema, plugins: [createHttpStatusMapperPlugin()] });
352
+ await server.start();
353
+ const results = {};
354
+ for (const scenario of SCENARIOS) {
355
+ mode = scenario.mode;
356
+ enforcedModels = new Set(scenario.enforcedModels ?? []);
357
+ auditDown = scenario.auditDown === true;
358
+ writes = [];
359
+ audit = [];
360
+ resetMutationAuthLogThrottle();
361
+ const before = await counterSnapshot();
362
+ const failuresBefore = await auditFailures();
363
+ const bypassesBefore = await auditBypasses();
364
+ const response = await server.executeOperation({ query: scenario.query }, {
365
+ contextValue: {
366
+ prisma,
367
+ principal: PRINCIPALS[scenario.principal],
368
+ req: {
369
+ ip: '203.0.113.7',
370
+ headers: { 'user-agent': 'mutation-guard-harness', 'x-adaptic-change-reason': 'harness: arm LIVE' },
371
+ },
372
+ },
373
+ });
374
+ const after = await counterSnapshot();
375
+ const counterDelta = {};
376
+ for (const [key, value] of Object.entries(after)) {
377
+ const delta = value - (before[key] ?? 0);
378
+ if (delta !== 0)
379
+ counterDelta[key] = delta;
380
+ }
381
+ const body = response.body.kind === 'single' ? response.body.singleResult : null;
382
+ const errors = body?.errors ?? [];
383
+ results[scenario.name] = {
384
+ status: response.http.status ?? 200,
385
+ codes: errors.map((e) => String(e.extensions?.code)),
386
+ reasons: errors.map((e) => String(e.extensions?.reason)),
387
+ json: JSON.stringify(body),
388
+ writes,
389
+ audit: JSON.parse(JSON.stringify(audit)),
390
+ counterDelta,
391
+ auditFailureDelta: (await auditFailures()) - failuresBefore,
392
+ auditBypassDelta: (await auditBypasses()) - bypassesBefore,
393
+ };
394
+ }
395
+ await server.stop();
396
+ process.stdout.write(`<<<RESULTS>>>${JSON.stringify({ guardedMutations, mutationFieldCount, results })}<<<END>>>\n`);
397
+ }
398
+ main().catch((error) => {
399
+ process.stderr.write(`harness failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
400
+ process.exit(1);
401
+ });
402
+ //# sourceMappingURL=mutation-auth-guard.harness.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Run `harnessPath` (relative to the repository root) under ts-node and parse
3
+ * its results.
4
+ *
5
+ * @param harnessPath - Harness file, relative to the repository root.
6
+ * @param timeoutMs - Wall-clock budget; the child is killed when it runs out.
7
+ * @returns The parsed results object.
8
+ */
9
+ export declare function runTsNodeHarness<T>(harnessPath: string, timeoutMs: number): Promise<T>;
10
+ //# sourceMappingURL=ts-node-harness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ts-node-harness.d.ts","sourceRoot":"","sources":["../../../../src/middleware/__tests__/ts-node-harness.ts"],"names":[],"mappings":"AAoDA;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CA6B5F"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ts-node-harness.js","sourceRoot":"","sources":["../../../../src/middleware/__tests__/ts-node-harness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,iEAAiE;AACjE,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;AAEtD,iDAAiD;AACjD,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE1C,gEAAgE;AAChE,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,MAAM,OAAO,GAAG,6BAA6B,CAAC;AAU9C,SAAS,eAA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K,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,WAAW,WAAW,yBAAyB,MAAM,CAAC,KAAK,CAAC,CAAC,kBAAkB,CAAC,EAAE,CACnF,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAM,CAAC;AACnC,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Run an out-of-process ts-node harness and return the JSON it prints between
3
+ * `<<<RESULTS>>>` and `<<<END>>>`.
4
+ *
5
+ * The guard harnesses build schemas from the generated resolvers, which need
6
+ * `emitDecoratorMetadata`, so they cannot run inside vitest's esbuild
7
+ * transform. A run costs tens of seconds of CPU, and far longer on a loaded
8
+ * machine, so the child is awaited, never spawned synchronously: a synchronous
9
+ * spawn blocks the vitest worker's event loop for the whole run, the worker
10
+ * cannot answer the runner's RPC in that time, and once the block outlasts
11
+ * vitest's 60 s RPC timeout the run records an unhandled
12
+ * `Timeout calling "onTaskUpdate"` error and exits 1 even though every
13
+ * assertion passed.
14
+ *
15
+ * The child is killed at `timeoutMs` and the failure says so. Set the calling
16
+ * hook's timeout above it, so a hung harness fails its suite with this reason
17
+ * rather than with a bare hook timeout that leaves the child running.
18
+ */
19
+ import { execFile } from 'node:child_process';
20
+ import path from 'node:path';
21
+ import { promisify } from 'node:util';
22
+ const execFileAsync = promisify(execFile);
23
+ /** Repository root, resolved from `src/middleware/__tests__`. */
24
+ const REPO_ROOT = path.resolve(__dirname, '../../..');
25
+ /** Largest harness stdout accepted, in bytes. */
26
+ const MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
27
+ /** Characters of harness output quoted in a failure message. */
28
+ const FAILURE_TAIL_CHARS = 2000;
29
+ const RESULTS = /<<<RESULTS>>>(.*)<<<END>>>/s;
30
+ function describeFailure(failure, timeoutMs) {
31
+ if (failure.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
32
+ return `printed more than ${MAX_OUTPUT_BYTES} bytes`;
33
+ }
34
+ if (failure.killed)
35
+ return `was killed after ${timeoutMs} ms`;
36
+ if (failure.signal)
37
+ return `was terminated by ${failure.signal}`;
38
+ return `exited with code ${String(failure.code)}`;
39
+ }
40
+ /**
41
+ * Run `harnessPath` (relative to the repository root) under ts-node and parse
42
+ * its results.
43
+ *
44
+ * @param harnessPath - Harness file, relative to the repository root.
45
+ * @param timeoutMs - Wall-clock budget; the child is killed when it runs out.
46
+ * @returns The parsed results object.
47
+ */
48
+ export async function runTsNodeHarness(harnessPath, timeoutMs) {
49
+ let stdout;
50
+ try {
51
+ ({ stdout } = await execFileAsync(path.join(REPO_ROOT, 'node_modules/.bin/ts-node'), ['--transpile-only', harnessPath], {
52
+ cwd: REPO_ROOT,
53
+ encoding: 'utf8',
54
+ env: { ...process.env, LOG_LEVEL: 'error' },
55
+ maxBuffer: MAX_OUTPUT_BYTES,
56
+ timeout: timeoutMs,
57
+ killSignal: 'SIGKILL',
58
+ }));
59
+ }
60
+ catch (error) {
61
+ const failure = error;
62
+ throw new Error(`harness ${harnessPath} ${describeFailure(failure, timeoutMs)}:\n` +
63
+ (failure.stderr ?? '').slice(-FAILURE_TAIL_CHARS));
64
+ }
65
+ const match = RESULTS.exec(stdout);
66
+ if (!match) {
67
+ throw new Error(`harness ${harnessPath} printed no results:\n${stdout.slice(-FAILURE_TAIL_CHARS)}`);
68
+ }
69
+ return JSON.parse(match[1]);
70
+ }
71
+ //# sourceMappingURL=ts-node-harness.js.map
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import type { ApolloServerPlugin } from '@apollo/server';
12
12
  import type { PrismaClient } from '@prisma/client';
13
+ import type { BackendPrincipal } from '../auth/token-verifier';
13
14
  /** Represents the user object decoded from JWT context */
14
15
  interface AuditUser {
15
16
  sub?: string;
@@ -22,6 +23,8 @@ interface AuditUser {
22
23
  interface AuditContext {
23
24
  prisma: PrismaClient;
24
25
  user?: AuditUser | string | null;
26
+ /** The verified principal, when the request presented one. */
27
+ principal?: BackendPrincipal | null;
25
28
  req?: {
26
29
  ip?: string;
27
30
  headers?: Record<string, string | string[] | undefined>;
@@ -59,11 +62,25 @@ declare function extractRecordId(data: Record<string, unknown> | null | undefine
59
62
  * For update operations, captures the data being set.
60
63
  * For delete operations, captures the where clause.
61
64
  *
65
+ * Stored-credential values (broker keys, OAuth / session / invite tokens) are
66
+ * replaced with a placeholder: an audit row is readable far more widely than
67
+ * the credential column, so a key copied into one is an unguarded second copy
68
+ * of the secret.
69
+ *
62
70
  * @param operationType - The type of mutation operation
63
71
  * @param variables - The GraphQL variables passed to the mutation
64
72
  * @returns A JSON-serializable object representing the changed fields
65
73
  */
66
74
  declare function extractChangedFields(operationType: 'CREATE' | 'UPDATE' | 'DELETE', variables: Record<string, unknown> | null | undefined): Record<string, unknown>;
75
+ /**
76
+ * The acting principal as recorded on an audit row. `userId` holds only a
77
+ * UUID subject, so a service or anonymous write needs its identity here or
78
+ * the row cannot say who made it.
79
+ */
80
+ declare function principalMetadata(principal: BackendPrincipal | null | undefined): {
81
+ principalKind: string;
82
+ principalSub: string | null;
83
+ };
67
84
  /**
68
85
  * Creates an Apollo Server plugin that logs all mutations to the AuditLog table.
69
86
  *
@@ -74,5 +91,5 @@ declare function extractChangedFields(operationType: 'CREATE' | 'UPDATE' | 'DELE
74
91
  * @returns An Apollo Server plugin instance
75
92
  */
76
93
  export declare function createAuditLogPlugin(): ApolloServerPlugin<AuditContext>;
77
- export { parseMutationOperation, extractUserId, extractRecordId, extractChangedFields, };
94
+ export { parseMutationOperation, extractUserId, extractRecordId, extractChangedFields, principalMetadata, };
78
95
  //# sourceMappingURL=audit-logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"audit-logger.d.ts","sourceRoot":"","sources":["../../../src/middleware/audit-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,kBAAkB,EAGnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAA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,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gCAC7D,SAAS,EAAE,SAAS,CAAC,SAAS;gCAC9B,aAAa,EAAE,SAAS,CAAC,aAAa;6BACvC,CAAC,CAAC;wBACL,CAAC;oBACH,CAAC;gBACH,CAAC;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,eAAe,EACf,oBAAoB,GACrB,CAAC"}
1
+ {"version":3,"file":"audit-logger.js","sourceRoot":"","sources":["../../../src/middleware/audit-logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAQH,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AA8BzC,uFAAuF;AACvF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,UAAU;IACV,SAAS;IACT,mBAAmB;IACnB,eAAe;CAChB,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,SAAS,sBAAsB,CAC7B,aAAqB;IAErB,MAAM,aAAa,GAAG,yCAAyC,CAAC;IAChE,MAAM,aAAa,GAAG,yCAAyC,CAAC;IAChE,MAAM,aAAa,GAAG,+BAA+B,CAAC;IAEtD,IAAI,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAC9C,IAAI,KAAK,EAAE,CAAC;QACV,OAAO;YACL,aAAa,EAAE,QAAQ;YACvB,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC;YACnB,aAAa;SACd,CAAC;IACJ,CAAC;IAED,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAC1C,IAAI,KAAK,EAAE,CAAC;QACV,OAAO;YACL,aAAa,EAAE,QAAQ;YACvB,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC;YACnB,aAAa;SACd,CAAC;IACJ,CAAC;IAED,KAAK,GAAG,aAAa,CAAC,I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