| title | services.sharing — the record share API |
|---|---|
| navTitle | services.sharing |
| description | Check and manage record-level sharing with services.sharing — read filters, the tri-state checkEdit and checkDelete verdicts and their canEdit and canDelete projections, the optional set form, and granting or revoking record shares. |
- Stability:
stable - Canonical source:
packages/spec/src/contracts/sharing-service.ts - Registry slot:
sharing— resolve withctx.getService('sharing').
services.sharing.buildReadFilter(object: string, context: ExecutionContext): Promise<unknown | null>
services.sharing.checkEdit(object: string, recordId: string, context: ExecutionContext): Promise<SharingWriteVerdict>
services.sharing.checkDelete(object: string, recordId: string, context: ExecutionContext): Promise<SharingWriteVerdict>
services.sharing.canEdit(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.canDelete(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.checkEditMany?(object: string, recordIds: readonly string[], context: ExecutionContext): Promise<SharingWriteVerdict[]>
services.sharing.checkDeleteMany?(object: string, recordIds: readonly string[], context: ExecutionContext): Promise<SharingWriteVerdict[]>
services.sharing.canManageShares(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.grant(input: GrantShareInput, context: ExecutionContext): Promise<RecordShare>
services.sharing.revoke(shareId: string, context: ExecutionContext, scope?: { object: string; recordId: string }): Promise<void>
services.sharing.listShares(object: string, recordId: string, context: ExecutionContext): Promise<RecordShare[]>Every method above adjudicates access, so each takes the complete
resolveAuthzContext envelope (ExecutionContext) — not a per-site subset
(#6523, applying the #6206 ruling). The six-field SharingExecutionContext
these signatures used to name was retired in #7218; pass the whole context you
were handed, unchanged.
Each write gate has a primary tri-state form, checkEdit (update) and
checkDelete (delete), which answers a SharingWriteVerdict:
allow— a positive basis to permit: ownership (widened by write DEPTH), themodifyAllRecordssuper-user bypass or a system context, and, forcheckEditonly, anedit-level share or a record sitting in a queue the caller belongs to.abstain— record sharing does not enforce on this row at all: apublicobject, an object with no owner field, a bypass-listed platform internal, or an object with no resolvable schema. The decision belongs to whatever else guards the row.checkDeleteabstains on the rowscheckEditabstains on except one class: on an object that declarespublic_read_writeand has an owner field, delete follows the record's owner, socheckDeleteanswersallowordenythere as it does underpublic_read.deny— refused: a sharing-enforced row where the caller has none of the bases above, a principal-less context, or a lookup that failed. A failure is alwaysdeny, neverabstain.
canEdit / canDelete are the two-state projection of those verdicts:
true for anything that is not deny, so abstain and allow both read as
true. That is right for a caller that only adds this gate to what already
guards the row, and wrong for one that would let the answer override another
authority's floor: such a caller must read checkEdit / checkDelete, so that
"sharing has no opinion" is never taken as permission.
checkEditMany / checkDeleteMany are the optional set form of the
tri-state verdicts: answer[i] is the verdict checkEdit / checkDelete
answers for recordIds[i] under the same context, with the same bases and the
same verb boundary, and the answer is exactly as long as recordIds. Only the
cost differs: the number of store reads grows with the number of chunks, not the
number of records. The bundled SharingService (@objectstack/plugin-sharing)
implements both, reading 1,000 ids per chunk. They are optional: a caller
feature-detects them (typeof sharing.checkEditMany === 'function') and, where
a service does not implement them, asks checkEdit / checkDelete once per
record, with the same answers. The platform's predicate update and delete do
exactly that. A chunk whose lookup fails answers deny for each of its records.
A custom ISharingService that does not add the set form keeps working.
grant / revoke / listShares are management operations, enforced in the
service for every non-system caller: the caller must hold canManageShares on
the record — its owner, a holder of Modify All Data, a hierarchy
manager whose effective write DEPTH (unit / unit_and_below /
own_and_reports) covers the record's owner (via the enterprise
hierarchy-scope-resolver), or system context. A deployment without
@objectstack/plugin-security fails closed to owner-only; without the
enterprise resolver the DEPTH path is inert and authority stays owner +
Modify-All. Pass { isSystem: true } only from platform-internal machinery.
A share a non-system caller grants is always a manual share: grant refuses
a source other than 'manual', and any sourceId, with VALIDATION_FAILED
(400), because only the platform's own sharing-rule, team and system paths write
a share of another source.
A share widens which rows a principal reaches, never which verbs they may
use. canEdit (the update gate) accepts an edit-level share; canDelete
(the delete gate) does not — delete is ownership (widened by write
DEPTH) or the modifyAllRecords super-user bypass only. Delete is not a share
level and never will be; a future per-record delete grant would be a capability
mask AND-ed with object CRUD, not a fourth access_level.
buildReadFilter:nullmeans unrestricted read; otherwise returns an engine filtercheckEdit/checkDelete: aSharingWriteVerdict('allow' | 'abstain' | 'deny'); a failed lookup answersdenyrather than throwingcheckEditMany/checkDeleteMany(optional): oneSharingWriteVerdictper id, in the order ofrecordIdscanEdit/canDelete/canManageShares: boolean decisions (they returnfalserather than throwing);canEdit/canDeletearetruefor every verdict that is notdenygrant/listShares: normalizedRecordSharerows
FORBIDDEN(403) — a write denied by thecanEditgate. Thrown by the sharing engine middleware;canEdititself returnsfalserather than throwing.VALIDATION_FAILED(400) —grant/revokecalled without a required field (object,recordId,recipientId, orshareId), orgrantwith a non-userrecipientType(onlyuserrows are enforced by the gates). The refusal names the sharing-rule recipient that delivers each declared value:group→team(a rule spells itteamsince the ADR-0090 D3 rename),position→position,unit_and_subordinates→unit_and_subordinates. A non-systemgrantis also refused when itsuserrecipient names no user the gates could ever match: on a deployment walled by organization (isolated/group) with the record's organization known, the recipient must be a member of that organization, and a user of another organization gets the same answer as an id that does not exist, so the door tells no caller who exists in another tenant; onsingleit must be an existingsys_user. Under a wall where the grant's organization does not resolve, the recipient is not judged: the engine refuses that insert for every recipient alike (ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED, 500).defineRulerefuses a non-systemuserrecipient the same way, in the rule's organization, when the rule is new or its recipient changes. The rule's organization is the caller's or, for a platform operator with no active organization updating a stored rule, the stored rule's own (the engine's organization rule refuses only inserts, so that update is judged here); a new rule written with no organization under a wall is not judged, and the engine refuses its insert. Asys_sharing_rulewrite through the/datadoor (Setup's form) gets the same refusal and sentence, judged in the organization the write leaves the rule in: anorganization_idthe write supplies, else the stored rule's, else the caller's active organization; a write that keeps the stored recipient is not judged.PERMISSION_DENIED(403) — the caller does not holdcanManageShareson the record (ADR-0111 D1). On the sharing-rule surface (ISharingRuleService, declared in the same canonical source —listRules/getRule/defineRule/deleteRule/evaluateRule) the same code carries a second condition: the caller holdsmanage_sharingbut their session resolves no active organization, and an org-scoped capability with no organization has no tenant whose rules it authorizes. System contexts and platform operators (manage_platform_settings, or theplatform_adminposition) are unaffected — see Rule administration.NOT_FOUND(404) — the record is missing or not visible to the caller (indistinguishable by design), or arevokeshare id does not exist / does not belong to thescoperecord.CONFLICT(409) —revokeon a rule-materialised share (source != 'manual'); the next rule reconciliation would silently re-grant it. Deactivate or edit the sharing rule instead.SHARING_NOT_ENABLED(422) —granton an object the sharing gates never consult for the recipient (a public sharing model, unless the recipient is anexternalmember of the record's organization, whose owner-only floor does consult it; noowner_idfield; a bypass object,controlled_by_parent, or a federated object whoseowner_idis the platform's injected anchor rather than a real remote column — the platform provisions no storage for a federated object, so the gates read that column off a table that has not got it and can never admit; or an object whose share grants cannot count where it is stored — it sits on another datasource thansys_record_share, even a SQL one, or on a driver that does not evaluate the share-grant subquery, today MongoDB, in-memory and OData (ADR-0155 R2); to share its records, store it on the datasource ofsys_record_share, on a driver that evaluates share grants, as the SQL drivers do). On the sharing-rule surface,defineRule(and asys_sharing_rulewrite through the/datadoor) answers the same code when the rule's object is one no gate consults for any recipient: the rule is refused at save instead of saved to share nothing.
With @objectstack/plugin-sharing installed, the gates run inside the engine: its
middleware picks the gate by verb — canEdit before a by-id update, canDelete before a
delete — and throws FORBIDDEN before the hook chain could ask anything. A hook that
re-checks adds nothing, and it cannot ask this service at all: a hook context is built key
by key by the engine (object / event / input / session / provenance / user /
api / transaction / ql) and carries no services key, so
ctx.services?.sharing?.canEdit(…) is undefined there and if (!ok) throw … rejects
every write (#5720). A hook's
own channel is ctx.api — use it for business rules
(examples).
Call canEdit only from code that holds the service — a plugin that resolved it from
the kernel service registry, or a managed runtime's services.sharing binding — for
example to pre-flight an affordance before offering it:
{/* os:check */}
import type { ISharingService } from '@objectstack/spec/contracts';
export async function mayEditContract(
sharing: ISharingService,
recordId: string,
session: { userId?: string; organizationId?: string; positions?: string[] },
): Promise<boolean> {
return sharing.canEdit('contract', recordId, {
userId: session.userId,
// The execution context names the org `tenantId`; a session exposes the
// same value as `organizationId` (the `session.tenantId` alias was removed in
// v16, #3290).
tenantId: session.organizationId,
positions: session.positions,
});
}canEdit returns false rather than throwing, so a caller decides what a denial means —
hiding a button, or raising its own error.