@adaptic/backend 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.
- package/auth/authorization-map.cjs +306 -0
- package/auth/authorization-map.d.ts +143 -0
- package/auth/cortex-auth-checker.cjs +172 -0
- package/auth/cortex-auth-checker.d.ts +114 -0
- package/auth/credential-fields.cjs +51 -0
- package/auth/credential-fields.d.ts +19 -0
- package/auth/credential-redaction.cjs +134 -0
- package/auth/credential-redaction.d.ts +60 -0
- package/auth/graphql-auth-shadow.cjs +317 -0
- package/auth/graphql-auth-shadow.d.ts +194 -0
- package/auth/membership-write-authority.cjs +131 -0
- package/auth/membership-write-authority.d.ts +110 -0
- package/auth/mutation-authorization.cjs +376 -0
- package/auth/mutation-authorization.d.ts +261 -0
- package/auth/nested-write-inspector.cjs +189 -0
- package/auth/nested-write-inspector.d.ts +94 -0
- package/auth/nested-write-policy.cjs +189 -0
- package/auth/nested-write-policy.d.ts +99 -0
- package/auth/service-token.cjs +316 -0
- package/auth/service-token.d.ts +94 -0
- package/auth/tenancy-scope.cjs +736 -0
- package/auth/tenancy-scope.d.ts +347 -0
- package/auth/token-verifier.cjs +451 -0
- package/auth/token-verifier.d.ts +153 -0
- package/auth/totp.cjs +265 -0
- package/auth/totp.d.ts +111 -0
- package/auth/user-write-content.cjs +116 -0
- package/auth/user-write-content.d.ts +47 -0
- package/auth/ws-auth-context.cjs +75 -0
- package/auth/ws-auth-context.d.ts +69 -0
- package/config/jwtConfig.cjs +52 -0
- package/config/jwtConfig.d.ts +16 -0
- package/config/metrics.cjs +356 -0
- package/config/metrics.d.ts +128 -0
- package/config/persisted-queries.cjs +122 -0
- package/config/persisted-queries.d.ts +40 -0
- package/config/server-only-models.cjs +166 -0
- package/config/server-only-models.d.ts +89 -0
- package/config/tracing.d.ts +24 -0
- package/generated/typegraphql-prisma/enhance.cjs +3 -3
- package/generated/typegraphql-prisma/index.cjs +6 -6
- package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
- package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
- package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
- package/middleware/audit-log-write-redaction.cjs +143 -0
- package/middleware/audit-log-write-redaction.d.ts +82 -0
- package/middleware/audit-logger.cjs +378 -0
- package/middleware/audit-logger.d.ts +158 -0
- package/middleware/audit-payload-guard.cjs +107 -0
- package/middleware/audit-payload-guard.d.ts +85 -0
- package/middleware/auth.cjs +66 -0
- package/middleware/auth.d.ts +41 -0
- package/middleware/credential-field-guard.cjs +514 -0
- package/middleware/credential-field-guard.d.ts +173 -0
- package/middleware/generated-type-names.cjs +77 -0
- package/middleware/generated-type-names.d.ts +44 -0
- package/middleware/graphql-validation-plugin.cjs +310 -0
- package/middleware/graphql-validation-plugin.d.ts +98 -0
- package/middleware/guard-log-throttle.cjs +89 -0
- package/middleware/guard-log-throttle.d.ts +80 -0
- package/middleware/index.cjs +57 -0
- package/middleware/index.d.ts +14 -0
- package/middleware/input-validator.cjs +220 -0
- package/middleware/input-validator.d.ts +63 -0
- package/middleware/mandate-version-validation.cjs +131 -0
- package/middleware/mandate-version-validation.d.ts +41 -0
- package/middleware/mutation-account-facts.cjs +223 -0
- package/middleware/mutation-account-facts.d.ts +143 -0
- package/middleware/mutation-auth-guard.cjs +536 -0
- package/middleware/mutation-auth-guard.d.ts +100 -0
- package/middleware/mutation-membership-facts.cjs +276 -0
- package/middleware/mutation-membership-facts.d.ts +133 -0
- package/middleware/mutation-tenant-facts.cjs +132 -0
- package/middleware/mutation-tenant-facts.d.ts +81 -0
- package/middleware/query-complexity.cjs +182 -0
- package/middleware/query-complexity.d.ts +56 -0
- package/middleware/rate-limiter.cjs +223 -0
- package/middleware/rate-limiter.d.ts +93 -0
- package/middleware/rate-tier.cjs +111 -0
- package/middleware/rate-tier.d.ts +56 -0
- package/middleware/soft-delete.cjs +175 -0
- package/middleware/soft-delete.d.ts +146 -0
- package/middleware/tenancy-scoping.cjs +229 -0
- package/middleware/tenancy-scoping.d.ts +67 -0
- package/middleware/trading-policy-audit.cjs +353 -0
- package/middleware/trading-policy-audit.d.ts +184 -0
- package/middleware/types.cjs +17 -0
- package/middleware/types.d.ts +87 -0
- package/middleware/validation-examples.cjs +398 -0
- package/middleware/validation-examples.d.ts +76 -0
- package/package.json +10 -2
- package/readers/index.cjs +15 -0
- package/readers/index.d.ts +10 -0
- package/readers/intraday-lane-prefs.cjs +76 -0
- package/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
- package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
- package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
- package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
- package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
- package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
- package/health.cjs +0 -274
- package/server.cjs +0 -607
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate-limit tier resolution (audit B01-backend-legacy-09).
|
|
3
|
+
*
|
|
4
|
+
* The rate limiter previously granted the 5x-higher authenticated tier to any
|
|
5
|
+
* request carrying a 3-dot-segment `Bearer` header — a trivially fabricated
|
|
6
|
+
* shape (`Bearer a.b.c`). This module keys the tier off ACTUAL verification
|
|
7
|
+
* instead, using the two offline-verifiable credential classes:
|
|
8
|
+
*
|
|
9
|
+
* 1. `SERVER_AUTH_TOKEN` exact match (the engine / server-to-server path).
|
|
10
|
+
* 2. App-issued HS256 JWTs verified against the shared `jwtSecret`.
|
|
11
|
+
*
|
|
12
|
+
* Google ID tokens (RS256, JWKS-verified) cannot be verified synchronously
|
|
13
|
+
* without a network dependency in the request hot path; they are deliberately
|
|
14
|
+
* tiered as `anon`. This is a metrics-only inaccuracy while the limiter is in
|
|
15
|
+
* shadow mode — before any enforce graduation, either extend this resolver
|
|
16
|
+
* with an async JWKS-backed path or raise the anon ceiling to cover browser
|
|
17
|
+
* traffic (tracked in the B01-02 graduation checklist).
|
|
18
|
+
*
|
|
19
|
+
* Verified results are memoised in a bounded, TTL'd cache keyed by the token's
|
|
20
|
+
* SHA-256 (raw tokens are never retained) so the per-request cost is one hash.
|
|
21
|
+
*/
|
|
22
|
+
import type { Request } from 'express';
|
|
23
|
+
/** Rate-limit tier: `auth` = verified caller budget, `anon` = default budget. */
|
|
24
|
+
export type RateTier = 'auth' | 'anon';
|
|
25
|
+
/**
|
|
26
|
+
* Outcome of tier resolution for one request.
|
|
27
|
+
*/
|
|
28
|
+
export interface RateTierResolution {
|
|
29
|
+
/** The tier the request's rate budget is drawn from. */
|
|
30
|
+
readonly tier: RateTier;
|
|
31
|
+
/**
|
|
32
|
+
* Stable per-principal bucket key (`sub:<sub>`) for verified callers, so
|
|
33
|
+
* authenticated traffic is bucketed per principal rather than per IP
|
|
34
|
+
* (audit B01-backend-legacy-02). `null` for anonymous callers — the limiter
|
|
35
|
+
* falls back to the client IP.
|
|
36
|
+
*/
|
|
37
|
+
readonly principalKey: string | null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Clears the memoised token-verdict cache. Test-only.
|
|
41
|
+
*
|
|
42
|
+
* @internal exported for testing
|
|
43
|
+
*/
|
|
44
|
+
export declare function _resetRateTierCacheForTests(): void;
|
|
45
|
+
/**
|
|
46
|
+
* Resolves the rate-limit tier and principal bucket key for a request.
|
|
47
|
+
*
|
|
48
|
+
* Cheap on the hot path: one SHA-256 over the token plus a bounded map lookup;
|
|
49
|
+
* the HMAC verification runs at most once per token per TTL window.
|
|
50
|
+
*
|
|
51
|
+
* @param req - Incoming Express request.
|
|
52
|
+
* @returns The request's {@link RateTierResolution}; `anon` when no `Bearer`
|
|
53
|
+
* token is present or the token cannot be verified offline.
|
|
54
|
+
*/
|
|
55
|
+
export declare function resolveRateTier(req: Request): RateTierResolution;
|
|
56
|
+
//# sourceMappingURL=rate-tier.d.ts.map
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Soft Delete Utilities
|
|
4
|
+
*
|
|
5
|
+
* Provides utilities for soft-delete behavior on critical models.
|
|
6
|
+
* Instead of removing records from the database, a `deletedAt` timestamp
|
|
7
|
+
* is set, and query helpers filter out soft-deleted records by default.
|
|
8
|
+
*
|
|
9
|
+
* Models with soft delete support: User, AlpacaAccount, Trade, Action
|
|
10
|
+
*
|
|
11
|
+
* Usage patterns:
|
|
12
|
+
* 1. Use `softDeleteFilter()` in where clauses to exclude deleted records
|
|
13
|
+
* 2. Use `softDeleteRecord()` to soft-delete a record (set deletedAt)
|
|
14
|
+
* 3. Use `hardDelete()` for permanent administrative deletion
|
|
15
|
+
* 4. Pass `includeDeleted: true` to admin queries to see all records
|
|
16
|
+
*
|
|
17
|
+
* Note: Prisma 6 removed the $use() middleware API. Soft delete behavior
|
|
18
|
+
* is implemented via utility functions called from resolvers and services.
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.SOFT_DELETE_MODELS = void 0;
|
|
22
|
+
exports.softDeleteFilter = softDeleteFilter;
|
|
23
|
+
exports.deletedOnlyFilter = deletedOnlyFilter;
|
|
24
|
+
exports.isSoftDeleteModel = isSoftDeleteModel;
|
|
25
|
+
exports.softDeleteRecord = softDeleteRecord;
|
|
26
|
+
exports.restoreRecord = restoreRecord;
|
|
27
|
+
exports.hardDelete = hardDelete;
|
|
28
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
29
|
+
/**
|
|
30
|
+
* Models that support soft deletion via the deletedAt field.
|
|
31
|
+
* Only these models have the deletedAt column in the database.
|
|
32
|
+
*/
|
|
33
|
+
const SOFT_DELETE_MODELS = new Set([
|
|
34
|
+
'User',
|
|
35
|
+
'AlpacaAccount',
|
|
36
|
+
'Trade',
|
|
37
|
+
'Action',
|
|
38
|
+
]);
|
|
39
|
+
exports.SOFT_DELETE_MODELS = SOFT_DELETE_MODELS;
|
|
40
|
+
/**
|
|
41
|
+
* Returns a where clause filter that excludes soft-deleted records.
|
|
42
|
+
* Can be spread into any Prisma where clause for soft-delete-aware queries.
|
|
43
|
+
*
|
|
44
|
+
* @param includeDeleted - When true, returns an empty filter (includes deleted records)
|
|
45
|
+
* @returns An object to spread into a Prisma where clause
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* // Exclude soft-deleted users (default)
|
|
50
|
+
* const users = await prisma.user.findMany({
|
|
51
|
+
* where: { role: 'USER', ...softDeleteFilter() },
|
|
52
|
+
* });
|
|
53
|
+
*
|
|
54
|
+
* // Include soft-deleted users (admin query)
|
|
55
|
+
* const allUsers = await prisma.user.findMany({
|
|
56
|
+
* where: { role: 'USER', ...softDeleteFilter(true) },
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
function softDeleteFilter(includeDeleted = false) {
|
|
61
|
+
if (includeDeleted) {
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
return { deletedAt: null };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Returns a where clause filter for finding only soft-deleted records.
|
|
68
|
+
* Useful for admin interfaces that need to list deleted records for restoration.
|
|
69
|
+
*
|
|
70
|
+
* @returns An object to spread into a Prisma where clause
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```typescript
|
|
74
|
+
* // Find only soft-deleted users
|
|
75
|
+
* const deletedUsers = await prisma.user.findMany({
|
|
76
|
+
* where: { ...deletedOnlyFilter() },
|
|
77
|
+
* });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
function deletedOnlyFilter() {
|
|
81
|
+
return { deletedAt: { not: null } };
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Checks whether a given model supports soft deletion.
|
|
85
|
+
*
|
|
86
|
+
* @param modelName - The Prisma model name (PascalCase)
|
|
87
|
+
* @returns True if the model has a deletedAt field
|
|
88
|
+
*/
|
|
89
|
+
function isSoftDeleteModel(modelName) {
|
|
90
|
+
return SOFT_DELETE_MODELS.has(modelName);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Soft-deletes a record by setting its deletedAt timestamp.
|
|
94
|
+
* This is the recommended way to "delete" records in soft-delete-enabled models.
|
|
95
|
+
*
|
|
96
|
+
* @param delegate - The Prisma model delegate (e.g., prisma.user)
|
|
97
|
+
* @param id - The record ID to soft-delete
|
|
98
|
+
* @param modelName - The model name for logging purposes
|
|
99
|
+
* @returns The updated record
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* // Soft-delete a user
|
|
104
|
+
* await softDeleteRecord(prisma.user, 'user-123', 'User');
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
async function softDeleteRecord(delegate, id, modelName) {
|
|
108
|
+
logger_1.logger.info('Soft delete: Setting deletedAt on record', {
|
|
109
|
+
model: modelName,
|
|
110
|
+
id,
|
|
111
|
+
});
|
|
112
|
+
return delegate.update({
|
|
113
|
+
where: { id },
|
|
114
|
+
data: { deletedAt: new Date() },
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Restores a soft-deleted record by clearing its deletedAt timestamp.
|
|
119
|
+
*
|
|
120
|
+
* @param delegate - The Prisma model delegate (e.g., prisma.user)
|
|
121
|
+
* @param id - The record ID to restore
|
|
122
|
+
* @param modelName - The model name for logging purposes
|
|
123
|
+
* @returns The updated record
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // Restore a soft-deleted user
|
|
128
|
+
* await restoreRecord(prisma.user, 'user-123', 'User');
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
async function restoreRecord(delegate, id, modelName) {
|
|
132
|
+
logger_1.logger.info('Soft delete: Restoring record (clearing deletedAt)', {
|
|
133
|
+
model: modelName,
|
|
134
|
+
id,
|
|
135
|
+
});
|
|
136
|
+
return delegate.update({
|
|
137
|
+
where: { id },
|
|
138
|
+
data: { deletedAt: null },
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Mapping from model names to their database table names.
|
|
143
|
+
* Used for raw SQL hard-delete operations.
|
|
144
|
+
*/
|
|
145
|
+
const TABLE_NAME_MAP = {
|
|
146
|
+
User: 'users',
|
|
147
|
+
AlpacaAccount: 'alpaca_accounts',
|
|
148
|
+
Trade: 'trades',
|
|
149
|
+
Action: 'actions',
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Permanently deletes a record from the database.
|
|
153
|
+
* This bypasses soft delete and removes the row entirely.
|
|
154
|
+
* Should only be used for administrative cleanup operations.
|
|
155
|
+
*
|
|
156
|
+
* @param prisma - The Prisma client instance (with $executeRawUnsafe)
|
|
157
|
+
* @param model - The model name (PascalCase)
|
|
158
|
+
* @param id - The record ID to permanently delete
|
|
159
|
+
* @returns The number of rows deleted
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```typescript
|
|
163
|
+
* // Permanently delete a soft-deleted user
|
|
164
|
+
* const deleted = await hardDelete(prisma, 'User', 'user-123');
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
async function hardDelete(prisma, model, id) {
|
|
168
|
+
const tableName = TABLE_NAME_MAP[model];
|
|
169
|
+
if (!tableName) {
|
|
170
|
+
throw new Error(`Model "${model}" does not support hard delete`);
|
|
171
|
+
}
|
|
172
|
+
logger_1.logger.warn('Hard delete: Permanently removing record', { model, id });
|
|
173
|
+
return prisma.$executeRawUnsafe(`DELETE FROM "${tableName}" WHERE "id" = $1`, id);
|
|
174
|
+
}
|
|
175
|
+
//# sourceMappingURL=soft-delete.js.map
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Soft Delete Utilities
|
|
3
|
+
*
|
|
4
|
+
* Provides utilities for soft-delete behavior on critical models.
|
|
5
|
+
* Instead of removing records from the database, a `deletedAt` timestamp
|
|
6
|
+
* is set, and query helpers filter out soft-deleted records by default.
|
|
7
|
+
*
|
|
8
|
+
* Models with soft delete support: User, AlpacaAccount, Trade, Action
|
|
9
|
+
*
|
|
10
|
+
* Usage patterns:
|
|
11
|
+
* 1. Use `softDeleteFilter()` in where clauses to exclude deleted records
|
|
12
|
+
* 2. Use `softDeleteRecord()` to soft-delete a record (set deletedAt)
|
|
13
|
+
* 3. Use `hardDelete()` for permanent administrative deletion
|
|
14
|
+
* 4. Pass `includeDeleted: true` to admin queries to see all records
|
|
15
|
+
*
|
|
16
|
+
* Note: Prisma 6 removed the $use() middleware API. Soft delete behavior
|
|
17
|
+
* is implemented via utility functions called from resolvers and services.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Models that support soft deletion via the deletedAt field.
|
|
21
|
+
* Only these models have the deletedAt column in the database.
|
|
22
|
+
*/
|
|
23
|
+
declare const SOFT_DELETE_MODELS: Set<string>;
|
|
24
|
+
/**
|
|
25
|
+
* Returns a where clause filter that excludes soft-deleted records.
|
|
26
|
+
* Can be spread into any Prisma where clause for soft-delete-aware queries.
|
|
27
|
+
*
|
|
28
|
+
* @param includeDeleted - When true, returns an empty filter (includes deleted records)
|
|
29
|
+
* @returns An object to spread into a Prisma where clause
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```typescript
|
|
33
|
+
* // Exclude soft-deleted users (default)
|
|
34
|
+
* const users = await prisma.user.findMany({
|
|
35
|
+
* where: { role: 'USER', ...softDeleteFilter() },
|
|
36
|
+
* });
|
|
37
|
+
*
|
|
38
|
+
* // Include soft-deleted users (admin query)
|
|
39
|
+
* const allUsers = await prisma.user.findMany({
|
|
40
|
+
* where: { role: 'USER', ...softDeleteFilter(true) },
|
|
41
|
+
* });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
declare function softDeleteFilter(includeDeleted?: boolean): {
|
|
45
|
+
deletedAt?: null;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Returns a where clause filter for finding only soft-deleted records.
|
|
49
|
+
* Useful for admin interfaces that need to list deleted records for restoration.
|
|
50
|
+
*
|
|
51
|
+
* @returns An object to spread into a Prisma where clause
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* // Find only soft-deleted users
|
|
56
|
+
* const deletedUsers = await prisma.user.findMany({
|
|
57
|
+
* where: { ...deletedOnlyFilter() },
|
|
58
|
+
* });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
declare function deletedOnlyFilter(): {
|
|
62
|
+
deletedAt: {
|
|
63
|
+
not: null;
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Checks whether a given model supports soft deletion.
|
|
68
|
+
*
|
|
69
|
+
* @param modelName - The Prisma model name (PascalCase)
|
|
70
|
+
* @returns True if the model has a deletedAt field
|
|
71
|
+
*/
|
|
72
|
+
declare function isSoftDeleteModel(modelName: string): boolean;
|
|
73
|
+
/** Minimal Prisma delegate interface for soft-delete operations */
|
|
74
|
+
interface PrismaModelDelegate {
|
|
75
|
+
update: (args: {
|
|
76
|
+
where: {
|
|
77
|
+
id: string;
|
|
78
|
+
};
|
|
79
|
+
data: {
|
|
80
|
+
deletedAt: Date;
|
|
81
|
+
};
|
|
82
|
+
}) => Promise<unknown>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Soft-deletes a record by setting its deletedAt timestamp.
|
|
86
|
+
* This is the recommended way to "delete" records in soft-delete-enabled models.
|
|
87
|
+
*
|
|
88
|
+
* @param delegate - The Prisma model delegate (e.g., prisma.user)
|
|
89
|
+
* @param id - The record ID to soft-delete
|
|
90
|
+
* @param modelName - The model name for logging purposes
|
|
91
|
+
* @returns The updated record
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```typescript
|
|
95
|
+
* // Soft-delete a user
|
|
96
|
+
* await softDeleteRecord(prisma.user, 'user-123', 'User');
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
declare function softDeleteRecord(delegate: PrismaModelDelegate, id: string, modelName: string): Promise<unknown>;
|
|
100
|
+
/** Minimal Prisma delegate interface for restore operations */
|
|
101
|
+
interface PrismaRestoreDelegate {
|
|
102
|
+
update: (args: {
|
|
103
|
+
where: {
|
|
104
|
+
id: string;
|
|
105
|
+
};
|
|
106
|
+
data: {
|
|
107
|
+
deletedAt: null;
|
|
108
|
+
};
|
|
109
|
+
}) => Promise<unknown>;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Restores a soft-deleted record by clearing its deletedAt timestamp.
|
|
113
|
+
*
|
|
114
|
+
* @param delegate - The Prisma model delegate (e.g., prisma.user)
|
|
115
|
+
* @param id - The record ID to restore
|
|
116
|
+
* @param modelName - The model name for logging purposes
|
|
117
|
+
* @returns The updated record
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```typescript
|
|
121
|
+
* // Restore a soft-deleted user
|
|
122
|
+
* await restoreRecord(prisma.user, 'user-123', 'User');
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
declare function restoreRecord(delegate: PrismaRestoreDelegate, id: string, modelName: string): Promise<unknown>;
|
|
126
|
+
/**
|
|
127
|
+
* Permanently deletes a record from the database.
|
|
128
|
+
* This bypasses soft delete and removes the row entirely.
|
|
129
|
+
* Should only be used for administrative cleanup operations.
|
|
130
|
+
*
|
|
131
|
+
* @param prisma - The Prisma client instance (with $executeRawUnsafe)
|
|
132
|
+
* @param model - The model name (PascalCase)
|
|
133
|
+
* @param id - The record ID to permanently delete
|
|
134
|
+
* @returns The number of rows deleted
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* ```typescript
|
|
138
|
+
* // Permanently delete a soft-deleted user
|
|
139
|
+
* const deleted = await hardDelete(prisma, 'User', 'user-123');
|
|
140
|
+
* ```
|
|
141
|
+
*/
|
|
142
|
+
declare function hardDelete(prisma: {
|
|
143
|
+
$executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;
|
|
144
|
+
}, model: string, id: string): Promise<number>;
|
|
145
|
+
export { SOFT_DELETE_MODELS, softDeleteFilter, deletedOnlyFilter, isSoftDeleteModel, softDeleteRecord, restoreRecord, hardDelete, };
|
|
146
|
+
//# sourceMappingURL=soft-delete.d.ts.map
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Row-level tenancy-scoping middleware (SP2-G7 / SOC2 hardening).
|
|
4
|
+
*
|
|
5
|
+
* A TypeGraphQL global middleware that restricts the auto-generated CRUD
|
|
6
|
+
* resolvers for the tenancy + notification models — Organization, OrgMembership,
|
|
7
|
+
* Fund, FundAssignment, BrokerageAccount, NotificationEvent,
|
|
8
|
+
* NotificationDelivery, NotificationPreference — to the rows a USER-scoped
|
|
9
|
+
* caller is entitled to.
|
|
10
|
+
*
|
|
11
|
+
* CRITICAL SAFETY CONTRACT: service (`SERVER_AUTH_TOKEN`) and admin principals
|
|
12
|
+
* — and, on the staged models, unauthenticated callers, which carry no user
|
|
13
|
+
* identity — are bypassed before any scoping runs, in EVERY mode. The desk
|
|
14
|
+
* models (`ALWAYS_ENFORCED_MODELS` in src/auth/tenancy-scope.ts) are the
|
|
15
|
+
* exception: they are scoped in every mode and refuse an unauthenticated
|
|
16
|
+
* caller with `UNAUTHENTICATED`. The engine and utils call these
|
|
17
|
+
* resolvers with a server principal and MUST retain full unscoped access; this
|
|
18
|
+
* middleware never narrows or denies a server/admin query.
|
|
19
|
+
*
|
|
20
|
+
* Behaviour is gated by `TENANCY_SCOPING_MODE` (default `shadow`), mirroring the
|
|
21
|
+
* engine WS channel-auth shadow→enforce rollout:
|
|
22
|
+
*
|
|
23
|
+
* - `off` — returns immediately; no classification, no entitlement lookup.
|
|
24
|
+
* - `shadow` — executes the resolver UNCHANGED, but emits a metric and a
|
|
25
|
+
* structured log for every access that `enforce` WOULD restrict or deny.
|
|
26
|
+
* - `enforce` — AND-injects the scope predicate into read `where` clauses and
|
|
27
|
+
* raises a `FORBIDDEN` GraphQL error on cross-tenant create/upsert.
|
|
28
|
+
*
|
|
29
|
+
* The middleware runs on every resolver in the schema, so its first action is a
|
|
30
|
+
* cheap guard: it only engages for root Query/Mutation fields whose name maps
|
|
31
|
+
* to a governed model (nested relation resolvers and non-governed models return
|
|
32
|
+
* immediately).
|
|
33
|
+
*
|
|
34
|
+
* Known scope boundary (tracked as a follow-up): scoping is applied at the root
|
|
35
|
+
* operation only. A governed model reached transitively through a NON-governed
|
|
36
|
+
* root (e.g. `User.orgMemberships`) is not re-scoped here; that residual vector
|
|
37
|
+
* is closed by the forthcoming resolver-level `AuthChecker` (CORTEX-P0-001) and
|
|
38
|
+
* by the platform's app-side authorization. The direct cross-tenant root
|
|
39
|
+
* read/mutation vector called out in SP2-G7 is what this middleware closes.
|
|
40
|
+
*/
|
|
41
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
+
exports.createTenancyScopingMiddleware = createTenancyScopingMiddleware;
|
|
43
|
+
const graphql_1 = require("graphql");
|
|
44
|
+
const tenancy_scope_1 = require("../auth/tenancy-scope.cjs");
|
|
45
|
+
const metrics_1 = require("../config/metrics.cjs");
|
|
46
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
47
|
+
/**
|
|
48
|
+
* Build a `FORBIDDEN` GraphQL error for a denied cross-tenant mutation. The
|
|
49
|
+
* `http.status: 403` is honoured by the `http-status-mapper` plugin.
|
|
50
|
+
*/
|
|
51
|
+
function forbidden(message) {
|
|
52
|
+
return new graphql_1.GraphQLError(message, {
|
|
53
|
+
extensions: { code: 'FORBIDDEN', http: { status: 403 } },
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** An `UNAUTHENTICATED` GraphQL error (HTTP 401) for an always-enforced model. */
|
|
57
|
+
function unauthenticated(model) {
|
|
58
|
+
return new graphql_1.GraphQLError(`Unauthenticated: ${model} requires a verified principal`, {
|
|
59
|
+
extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* For a create the payload cannot prove in scope on its own (a model scoped
|
|
64
|
+
* by a parent row, such as an Ada message by its conversation), read the
|
|
65
|
+
* parent under the caller's write scope. Any other assessment is returned as is.
|
|
66
|
+
*/
|
|
67
|
+
async function withParentScope(governed, assessment, args, context, entitlement) {
|
|
68
|
+
if (governed.opKind !== 'createScope' || assessment.decision !== 'deny')
|
|
69
|
+
return assessment;
|
|
70
|
+
if (!(0, tenancy_scope_1.hasCreateParent)(governed.model))
|
|
71
|
+
return assessment;
|
|
72
|
+
const prisma = context.prisma;
|
|
73
|
+
if (!prisma)
|
|
74
|
+
return assessment;
|
|
75
|
+
return (await (0, tenancy_scope_1.parentScopedCreateInScope)(prisma, governed.model, args.data, entitlement))
|
|
76
|
+
? { decision: 'allow', reason: 'create_parent_in_scope' }
|
|
77
|
+
: assessment;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Resolve (and memoise for the request) the caller's entitlement. Throws when
|
|
81
|
+
* the Prisma client is missing from the context so callers can fail closed
|
|
82
|
+
* under enforcement.
|
|
83
|
+
*/
|
|
84
|
+
function getEntitlement(context, userId) {
|
|
85
|
+
if (!context.__tenancyEntitlement) {
|
|
86
|
+
const prisma = context.prisma;
|
|
87
|
+
context.__tenancyEntitlement = prisma
|
|
88
|
+
? (0, tenancy_scope_1.resolveEntitlement)(prisma, userId)
|
|
89
|
+
: Promise.reject(new Error('tenancy scoping: Prisma client missing from context'));
|
|
90
|
+
}
|
|
91
|
+
return context.__tenancyEntitlement;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Create the TypeGraphQL global middleware enforcing row-level tenancy scoping.
|
|
95
|
+
*
|
|
96
|
+
* @param options - Optional overrides (mode provider) for testing.
|
|
97
|
+
* @returns A {@link MiddlewareFn} to register via `buildSchema({ globalMiddlewares })`.
|
|
98
|
+
*/
|
|
99
|
+
function createTenancyScopingMiddleware(options = {}) {
|
|
100
|
+
var _a;
|
|
101
|
+
const resolveMode = (_a = options.modeProvider) !== null && _a !== void 0 ? _a : tenancy_scope_1.getTenancyScopingMode;
|
|
102
|
+
return async ({ context, args, info }, next) => {
|
|
103
|
+
var _a, _b, _c, _d;
|
|
104
|
+
// `next` is typed `() => Promise<any>` by type-graphql. Widen it once to a
|
|
105
|
+
// typed pass-through so returning it downstream is not an unsafe-any return.
|
|
106
|
+
const proceed = () => next();
|
|
107
|
+
// Only the root Query/Mutation entry points are scoped. Nested relation
|
|
108
|
+
// resolvers (parentType is a model) and every non-governed field short out
|
|
109
|
+
// here — the cheapest possible path for the hot resolver stack.
|
|
110
|
+
const parentTypeName = (_a = info.parentType) === null || _a === void 0 ? void 0 : _a.name;
|
|
111
|
+
if (parentTypeName !== 'Query' && parentTypeName !== 'Mutation') {
|
|
112
|
+
return proceed();
|
|
113
|
+
}
|
|
114
|
+
const governed = (0, tenancy_scope_1.classifyGovernedField)(info.fieldName);
|
|
115
|
+
if (!governed)
|
|
116
|
+
return proceed();
|
|
117
|
+
// An always-enforced (desk) model is scoped whatever the configured mode;
|
|
118
|
+
// see ALWAYS_ENFORCED_MODELS for why it has no shadow or off state.
|
|
119
|
+
const alwaysEnforced = (0, tenancy_scope_1.isAlwaysEnforced)(governed.model);
|
|
120
|
+
const mode = alwaysEnforced ? 'enforce' : resolveMode();
|
|
121
|
+
if (mode === 'off')
|
|
122
|
+
return proceed();
|
|
123
|
+
// Principal gate: service/admin callers are NEVER scoped. An
|
|
124
|
+
// unauthenticated caller carries no identity to scope by: a model with an
|
|
125
|
+
// anonymous scope (the SYSTEM strategies) narrows it to that scope, the
|
|
126
|
+
// staged models pass it, and the always-enforced ones refuse it.
|
|
127
|
+
const principal = context.principal;
|
|
128
|
+
if (!principal) {
|
|
129
|
+
const anonymousScope = (0, tenancy_scope_1.anonymousScopeWhere)(governed.model);
|
|
130
|
+
if (anonymousScope !== null && governed.opKind === 'whereScope') {
|
|
131
|
+
metrics_1.tenancyScopingDecisionsTotal.inc({
|
|
132
|
+
mode,
|
|
133
|
+
model: governed.model,
|
|
134
|
+
operation: info.fieldName,
|
|
135
|
+
decision: 'restrict',
|
|
136
|
+
});
|
|
137
|
+
args.where = (0, tenancy_scope_1.injectScopeWhere)((_b = args.where) !== null && _b !== void 0 ? _b : undefined, anonymousScope);
|
|
138
|
+
return proceed();
|
|
139
|
+
}
|
|
140
|
+
if (alwaysEnforced) {
|
|
141
|
+
metrics_1.tenancyScopingDecisionsTotal.inc({
|
|
142
|
+
mode,
|
|
143
|
+
model: governed.model,
|
|
144
|
+
operation: info.fieldName,
|
|
145
|
+
decision: 'deny',
|
|
146
|
+
});
|
|
147
|
+
throw unauthenticated(governed.model);
|
|
148
|
+
}
|
|
149
|
+
return proceed();
|
|
150
|
+
}
|
|
151
|
+
if (principal.kind === 'server' || principal.kind === 'admin') {
|
|
152
|
+
return proceed();
|
|
153
|
+
}
|
|
154
|
+
// From here the principal is user-scoped.
|
|
155
|
+
const userId = principal.sub;
|
|
156
|
+
let entitlement;
|
|
157
|
+
try {
|
|
158
|
+
entitlement = await getEntitlement(context, userId);
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
// Fail closed under enforcement; in shadow, log and let the query run
|
|
162
|
+
// unchanged so a transient resolution failure never blocks traffic while
|
|
163
|
+
// we are still proving the rollout.
|
|
164
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
165
|
+
if (mode === 'enforce') {
|
|
166
|
+
logger_1.logger.error('[tenancy-scope] enforce: entitlement resolution failed — denying', { model: governed.model, operation: info.fieldName, userId, detail });
|
|
167
|
+
metrics_1.tenancyScopingDecisionsTotal.inc({
|
|
168
|
+
mode,
|
|
169
|
+
model: governed.model,
|
|
170
|
+
operation: info.fieldName,
|
|
171
|
+
decision: 'deny',
|
|
172
|
+
});
|
|
173
|
+
throw forbidden('Access denied: tenancy entitlement unavailable');
|
|
174
|
+
}
|
|
175
|
+
logger_1.logger.warn('[tenancy-scope] shadow: entitlement resolution failed — allowing', { model: governed.model, operation: info.fieldName, userId, detail });
|
|
176
|
+
return proceed();
|
|
177
|
+
}
|
|
178
|
+
const assessment = await withParentScope(governed, (0, tenancy_scope_1.evaluateAccess)(governed, args, entitlement), args, context, entitlement);
|
|
179
|
+
metrics_1.tenancyScopingDecisionsTotal.inc({
|
|
180
|
+
mode,
|
|
181
|
+
model: governed.model,
|
|
182
|
+
operation: info.fieldName,
|
|
183
|
+
decision: assessment.decision,
|
|
184
|
+
});
|
|
185
|
+
// --- shadow: execute UNCHANGED, but log what enforce would do ------------
|
|
186
|
+
if (mode === 'shadow') {
|
|
187
|
+
if (assessment.decision !== 'allow') {
|
|
188
|
+
logger_1.logger.warn('[tenancy-scope] shadow: enforce would restrict cross-tenant access', {
|
|
189
|
+
model: governed.model,
|
|
190
|
+
operation: info.fieldName,
|
|
191
|
+
opKind: governed.opKind,
|
|
192
|
+
decision: assessment.decision,
|
|
193
|
+
reason: assessment.reason,
|
|
194
|
+
userId,
|
|
195
|
+
orgCount: entitlement.orgIds.length,
|
|
196
|
+
fundCount: entitlement.fundIds.length,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return proceed();
|
|
200
|
+
}
|
|
201
|
+
// --- enforce -------------------------------------------------------------
|
|
202
|
+
// A write (update, delete, upsert) is held to the write scope, which is
|
|
203
|
+
// narrower than the read scope for models a member may read but only the
|
|
204
|
+
// author may change (a shared Ada conversation).
|
|
205
|
+
const scopeFor = parentTypeName === 'Mutation' ? tenancy_scope_1.buildWriteScopeWhere : tenancy_scope_1.buildScopeWhere;
|
|
206
|
+
if (governed.opKind === 'whereScope') {
|
|
207
|
+
const scoped = (0, tenancy_scope_1.injectScopeWhere)((_c = args.where) !== null && _c !== void 0 ? _c : undefined, scopeFor(governed.model, entitlement));
|
|
208
|
+
args.where = scoped;
|
|
209
|
+
return proceed();
|
|
210
|
+
}
|
|
211
|
+
// create/upsert
|
|
212
|
+
if (assessment.decision === 'deny') {
|
|
213
|
+
logger_1.logger.warn('[tenancy-scope] enforce: denied cross-tenant mutation', {
|
|
214
|
+
model: governed.model,
|
|
215
|
+
operation: info.fieldName,
|
|
216
|
+
opKind: governed.opKind,
|
|
217
|
+
reason: assessment.reason,
|
|
218
|
+
userId,
|
|
219
|
+
});
|
|
220
|
+
throw forbidden(`Access denied: ${governed.model} target is outside your organization`);
|
|
221
|
+
}
|
|
222
|
+
if (governed.opKind === 'upsertScope') {
|
|
223
|
+
const scoped = (0, tenancy_scope_1.injectScopeWhere)((_d = args.where) !== null && _d !== void 0 ? _d : undefined, scopeFor(governed.model, entitlement));
|
|
224
|
+
args.where = scoped;
|
|
225
|
+
}
|
|
226
|
+
return proceed();
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
//# sourceMappingURL=tenancy-scoping.js.map
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Row-level tenancy-scoping middleware (SP2-G7 / SOC2 hardening).
|
|
3
|
+
*
|
|
4
|
+
* A TypeGraphQL global middleware that restricts the auto-generated CRUD
|
|
5
|
+
* resolvers for the tenancy + notification models — Organization, OrgMembership,
|
|
6
|
+
* Fund, FundAssignment, BrokerageAccount, NotificationEvent,
|
|
7
|
+
* NotificationDelivery, NotificationPreference — to the rows a USER-scoped
|
|
8
|
+
* caller is entitled to.
|
|
9
|
+
*
|
|
10
|
+
* CRITICAL SAFETY CONTRACT: service (`SERVER_AUTH_TOKEN`) and admin principals
|
|
11
|
+
* — and, on the staged models, unauthenticated callers, which carry no user
|
|
12
|
+
* identity — are bypassed before any scoping runs, in EVERY mode. The desk
|
|
13
|
+
* models (`ALWAYS_ENFORCED_MODELS` in src/auth/tenancy-scope.ts) are the
|
|
14
|
+
* exception: they are scoped in every mode and refuse an unauthenticated
|
|
15
|
+
* caller with `UNAUTHENTICATED`. The engine and utils call these
|
|
16
|
+
* resolvers with a server principal and MUST retain full unscoped access; this
|
|
17
|
+
* middleware never narrows or denies a server/admin query.
|
|
18
|
+
*
|
|
19
|
+
* Behaviour is gated by `TENANCY_SCOPING_MODE` (default `shadow`), mirroring the
|
|
20
|
+
* engine WS channel-auth shadow→enforce rollout:
|
|
21
|
+
*
|
|
22
|
+
* - `off` — returns immediately; no classification, no entitlement lookup.
|
|
23
|
+
* - `shadow` — executes the resolver UNCHANGED, but emits a metric and a
|
|
24
|
+
* structured log for every access that `enforce` WOULD restrict or deny.
|
|
25
|
+
* - `enforce` — AND-injects the scope predicate into read `where` clauses and
|
|
26
|
+
* raises a `FORBIDDEN` GraphQL error on cross-tenant create/upsert.
|
|
27
|
+
*
|
|
28
|
+
* The middleware runs on every resolver in the schema, so its first action is a
|
|
29
|
+
* cheap guard: it only engages for root Query/Mutation fields whose name maps
|
|
30
|
+
* to a governed model (nested relation resolvers and non-governed models return
|
|
31
|
+
* immediately).
|
|
32
|
+
*
|
|
33
|
+
* Known scope boundary (tracked as a follow-up): scoping is applied at the root
|
|
34
|
+
* operation only. A governed model reached transitively through a NON-governed
|
|
35
|
+
* root (e.g. `User.orgMemberships`) is not re-scoped here; that residual vector
|
|
36
|
+
* is closed by the forthcoming resolver-level `AuthChecker` (CORTEX-P0-001) and
|
|
37
|
+
* by the platform's app-side authorization. The direct cross-tenant root
|
|
38
|
+
* read/mutation vector called out in SP2-G7 is what this middleware closes.
|
|
39
|
+
*/
|
|
40
|
+
import type { MiddlewareFn } from 'type-graphql';
|
|
41
|
+
import type { BackendPrincipal } from '../auth/token-verifier';
|
|
42
|
+
import { type Entitlement, type TenancyScopingMode } from '../auth/tenancy-scope';
|
|
43
|
+
/**
|
|
44
|
+
* GraphQL context shape this middleware reads. `principal` is the verified
|
|
45
|
+
* `BackendPrincipal` (added to the context in `server.ts`); `prisma` is the
|
|
46
|
+
* request-scoped Prisma client the generated resolvers already rely on. The
|
|
47
|
+
* memoised entitlement promise is cached on the context for the request.
|
|
48
|
+
*/
|
|
49
|
+
export interface TenancyScopingContext {
|
|
50
|
+
principal?: BackendPrincipal | null;
|
|
51
|
+
prisma?: unknown;
|
|
52
|
+
/** @internal per-request memoised entitlement resolution. */
|
|
53
|
+
__tenancyEntitlement?: Promise<Entitlement>;
|
|
54
|
+
}
|
|
55
|
+
/** Options for {@link createTenancyScopingMiddleware}, primarily for tests. */
|
|
56
|
+
export interface TenancyScopingMiddlewareOptions {
|
|
57
|
+
/** Override the mode resolver (defaults to reading `TENANCY_SCOPING_MODE`). */
|
|
58
|
+
modeProvider?: () => TenancyScopingMode;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Create the TypeGraphQL global middleware enforcing row-level tenancy scoping.
|
|
62
|
+
*
|
|
63
|
+
* @param options - Optional overrides (mode provider) for testing.
|
|
64
|
+
* @returns A {@link MiddlewareFn} to register via `buildSchema({ globalMiddlewares })`.
|
|
65
|
+
*/
|
|
66
|
+
export declare function createTenancyScopingMiddleware(options?: TenancyScopingMiddlewareOptions): MiddlewareFn<TenancyScopingContext>;
|
|
67
|
+
//# sourceMappingURL=tenancy-scoping.d.ts.map
|