@tearleads/client-sdk 0.1.212 → 0.1.215
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/client/containerContents/documentDiscovery.js +2 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/organizations/organizationReadModels.js +3 -3
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +11 -2
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +89 -77
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js +0 -43
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +7 -2
- package/data/persistence/organizations/organizationReadModelMemberLoad.js +22 -27
- package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPersistence.js +38 -81
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +0 -38
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelRepository.js +264 -0
- package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -0
- package/package.json +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +6 -2
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/index.d.ts +0 -1
- package/workflows/organizations/index.js +0 -1
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js +7 -4
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -1
- package/workflows/organizations/readModel/dataUsageReadModel.js +2 -2
- package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +4 -2
- package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +8 -9
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/organizations/readModel/organizationPresentationAccessState.js +2 -2
- package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.d.ts +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +12 -13
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js +0 -49
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +0 -1
- package/data/persistence/organizations/organizationGroupNamePersistence.js +0 -33
- package/data/persistence/organizations/organizationGroupNamePersistence.js.map +0 -1
- package/data/persistence/organizations/organizationProfileDocumentPointers.js +0 -32
- package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +0 -1
- package/data/persistence/organizations/organizationReadModelCursorPersistence.d.ts +0 -15
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js +0 -25
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js.map +0 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { and, eq } from "drizzle-orm";
|
|
2
|
+
import { getOrCreatePrincipalPolicyCoordinator } from "../../principals/principalPolicyCoordinator.js";
|
|
3
|
+
import { organizationReadModelTables } from "../../sqlite/schema/index.js";
|
|
4
|
+
import { organizationDataUsageTables } from "../../sqlite/schema/organizationDataUsageSchema.js";
|
|
5
|
+
import { organizationPresentationDenials, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/schema/organizationReadModelSchema.js";
|
|
6
|
+
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
|
+
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
8
|
+
import { purgeOrganizationDataUsageProjectionInTransaction } from "./organizationDataUsagePersistence.js";
|
|
9
|
+
import { notifyOrganizationReadModelInvalidated } from "./organizationReadModelInvalidation.js";
|
|
10
|
+
import { loadRequesterOrganizationReadModelGroupMembersInTransaction, } from "./organizationReadModelMemberLoad.js";
|
|
11
|
+
import { applyOrganizationReadModelResponseInTransaction, } from "./organizationReadModelPersistence.js";
|
|
12
|
+
import { loadOrganizationReadModelProjectionInTransaction, } from "./organizationReadModelProjection.js";
|
|
13
|
+
import { OrganizationReadModelIntegrityError } from "./organizationReadModelProtocol.js";
|
|
14
|
+
import { purgeOrganizationReadModelProjectionInTransaction } from "./organizationReadModelPurge.js";
|
|
15
|
+
import { assertOrganizationReadModelResponse } from "./organizationReadModelResponseAssertions.js";
|
|
16
|
+
const organizationAccessProjectionTables = [
|
|
17
|
+
...organizationReadModelTables,
|
|
18
|
+
...organizationDataUsageTables,
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* The durable organization read-model projection, its group display names,
|
|
22
|
+
* and its presentation denial markers, over one database. Invalidation
|
|
23
|
+
* notices and recovery invalidation are keyed by the executor this
|
|
24
|
+
* repository was built from.
|
|
25
|
+
*/
|
|
26
|
+
export class OrganizationReadModelRepository {
|
|
27
|
+
execSql;
|
|
28
|
+
now;
|
|
29
|
+
constructor(execSql, now = () => new Date()) {
|
|
30
|
+
this.execSql = execSql;
|
|
31
|
+
this.now = now;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The ONE load shell for the durable read-model projection: run `load` in a
|
|
35
|
+
* transaction and, if a stored row fails integrity validation, purge the
|
|
36
|
+
* organization's projection and report null. The projection is a
|
|
37
|
+
* server-refetchable cache, so the next reconcile requests a cursorless
|
|
38
|
+
* snapshot instead of every read and repair pass failing on the same row.
|
|
39
|
+
*/
|
|
40
|
+
async loadWithOrganizationReadModelIntegrityPurge(input) {
|
|
41
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
42
|
+
let purgedInvalidRows = false;
|
|
43
|
+
const result = await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
44
|
+
try {
|
|
45
|
+
return await input.load(tx);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (!(error instanceof OrganizationReadModelIntegrityError)) {
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
52
|
+
organizationId: input.organizationId,
|
|
53
|
+
tx,
|
|
54
|
+
});
|
|
55
|
+
purgedInvalidRows = true;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
if (purgedInvalidRows) {
|
|
60
|
+
// Realtime consumers may hold a caught-up lease over rows that no longer
|
|
61
|
+
// exist; the notification lets them drop it and refetch authoritatively.
|
|
62
|
+
notifyOrganizationReadModelInvalidated(this.execSql, input.organizationId);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
async loadOrganizationReadModelProjection(organizationId, currentUserId) {
|
|
67
|
+
return this.loadWithOrganizationReadModelIntegrityPurge({
|
|
68
|
+
organizationId,
|
|
69
|
+
load: (tx) => loadOrganizationReadModelProjectionInTransaction({
|
|
70
|
+
currentUserId,
|
|
71
|
+
organizationId,
|
|
72
|
+
tx,
|
|
73
|
+
}),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async loadOrganizationReadModelGroupMembers(organizationId, groupId, currentUserId) {
|
|
77
|
+
return this.loadWithOrganizationReadModelIntegrityPurge({
|
|
78
|
+
organizationId,
|
|
79
|
+
load: (tx) => loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {
|
|
80
|
+
currentUserId,
|
|
81
|
+
groupId,
|
|
82
|
+
organizationId,
|
|
83
|
+
}),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async applyOrganizationReadModelResponse(input) {
|
|
87
|
+
assertOrganizationReadModelResponse({
|
|
88
|
+
currentUserId: input.currentUserId,
|
|
89
|
+
response: input.response,
|
|
90
|
+
});
|
|
91
|
+
// The requester prune also retires pruned users' usage projections.
|
|
92
|
+
await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
|
|
93
|
+
const disposition = await getClientSQLitePersistenceRuntime(this.execSql).transaction((tx) => applyOrganizationReadModelResponseInTransaction(tx, {
|
|
94
|
+
currentUserId: input.currentUserId,
|
|
95
|
+
now: this.now,
|
|
96
|
+
requestedCursor: input.requestedCursor,
|
|
97
|
+
response: input.response,
|
|
98
|
+
}));
|
|
99
|
+
// An applied change follows an organization hint or mutation; in-flight
|
|
100
|
+
// operations recover the directory again instead of reusing their memo.
|
|
101
|
+
if (disposition === "applied")
|
|
102
|
+
getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.response.organizationId);
|
|
103
|
+
return disposition;
|
|
104
|
+
}
|
|
105
|
+
async purgeOrganizationReadModelProjection(organizationId, options = {}) {
|
|
106
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
107
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
108
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
109
|
+
onlyRequesterUserId: options.onlyRequesterUserId,
|
|
110
|
+
organizationId,
|
|
111
|
+
tx,
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Purge one requester's access to an organization's presentation projections
|
|
117
|
+
* after the server denied that requester. The denial is requester-scoped: the
|
|
118
|
+
* shared read-model rows stay while another local identity in the same
|
|
119
|
+
* database still holds a requester row, and organization-wide rows fall with
|
|
120
|
+
* the last requester.
|
|
121
|
+
*/
|
|
122
|
+
async purgeOrganizationAccessProjection(input) {
|
|
123
|
+
await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
|
|
124
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
125
|
+
await tx
|
|
126
|
+
.delete(organizationReadModelRequesters)
|
|
127
|
+
.where(and(eq(organizationReadModelRequesters.organizationId, input.organizationId), eq(organizationReadModelRequesters.userId, input.requesterUserId)))
|
|
128
|
+
.run();
|
|
129
|
+
const [remainingRequester] = await tx
|
|
130
|
+
.select({ userId: organizationReadModelRequesters.userId })
|
|
131
|
+
.from(organizationReadModelRequesters)
|
|
132
|
+
.where(eq(organizationReadModelRequesters.organizationId, input.organizationId))
|
|
133
|
+
.limit(1);
|
|
134
|
+
if (!remainingRequester) {
|
|
135
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
136
|
+
organizationId: input.organizationId,
|
|
137
|
+
tx,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
await purgeOrganizationDataUsageProjectionInTransaction({
|
|
141
|
+
organizationId: input.organizationId,
|
|
142
|
+
requesterUserId: input.requesterUserId,
|
|
143
|
+
tx,
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
// A denial is a realtime-hinted access change: in-flight operations recover
|
|
147
|
+
// the organization's directory again instead of reusing their memo.
|
|
148
|
+
getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.organizationId);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The cursor this requester has applied, or null when it holds none. The
|
|
152
|
+
* organization row's cursor is shared: another identity on this device may
|
|
153
|
+
* have advanced it while this requester's own fields (for example
|
|
154
|
+
* `isOrgAdmin`) still reflect an older response. Only the requester's own
|
|
155
|
+
* applied cursor, while it is still the stored projection's cursor, proves
|
|
156
|
+
* this requester is current. Realtime hints compare against it so a hint for
|
|
157
|
+
* a cursor already applied costs no read.
|
|
158
|
+
*/
|
|
159
|
+
async loadAppliedOrganizationReadModelCursor(input) {
|
|
160
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
161
|
+
const [row] = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
162
|
+
.db.select({ cursor: organizationReadModelRequesters.appliedCursor })
|
|
163
|
+
.from(organizationReadModelRequesters)
|
|
164
|
+
.innerJoin(organizationReadModelState, and(eq(organizationReadModelState.organizationId, organizationReadModelRequesters.organizationId), eq(organizationReadModelState.cursor, organizationReadModelRequesters.appliedCursor)))
|
|
165
|
+
.where(and(eq(organizationReadModelRequesters.organizationId, input.organizationId), eq(organizationReadModelRequesters.userId, input.requesterUserId)))
|
|
166
|
+
.limit(1);
|
|
167
|
+
return row?.cursor ?? null;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Every locally projected organization's pointer to its organization_profile
|
|
171
|
+
* document, keyed by organization id.
|
|
172
|
+
*
|
|
173
|
+
* This is the only container-independent handle on that document. Callers
|
|
174
|
+
* that need an org's display name from local state cannot rely on where the
|
|
175
|
+
* document is linked: the provisioner writes it under a deterministic local
|
|
176
|
+
* alias into the organization-metadata container, while a device that only
|
|
177
|
+
* *synced* it (identity recovery, another member) keys it under the server
|
|
178
|
+
* documentId in whichever container the grant arrived through.
|
|
179
|
+
*
|
|
180
|
+
* The local schema stores only the current read-model contract, so every
|
|
181
|
+
* state row is eligible to provide its profile-document pointer.
|
|
182
|
+
*/
|
|
183
|
+
async loadOrganizationProfileDocumentIds() {
|
|
184
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
185
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
186
|
+
const rows = await db
|
|
187
|
+
.select({
|
|
188
|
+
organizationId: organizationReadModelState.organizationId,
|
|
189
|
+
profileDocumentId: organizationReadModelState.profileDocumentId,
|
|
190
|
+
})
|
|
191
|
+
.from(organizationReadModelState);
|
|
192
|
+
return new Map(rows.flatMap((row) => row.profileDocumentId
|
|
193
|
+
? [[row.organizationId, row.profileDocumentId]]
|
|
194
|
+
: []));
|
|
195
|
+
}
|
|
196
|
+
async loadOrganizationGroupDisplayNames(organizationId) {
|
|
197
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
198
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
199
|
+
const rows = await db
|
|
200
|
+
.select({
|
|
201
|
+
groupId: organizationReadModelGroups.groupId,
|
|
202
|
+
name: organizationReadModelGroups.name,
|
|
203
|
+
})
|
|
204
|
+
.from(organizationReadModelGroups)
|
|
205
|
+
.where(eq(organizationReadModelGroups.organizationId, organizationId));
|
|
206
|
+
return new Map(rows
|
|
207
|
+
.filter((row) => row.name.length > 0)
|
|
208
|
+
.map((row) => [row.groupId, row.name]));
|
|
209
|
+
}
|
|
210
|
+
/** Local display cache only: these labels never enter a server request. */
|
|
211
|
+
async saveOrganizationGroupDisplayNames(input) {
|
|
212
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
213
|
+
await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(async (tx) => {
|
|
214
|
+
for (const group of input.names) {
|
|
215
|
+
await tx
|
|
216
|
+
.update(organizationReadModelGroups)
|
|
217
|
+
.set({ name: group.name })
|
|
218
|
+
.where(and(eq(organizationReadModelGroups.organizationId, input.organizationId), eq(organizationReadModelGroups.groupId, group.groupId), eq(organizationReadModelGroups.stateHash, group.stateHash)))
|
|
219
|
+
.run();
|
|
220
|
+
}
|
|
221
|
+
}, input.stillCurrent);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Durably record a server denial before the revoked projection rows are
|
|
225
|
+
* purged. The marker is what keeps a failed purge plus an offline restart
|
|
226
|
+
* from serving the revoked projection; it is cleared only when an
|
|
227
|
+
* authoritative reconcile stores fresh server state for the same scope.
|
|
228
|
+
*/
|
|
229
|
+
async recordOrganizationPresentationDenials(scope, projections) {
|
|
230
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
231
|
+
const deniedAt = this.now().toISOString();
|
|
232
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
233
|
+
for (const projection of new Set(projections)) {
|
|
234
|
+
await tx
|
|
235
|
+
.insert(organizationPresentationDenials)
|
|
236
|
+
.values({
|
|
237
|
+
organizationId: scope.organizationId,
|
|
238
|
+
requesterUserId: scope.requesterUserId,
|
|
239
|
+
projection,
|
|
240
|
+
deniedAt,
|
|
241
|
+
})
|
|
242
|
+
.onConflictDoUpdate({
|
|
243
|
+
target: [
|
|
244
|
+
organizationPresentationDenials.organizationId,
|
|
245
|
+
organizationPresentationDenials.requesterUserId,
|
|
246
|
+
organizationPresentationDenials.projection,
|
|
247
|
+
],
|
|
248
|
+
set: { deniedAt },
|
|
249
|
+
})
|
|
250
|
+
.run();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async hasOrganizationPresentationDenial(scope, projection) {
|
|
255
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
256
|
+
const rows = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
257
|
+
.db.select({ projection: organizationPresentationDenials.projection })
|
|
258
|
+
.from(organizationPresentationDenials)
|
|
259
|
+
.where(and(eq(organizationPresentationDenials.organizationId, scope.organizationId), eq(organizationPresentationDenials.requesterUserId, scope.requesterUserId), eq(organizationPresentationDenials.projection, projection)))
|
|
260
|
+
.limit(1);
|
|
261
|
+
return rows.length > 0;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
//# sourceMappingURL=organizationReadModelRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE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AAC;QACZ,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(\n (tx): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n }),\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentDiscoveryEvidence.js","sourceRoot":"","sources":["documentDiscoveryEvidence.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AAEtE,wEAAwE;AACxE,yEAAyE;AACzE,SAAS,mBAAmB,CAC1B,IAAiC,EACjC,KAAkC;IAElC,OAAO,IAAI,C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esContent":["import type { DiscoveredDocumentInput } from \"../../../data/documents/documentSummary\";\nimport type {\n DiscoveredDocumentCandidate,\n DocumentDiscoveryEvidenceRepository,\n} from \"../../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport type {\n DocumentHeadLinkSetLoader,\n LocalDocumentAccessEpochLoader,\n VerifiedDocumentHeadLinkSet,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport {\n HEAD_LINK_SET_LOAD_CONCURRENCY,\n HEAD_LINK_SET_LOADS_PER_RUN,\n} from \"../tombstones/documentTombstoneEvidence\";\nimport { groupPendingDocumentDiscoveries } from \"./documentDiscoveryCandidates\";\nimport type { DiscoverContainerDocumentsOptions } from \"./documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"./documentHeadScope\";\n\n// A same-epoch head can predate a link addition. Only the named head or\n// terminal signed purge evidence can settle a candidate without a retry.\nfunction unlistedHeadVerdict(\n head: VerifiedDocumentHeadLinkSet,\n input: DiscoveredDocumentCandidate,\n): null | \"unavailable\" {\n return head.accessEpoch > input.accessEpoch ||\n head.accessStateHash === input.accessStateHash ||\n (!head.accessStateHash && head.accessEpoch === Number.MAX_SAFE_INTEGER)\n ? null\n : \"unavailable\";\n}\n\nasync function verifyInput(\n input: DiscoveredDocumentCandidate,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceRepository,\n generation: number,\n organizationId: string | undefined,\n): Promise<DiscoveredDocumentInput | null | \"unavailable\"> {\n const localEpoch = await loadLocalEpoch(input.documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n const cached = await store.loadHead(input.documentId, input.accessStateHash);\n const minimumEpoch = Math.max(localEpoch, input.accessEpoch);\n const head =\n cached && cached.accessEpoch >= minimumEpoch\n ? cached\n : await loadHead(\n input.documentId,\n input.accessEpoch >= localEpoch\n ? (input.accessStateHash ?? undefined)\n : undefined,\n );\n if (head === \"not-found\") return null;\n if (!head || head.accessEpoch < Math.max(localEpoch, input.accessEpoch))\n return \"unavailable\";\n if (!documentHeadMatchesOrganization(head, organizationId))\n return \"unavailable\";\n // A stale first lane must not hide a document present in another listed lane.\n const containerId = input.listedContainerIds.find((id) =>\n head.linkedContainerIds.includes(id),\n );\n if (!containerId) return unlistedHeadVerdict(head, input);\n if (!head.accessStateHash) return \"unavailable\";\n if (!(await store.saveHead(input.documentId, head, generation)))\n return \"unavailable\";\n const { listedContainerIds: _listedContainerIds, ...document } = input;\n return {\n ...document,\n containerId,\n accessEpoch: head.accessEpoch,\n accessStateHash: head.accessStateHash,\n linkedContainerIds: head.linkedContainerIds,\n };\n}\n\n/**\n * Persist untrusted candidates before advancing listing watermarks. Each pass\n * checks a bounded batch; unavailable heads back off independently while verified\n * siblings and tombstones still settle. Acknowledgement follows local apply so\n * a crash cannot lose a candidate behind an already advanced listing watermark.\n */\nexport function createDiscoveredDocumentVerifier(\n organizationId: string | undefined,\n loadHead: DocumentHeadLinkSetLoader,\n loadLocalEpoch: LocalDocumentAccessEpochLoader,\n store: DocumentDiscoveryEvidenceRepository,\n onPendingDiscovery?: ((delayMs: number) => void) | undefined,\n): DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"] {\n return async (inputs, containerIds, generation, tombstones = []) => {\n const isCurrent = () => store.isCurrent(generation);\n const lanes = new Set(containerIds);\n const removed = tombstones.filter((row) => lanes.has(row.containerId));\n if (!(await store.stage(inputs, generation, removed)))\n return { inputs: [], isCurrent, commit: async () => true };\n const candidates = groupPendingDocumentDiscoveries(\n await store.pending(containerIds, HEAD_LINK_SET_LOADS_PER_RUN),\n );\n const verified = new Map<string, DiscoveredDocumentInput>();\n const settled: DiscoveredDocumentCandidate[] = [];\n let next = 0;\n const worker = async () => {\n while (next < candidates.length) {\n const group = candidates[next++];\n if (!group) break;\n const { input, rows } = group;\n const result = await verifyInput(\n input,\n loadHead,\n loadLocalEpoch,\n store,\n generation,\n organizationId,\n );\n if (result === \"unavailable\") {\n await Promise.all(rows.map((row) => store.defer(row, generation)));\n continue;\n }\n if (result) verified.set(result.documentId, result);\n settled.push(...rows);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, candidates.length) },\n worker,\n ),\n );\n return {\n inputs: [...verified.values()],\n isCurrent,\n commit: async () => {\n await store.acknowledge(settled, generation);\n const retryDelay = await store.retryDelay(containerIds);\n if (retryDelay !== null) onPendingDiscovery?.(retryDelay);\n return retryDelay === null;\n },\n };\n };\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
3
3
|
import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
4
|
-
import {
|
|
4
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
5
5
|
import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
|
|
6
6
|
import { GroupMetadataUnreadableError } from "../groupMetadata/groupMetadataAccess.js";
|
|
7
7
|
import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
|
|
@@ -39,7 +39,11 @@ export async function hydrateCurrentOrganizationGroupNames(input) {
|
|
|
39
39
|
policies: [authority.directory.policy, authority.admins.policy],
|
|
40
40
|
stillCurrent,
|
|
41
41
|
});
|
|
42
|
-
await saveOrganizationGroupDisplayNames({
|
|
42
|
+
await new OrganizationReadModelRepository(input.execSql).saveOrganizationGroupDisplayNames({
|
|
43
|
+
organizationId: input.organizationId,
|
|
44
|
+
names,
|
|
45
|
+
stillCurrent,
|
|
46
|
+
});
|
|
43
47
|
assertProjectionVerificationCurrent(stillCurrent);
|
|
44
48
|
const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));
|
|
45
49
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"currentOrganizationGroupNames.js","sourceRoot":"","sources":["currentOrganizationGroupNames.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAEL,0BAA0B,GAC3B,MAAM,2CAA2C,CAAC;AAcnD,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAAY;IAEZ,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG;QAChB,GAAG,KAAK;QACR,iBAAiB,EACf,KAAK,CAAC,uBAAuB,EAAE,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,iBAAiB;KACxE,CAAC;IACF,MAAM,KAAK,GAA2D,EAAE,CAAC;IACzE,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,MAAM,SAAS,GAAsB,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;IAC9D,KAAK,MAAM,KAAK,IAAI,KAAK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,YAAY,CAAC,SAAS,EAAE;YAC7D,QAAQ,EAAE,OAAO,CAAC,YAAY,CAAC,WAAW;YAC1C,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,wBAAwB;YACnC,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CACF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport type { OrganizationDirectoryAndGroups } from \"../readModel\";\n\ntype Input = Parameters<typeof loadCurrentOrganizationAuthority>[0] & {\n readonly directory: OrganizationDirectoryAndGroups;\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly createCurrentNameReader?:\n | ((\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>,\n ) => GroupPolicyNameReader)\n | undefined;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n};\n\n/** Names consume verified current artifacts; paged recovery retains their separate evidence. */\nexport async function hydrateCurrentOrganizationGroupNames(\n input: Input,\n): Promise<OrganizationDirectoryAndGroups> {\n const authority = await loadCurrentOrganizationAuthority(input);\n const nameInput = {\n ...input,\n readEncryptedName:\n input.createCurrentNameReader?.(authority) ?? input.readEncryptedName,\n };\n const names: { groupId: string; name: string; stateHash: string }[] = [];\n const unreadable = new Set<string>();\n const lifetimes: (() => boolean)[] = [authority.stillCurrent];\n for (const group of input.directory.groups) {\n const head = authority.descriptor.groupHeads.find(\n (head) => head.principalId === group.groupId,\n );\n if (!head || head.stateHash !== group.currentState?.stateHash)\n throw new Error(\"Group listing does not match the signed directory\");\n const verified = await authority.readGroup(group.groupId);\n lifetimes.push(verified.stillCurrent);\n assertGroupMetadataBinding(verified.current, authority.descriptor);\n const name = await readCurrentGroupName(nameInput, verified.current);\n if (name === null) unreadable.add(group.groupId);\n else\n names.push({ groupId: group.groupId, name, stateHash: head.stateHash });\n }\n const stillCurrent = () =>\n input.stillCurrent() && lifetimes.every((current) => current());\n assertProjectionVerificationCurrent(stillCurrent);\n // Match the authority admission performed by the full-bundle path. Group\n // name reads alone do not move group checkpoints.\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent,\n });\n await new OrganizationReadModelRepository(\n input.execSql,\n ).saveOrganizationGroupDisplayNames({\n organizationId: input.organizationId,\n names,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const byId = new Map(names.map((entry) => [entry.groupId, entry.name]));\n return {\n ...input.directory,\n groups: input.directory.groups.map((group) => ({\n ...group,\n name: byId.get(group.groupId) ?? \"\",\n nameUnreadable: unreadable.has(group.groupId),\n })),\n };\n}\n\nasync function readCurrentGroupName(\n input: Input,\n current: Parameters<GroupPolicyNameReader>[0],\n) {\n try {\n return await readGroupPolicyPayloadName(current, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: current.currentState.stateHash },\n objectId: current.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export { loadAppliedOrganizationReadModelCursor } from "../../data/persistence/organizations/organizationReadModelCursorPersistence.js";
|
|
2
1
|
export { type OrganizationReadModelInvalidationListener, subscribeOrganizationReadModelInvalidation, } from "../../data/persistence/organizations/organizationReadModelInvalidation.js";
|
|
3
2
|
export { PendingPrincipalMutationError } from "../../data/persistence/principalMutationJournalPersistence.js";
|
|
4
3
|
export type { AuthoredPrincipalMutation, PrincipalMutationJournalScope, } from "../../data/principals/principalMutationJournal.js";
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export { loadAppliedOrganizationReadModelCursor } from "../../data/persistence/organizations/organizationReadModelCursorPersistence.js";
|
|
2
1
|
export { subscribeOrganizationReadModelInvalidation, } from "../../data/persistence/organizations/organizationReadModelInvalidation.js";
|
|
3
2
|
export { PendingPrincipalMutationError } from "../../data/persistence/principalMutationJournalPersistence.js";
|
|
4
3
|
export { UnreadablePrincipalMutationError } from "../../data/principals/principalMutationJournalRecord.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0CAA0C,GAC3C,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAK3G,OAAO,EAAE,gCAAgC,EAAE,MAAM,sDAAsD,CAAC;AACxG,OAAO,EACL,wBAAwB,EACxB,gBAAgB,EAChB,8BAA8B,EAC9B,mCAAmC,EACnC,oBAAoB,EACpB,2BAA2B,EAC3B,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,yBAAyB,EAOzB,8BAA8B,EAG9B,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,gCAAgC,EAAE,MAAM,4BAA4B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ACpC,oCAAoC,EACpC,uCAAuC,EACvC,kCAAkC,EAClC,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EAEjC,uCAAuC,GACxC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,EAC/B,sCAAsC,EACtC,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC","sourcesContent":["export {\n type OrganizationReadModelInvalidationListener,\n subscribeOrganizationReadModelInvalidation,\n} from \"../../data/persistence/organizations/organizationReadModelInvalidation\";\nexport { PendingPrincipalMutationError } from \"../../data/persistence/principalMutationJournalPersistence\";\nexport type {\n AuthoredPrincipalMutation,\n PrincipalMutationJournalScope,\n} from \"../../data/principals/principalMutationJournal\";\nexport { UnreadablePrincipalMutationError } from \"../../data/principals/principalMutationJournalRecord\";\nexport {\n cancelStripeSubscription,\n changeStripePlan,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createStripeCheckout,\n createStripeCheckoutSession,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n type OrganizationBilling,\n type OrganizationBillingHistory,\n type OrganizationBillingHistoryEntry,\n type OrganizationBillingManagementUrl,\n type OrganizationBillingView,\n type OrganizationNativePurchaseEligibility,\n resolveOrganizationBillingView,\n type StripeCheckoutIntent,\n type StripeCheckoutOptions,\n startOrganizationTrial,\n} from \"./billing\";\nexport { revokeOrganizationContainerGrant } from \"./containerGrantRevocation\";\nexport { GroupMembershipNameMismatchError } from \"./groupNames/groupMembershipName\";\nexport {\n GroupShareNameMismatchError,\n shareRemoteContainerWithGroup,\n} from \"./groupShare\";\nexport { deleteOrganizationGroup } from \"./groups/deleteOrganizationGroup\";\nexport {\n type OrganizationLeaveRequestResult,\n setOrganizationLeaveRequested,\n} from \"./memberships/leaveRequest\";\nexport {\n withVerifiedDirectoryUser,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"./memberships/leaveRequestVerification\";\nexport {\n forgetPausedOrganizationContent,\n type OrganizationContentHost,\n type OrganizationMembership,\n type OrganizationMembershipApi,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationSyncPaused,\n} from \"./memberships/organizationMemberships\";\nexport {\n buildOrganizationProfileDocumentPatch,\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n getOrganizationProfileDocumentLocalId,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n readOrganizationProfileName,\n} from \"./organizationProfile\";\nexport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n readJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalManagement\";\nexport {\n type PrincipalMutationJournalContext,\n PrincipalMutationOutcomeUnknownError,\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"./principalMutations/principalMutationJournalSession\";\nexport type { PrincipalMutationResponse } from \"./principalMutations/principalOperationReceipt\";\nexport {\n type AcknowledgedPrincipalCurrentInput,\n type AcknowledgedPrincipalCurrentRetirement,\n retainAcknowledgedPrincipalCurrents,\n} from \"./principalMutations/retainAcknowledgedPrincipalCurrents\";\nexport {\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n createOrganizationGroup,\n removeOrganizationGroupUser,\n rotateOrganizationGroupForAccessSetShrink,\n} from \"./principalPolicy\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n} from \"./provisioning/createOrganization\";\nexport {\n buildOrganizationGroupPolicyHistory,\n type OrganizationContainerGrant,\n type OrganizationContainerGrants,\n type OrganizationDirectory,\n type OrganizationDirectoryAndGroups,\n type OrganizationDirectoryUser,\n type OrganizationGroupContainer,\n type OrganizationGroupContainers,\n type OrganizationGroupDetails,\n type OrganizationGroupMember,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationGroupPolicyHistoryEntry,\n type OrganizationGroupSummary,\n type OrganizationPolicyGrantChange,\n type OrganizationPolicyGroupChange,\n type OrganizationPolicyHistory,\n type OrganizationPolicyHistoryEntry,\n type OrganizationPrincipalMemberChange,\n type OrganizationPrincipalMemberChangeType,\n type OrganizationPrincipalPolicyHistory,\n type OrganizationPrincipalPolicyHistoryEntry,\n type OrganizationProfile,\n type OrganizationUserDetail,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./readModel\";\nexport {\n loadLocalOrganizationDataUsage,\n type OrganizationDataUsage,\n type ReconcileOrganizationDataUsageInput,\n reconcileOrganizationDataUsage,\n} from \"./readModel/dataUsageReadModel\";\nexport {\n measureOrganizationDeviceDataUsage,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n type OrganizationDeviceDataUsage,\n type OrganizationDeviceDocumentUsageCategoryBreakdown,\n type OrganizationDocumentUsageCategory,\n} from \"./readModel/deviceDataUsage\";\nexport {\n type LocalOrganizationSummary,\n listLocalOrganizations,\n} from \"./readModel/listLocalOrganizations\";\nexport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupPolicyHistory,\n loadLocalOrganizationPolicyHistory,\n loadLocalOrganizationPolicyReference,\n loadLocalOrganizationUserDetail,\n} from \"./readModel/localReadModelDetails\";\nexport {\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupMembers,\n type ReconcileOrganizationDirectoryAndGroupsInput,\n reconcileOrganizationDirectoryAndGroups,\n} from \"./readModel/readModelProjection\";\nexport {\n buildRosterProfileDocumentPatch,\n createInitializedRosterProfileDocument,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"./rosterProfileContainer\";\n"]}
|
|
@@ -1,16 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { recordOrganizationPresentationDenials } from "../../../data/persistence/organizations/organizationPresentationDenialPersistence.js";
|
|
1
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
3
2
|
import { denyOrganizationPresentationAccess, runOrganizationPresentationMutation, } from "../readModel/organizationPresentationAccessState.js";
|
|
4
3
|
export async function denyPolicyHistoryAccess(input) {
|
|
5
4
|
denyOrganizationPresentationAccess(input, ["readModel", "usage"]);
|
|
5
|
+
const repository = new OrganizationReadModelRepository(input.execSql);
|
|
6
6
|
try {
|
|
7
|
-
await runOrganizationPresentationMutation(input.execSql, () => recordOrganizationPresentationDenials(input, [
|
|
7
|
+
await runOrganizationPresentationMutation(input.execSql, () => repository.recordOrganizationPresentationDenials(input, [
|
|
8
|
+
"readModel",
|
|
9
|
+
"usage",
|
|
10
|
+
]));
|
|
8
11
|
}
|
|
9
12
|
catch (error) {
|
|
10
13
|
input.logError("Failed to record denied organization policy history", error);
|
|
11
14
|
}
|
|
12
15
|
try {
|
|
13
|
-
await runOrganizationPresentationMutation(input.execSql, () => purgeOrganizationAccessProjection(input));
|
|
16
|
+
await runOrganizationPresentationMutation(input.execSql, () => repository.purgeOrganizationAccessProjection(input));
|
|
14
17
|
}
|
|
15
18
|
catch (error) {
|
|
16
19
|
input.logError("Failed to purge denied organization policy history", error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policyHistoryAccessDenial.js","sourceRoot":"","sources":["policyHistoryAccessDenial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"policyHistoryAccessDenial.js","sourceRoot":"","sources":["policyHistoryAccessDenial.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAE1H,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,kDAAkD,CAAC;AAE1D,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAK7C;IACC,kCAAkC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;IAClE,MAAM,UAAU,GAAG,IAAI,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACtE,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,UAAU,CAAC,qCAAqC,CAAC,KAAK,EAAE;YACtD,WAAW;YACX,OAAO;SACR,CAAC,CACH,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CACZ,qDAAqD,EACrD,KAAK,CACN,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,mCAAmC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5D,UAAU,CAAC,iCAAiC,CAAC,KAAK,CAAC,CACpD,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,QAAQ,CAAC,oDAAoD,EAAE,KAAK,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n denyOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n} from \"../readModel/organizationPresentationAccessState\";\n\nexport async function denyPolicyHistoryAccess(input: {\n execSql: ExecSql;\n organizationId: string;\n requesterUserId: string;\n logError: (message: string | Error, cause?: unknown) => void;\n}): Promise<void> {\n denyOrganizationPresentationAccess(input, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(input, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError(\n \"Failed to record denied organization policy history\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection(input),\n );\n } catch (error) {\n input.logError(\"Failed to purge denied organization policy history\", error);\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrganizationDataUsageRepository } from "../../../data/persistence/organizations/organizationDataUsagePersistence.js";
|
|
2
|
-
import {
|
|
2
|
+
import { OrganizationReadModelRepository } from "../../../data/persistence/organizations/organizationReadModelRepository.js";
|
|
3
3
|
import { captureOrganizationPresentationAccessAttempt, denyOrganizationPresentationAccess, isOrganizationPresentationAccessAttemptCurrent, isOrganizationPresentationAccessReadable, restoreOrganizationPresentationAccess, runOrganizationPresentationMutation, runOrganizationPresentationRead, } from "./organizationPresentationAccessState.js";
|
|
4
4
|
import { isOrganizationPresentationAccessDeniedFailure } from "./organizationPresentationFailures.js";
|
|
5
5
|
export async function loadLocalOrganizationDataUsage(input) {
|
|
@@ -21,7 +21,7 @@ export async function reconcileOrganizationDataUsage(input) {
|
|
|
21
21
|
// Durable marker first: a failed purge plus a restart must not serve
|
|
22
22
|
// the revoked usage projection.
|
|
23
23
|
try {
|
|
24
|
-
await runOrganizationPresentationMutation(input.execSql, () => recordOrganizationPresentationDenials(input, ["usage"]));
|
|
24
|
+
await runOrganizationPresentationMutation(input.execSql, () => new OrganizationReadModelRepository(input.execSql).recordOrganizationPresentationDenials(input, ["usage"]));
|
|
25
25
|
}
|
|
26
26
|
catch (error) {
|
|
27
27
|
input.logError?.("Failed to record denied organization data usage", error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dataUsageReadModel.js","sourceRoot":"","sources":["dataUsageReadModel.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,+BAA+B,EAAE,MAAM,0EAA0E,CAAC;AAC3H,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C,OAAO,EAAE,KAAK,IAAI,EAAE;QACnE,IAAI,CAAC,8CAA8C,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;YACpE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,IAAI,CAAC;YACH,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;gBACpC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,QAAQ,EAAE,MAAM,CAAC,IAAI;aACtB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,KAAK,CAAC,QAAQ,EAAE,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;YACrE,OAAO,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;QACxD,CAAC;QACD,OAAO,qCAAqC,CAAC,KAAK,EAAE,OAAO,CAAC;YAC1D,CAAC,CAAC,MAAM,CAAC,IAAI;YACb,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport { OrganizationDataUsageRepository } from \"../../../data/persistence/organizations/organizationDataUsagePersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nexport type OrganizationDataUsage = OrganizationDataUsageResponse;\n\ninterface OrganizationDataUsageApi {\n getOrganizationDataUsageResult(\n organizationId: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationDataUsageResponse>>;\n}\n\ninterface OrganizationDataUsageProjectionInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly requesterUserId: string;\n}\n\nexport interface ReconcileOrganizationDataUsageInput\n extends OrganizationDataUsageProjectionInput {\n readonly apiClient: OrganizationDataUsageApi;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n}\n\nexport async function loadLocalOrganizationDataUsage(\n input: OrganizationDataUsageProjectionInput,\n): Promise<OrganizationDataUsage | null> {\n return runOrganizationPresentationRead(input, \"usage\", () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).loadOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n}\n\nfunction retainedIfUsageReadable<T>(\n input: OrganizationDataUsageProjectionInput,\n attempt: OrganizationPresentationAccessAttempt,\n value: T,\n): T | null {\n return isOrganizationPresentationAccessAttemptCurrent(input, attempt) &&\n isOrganizationPresentationAccessReadable(input, \"usage\")\n ? value\n : null;\n}\n\nexport async function reconcileOrganizationDataUsage(\n input: ReconcileOrganizationDataUsageInput,\n): Promise<OrganizationDataUsage | null> {\n const attempt = captureOrganizationPresentationAccessAttempt(input, \"usage\");\n const local = await loadLocalOrganizationDataUsage(input);\n const result = await input.apiClient.getOrganizationDataUsageResult(\n input.organizationId,\n { reportErrors: false },\n );\n if (!result.ok) {\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n denyOrganizationPresentationAccess(input, [\"usage\"]);\n // Durable marker first: a failed purge plus a restart must not serve\n // the revoked usage projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).recordOrganizationPresentationDenials(input, [\"usage\"]),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to record denied organization data usage\",\n error,\n );\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n new OrganizationDataUsageRepository(\n input.execSql,\n ).purgeOrganizationDataUsageProjection(\n input.organizationId,\n input.requesterUserId,\n ),\n );\n } catch (error) {\n input.logError?.(\n \"Failed to purge denied organization data usage\",\n error,\n );\n }\n return null;\n }\n\n result.report();\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n if (result.data.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization data-usage response scope does not match ${input.organizationId}`,\n );\n return retainedIfUsageReadable(input, attempt, local);\n }\n\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (!isOrganizationPresentationAccessAttemptCurrent(input, attempt)) {\n return null;\n }\n try {\n await new OrganizationDataUsageRepository(\n input.execSql,\n ).saveOrganizationDataUsageProjection({\n requesterUserId: input.requesterUserId,\n response: result.data,\n });\n } catch (error) {\n input.logError?.(\"Failed to persist organization data usage\", error);\n return retainedIfUsageReadable(input, attempt, local);\n }\n return restoreOrganizationPresentationAccess(input, attempt)\n ? result.data\n : null;\n });\n}\n"]}
|