-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsharing-service.ts
More file actions
289 lines (261 loc) · 9.71 KB
/
Copy pathsharing-service.ts
File metadata and controls
289 lines (261 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type {
ISharingService,
RecordShare,
GrantShareInput,
SharingExecutionContext,
ShareAccessLevel,
} from '@objectstack/spec/contracts';
/**
* Shape of the data engine the service actually needs. Kept narrow so
* unit tests can pass an in-memory fake without depending on the full
* ObjectQL engine class.
*/
export interface SharingEngine {
find(object: string, options?: any): Promise<any[]>;
findOne?(object: string, options?: any): Promise<any>;
insert(object: string, data: any, options?: any): Promise<any>;
update(object: string, idOrData: any, dataOrOptions?: any, options?: any): Promise<any>;
delete(object: string, options?: any): Promise<any>;
getSchema?(object: string): any | undefined;
}
/**
* Random share id. Keeps the plugin self-contained (no `crypto.randomUUID`
* dependency in environments that don't expose it on `globalThis`).
*/
function makeShareId(): string {
const g: any = globalThis as any;
if (g.crypto?.randomUUID) return `shr_${g.crypto.randomUUID()}`;
return `shr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
/** System-elevated context for the plugin's own queries / mutations. */
const SYSTEM_CTX = { isSystem: true, roles: [], permissions: [] } as const;
/**
* Owner field convention. Hard-coded to `owner_id` for MVP — the
* sharing model in Salesforce / ServiceNow / Dynamics all assume a
* single owner field, and customising it is a follow-up. Objects
* without `owner_id` are treated as "unowned" and read filters are
* suppressed (they fall back to OWD-public behaviour).
*/
const OWNER_FIELD = 'owner_id';
/**
* Effective sharing model — collapses the authorable OWD vocabulary onto the
* three behaviours this service enforces (ADR-0056 D1):
* - `private` → owner-only read + write
* - `public_read` / legacy `read` → everyone reads, owner writes
* - everything else → public (no record-level filter)
*
* "Everything else" covers the canonical `public_read_write`, the legacy
* `read_write` / `full` aliases, `controlled_by_parent` (scoped separately by
* the security plugin), and objects that declare no `sharingModel` at all — so
* existing behaviour is preserved until an admin opts an object in.
*/
function effectiveSharingModel(schema: any): 'private' | 'read' | 'public' {
const m = schema?.sharingModel ?? schema?.security?.sharingModel;
if (m === 'private') return 'private';
if (m === 'read' || m === 'public_read') return 'read';
return 'public';
}
function hasOwnerField(schema: any): boolean {
return Boolean(schema?.fields && OWNER_FIELD in schema.fields);
}
export interface SharingServiceOptions {
engine: SharingEngine;
/** Object names that bypass sharing — typically platform internals. */
bypassObjects?: string[];
}
/**
* Default `ISharingService` implementation.
*
* Stores every grant in `sys_record_share`. The plugin layer registers
* an engine middleware that calls `buildReadFilter` / `canEdit` so that
* neither this class nor its callers need to know about middleware
* plumbing.
*/
export class SharingService implements ISharingService {
private readonly engine: SharingEngine;
private readonly bypassObjects: Set<string>;
constructor(options: SharingServiceOptions) {
this.engine = options.engine;
this.bypassObjects = new Set([
'sys_record_share',
'sys_user',
'sys_organization',
'sys_member',
'sys_role',
'sys_permission_set',
'sys_user_permission_set',
'sys_role_permission_set',
...(options.bypassObjects ?? []),
]);
}
/**
* Build a `FilterCondition` restricting `find` to records the caller
* may see. Returns `null` when no filter should be applied.
*/
async buildReadFilter(
object: string,
context: SharingExecutionContext,
): Promise<unknown | null> {
if (this.shouldBypass(object, context)) return null;
const schema = this.engine.getSchema?.(object);
if (!schema) return null;
if (effectiveSharingModel(schema) !== 'private') return null;
if (!hasOwnerField(schema)) return null;
if (!context.userId) {
// Authenticated context with no user id is a degenerate case
// (e.g. anonymous API key). Restrict to nothing rather than
// accidentally leaking owner-only data.
return { id: '__deny_all__' };
}
const grants = await this.engine.find('sys_record_share', {
filter: {
object_name: object,
recipient_type: 'user',
recipient_id: context.userId,
},
fields: ['record_id', 'access_level'],
limit: 5000,
context: SYSTEM_CTX,
});
const grantedIds: string[] = Array.isArray(grants)
? grants.map((g: any) => String(g.record_id)).filter(Boolean)
: [];
if (grantedIds.length === 0) {
return { [OWNER_FIELD]: context.userId };
}
return {
$or: [
{ [OWNER_FIELD]: context.userId },
{ id: { $in: grantedIds } },
],
};
}
/**
* Return `true` if the caller may edit `(object, recordId)`. Always
* `true` for system context, public objects, and objects without an
* owner field.
*/
async canEdit(
object: string,
recordId: string,
context: SharingExecutionContext,
): Promise<boolean> {
if (this.shouldBypass(object, context)) return true;
const schema = this.engine.getSchema?.(object);
if (!schema) return true;
const model = effectiveSharingModel(schema);
if (model === 'public') return true;
if (!hasOwnerField(schema)) return true;
if (!context.userId) return false;
// 1) Ownership — fast path.
const own = await this.engine.find(object, {
filter: { id: recordId },
fields: ['id', OWNER_FIELD],
limit: 1,
context: SYSTEM_CTX,
});
const owner = Array.isArray(own) && own[0] ? (own[0] as any)[OWNER_FIELD] : undefined;
if (owner && String(owner) === String(context.userId)) return true;
// 2) Explicit edit / full share.
const editGrants = await this.engine.find('sys_record_share', {
filter: {
object_name: object,
record_id: recordId,
recipient_type: 'user',
recipient_id: context.userId,
access_level: { $in: ['edit', 'full'] },
},
fields: ['id'],
limit: 1,
context: SYSTEM_CTX,
});
return Array.isArray(editGrants) && editGrants.length > 0;
}
/**
* Upsert a share row. Returning the existing row when an identical
* grant already exists keeps the REST endpoint idempotent.
*/
async grant(
input: GrantShareInput,
context: SharingExecutionContext,
): Promise<RecordShare> {
if (!input.object) throw new Error('VALIDATION_FAILED: object is required');
if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required');
if (!input.recipientId) throw new Error('VALIDATION_FAILED: recipientId is required');
const recipientType = input.recipientType ?? 'user';
const accessLevel: ShareAccessLevel = input.accessLevel ?? 'read';
const source = input.source ?? 'manual';
// Upsert: if a row with same (object, record, recipient) exists,
// update its access level / reason; otherwise insert a new one.
const existing = await this.engine.find('sys_record_share', {
filter: {
object_name: input.object,
record_id: input.recordId,
recipient_type: recipientType,
recipient_id: input.recipientId,
},
limit: 1,
context: SYSTEM_CTX,
});
const now = new Date().toISOString();
if (Array.isArray(existing) && existing[0]) {
const row: any = existing[0];
const patch: any = {
id: row.id,
access_level: accessLevel,
source,
source_id: input.sourceId ?? row.source_id ?? null,
reason: input.reason ?? row.reason ?? null,
updated_at: now,
};
await this.engine.update('sys_record_share', patch, { context: SYSTEM_CTX });
return { ...row, ...patch } as RecordShare;
}
const id = makeShareId();
const row: any = {
id,
object_name: input.object,
record_id: input.recordId,
recipient_type: recipientType,
recipient_id: input.recipientId,
access_level: accessLevel,
source,
source_id: input.sourceId ?? null,
granted_by: context.userId ?? null,
reason: input.reason ?? null,
created_at: now,
updated_at: now,
};
await this.engine.insert('sys_record_share', row, { context: SYSTEM_CTX });
return row as RecordShare;
}
/** Delete a share row by id. No-op when not found. */
async revoke(shareId: string, _context: SharingExecutionContext): Promise<void> {
if (!shareId) throw new Error('VALIDATION_FAILED: shareId is required');
await this.engine.delete('sys_record_share', {
where: { id: shareId },
context: SYSTEM_CTX,
});
}
/** List share rows for `(object, recordId)`. */
async listShares(
object: string,
recordId: string,
_context: SharingExecutionContext,
): Promise<RecordShare[]> {
const rows = await this.engine.find('sys_record_share', {
filter: { object_name: object, record_id: recordId },
orderBy: [{ field: 'created_at', order: 'desc' }],
limit: 500,
context: SYSTEM_CTX,
});
return Array.isArray(rows) ? (rows as RecordShare[]) : [];
}
// ── helpers ──────────────────────────────────────────────────────
private shouldBypass(object: string, context: SharingExecutionContext): boolean {
if (context?.isSystem) return true;
if (this.bypassObjects.has(object)) return true;
return false;
}
}