Repository navigation
Expand file tree
/
Copy pathsys-invitation.object.ts
More file actions
472 lines (452 loc) · 21.6 KB
/
Copy pathsys-invitation.object.ts
File metadata and controls
472 lines (452 loc) · 21.6 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { ObjectSchema, Field } from '@objectstack/spec/data';
import { F } from '@objectstack/spec/shared';
import {
BUILTIN_MEMBERSHIP_ROLE_OPTIONS,
INVITATION_ROLE_OPTIONS,
InvitationStatus,
MEMBERSHIP_ROLE_MEMBER,
} from '@objectstack/spec/identity';
import { INVITE_USER_OUTCOME_MESSAGES, RESEND_INVITATION_OUTCOME_MESSAGES } from './invite-outcome-messages.js';
import { MEMBERSHIP_ROLE_PARAM_HELP } from './membership-role-help.js';
/**
* The display label of each invitation status. Keyed by the spec enum, so a
* value the enum gains fails to compile here until it has a label. `rejected`
* reads "Declined": the invitee's action is Decline Invitation.
*/
const INVITATION_STATUS_LABELS: Record<InvitationStatus, string> = {
pending: 'Pending',
accepted: 'Accepted',
rejected: 'Declined',
expired: 'Expired',
canceled: 'Canceled',
};
/**
* sys_invitation — System Invitation Object
*
* Organization invitation tokens for inviting users.
* Backed by better-auth's organization plugin.
*
* @namespace sys
*/
export const SysInvitation = ObjectSchema.create({
name: 'sys_invitation',
label: 'Invitation',
pluralLabel: 'Invitations',
icon: 'mail',
isSystem: true,
managedBy: 'better-auth',
// ADR-0010 §3.7 — managed by better-auth; tenants may not edit schema,
// but may add overlay row-level config. Use `no-overlay` if you need to
// forbid sys_metadata overlays entirely.
protection: {
lock: 'full',
reason: 'Identity table managed by better-auth — see ADR-0010.',
docsUrl: 'https://objectstack.ai/docs/references/shared/protection',
},
description: 'Organization invitations for user onboarding',
// [ADR-0079] The record title is `display_title`, a text formula over the
// columns `titleFormat` named. With no pointer declared, the registry's
// designate-only pass stamped `nameField: 'id'` (the first title-eligible
// field), so a renderer honouring ADR-0079's order (an explicit `nameField`
// wins over `titleFormat`) drew the raw id as the record page's H1. The
// retired `titleFormat` template beside it is gone (refused at save and by
// `os validate`); `identity-display-title.test.ts` holds the formula to the
// text that template drew.
displayNameField: 'display_title',
nameField: 'display_title', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField)
// Title by invitee email rather than organization_id: the latter is null in
// single-org mode (renders "Invitation to null"), and the recipient email is
// the more useful identifier in both modes anyway.
highlightFields: ['email', 'organization_id', 'status'],
// Custom actions — generic CRUD is suppressed (better-auth-managed).
// Mirror the `invite_user` toolbar action from sys_user here so admins
// landing on the Invitations page get an obvious entry point.
actions: [
{
name: 'invite_user',
label: 'Invite User',
// Same wording as the sys_user / sys_member mirrors.
description:
'Invite someone by email address. They join this organization with the chosen role when they accept the invitation.',
icon: 'user-plus',
variant: 'primary',
locations: ['list_toolbar'],
type: 'api',
target: '/api/v1/auth/organization/invite-member',
// Inviting/managing invitations is a multi-org-only flow (the
// endpoint resolves an active org absent in single-org mode). Gate
// the admin-side actions on the multi-org flag (mirrors
// sys_organization.create_organization). The recipient-side
// accept/reject actions below stay record-gated — they are
// unreachable in single-org anyway (no invitation rows exist).
// Hidden while cloud-managed, as on the other three mirrors.
visible: 'features.cloudManaged != true',
requiresFeature: 'organization',
requiresMembershipReach: 'invite_member',
// `{{ result.email }}`: the invitee's address from the invitation row
// invite-member answers (see sys_user's mirror).
successMessage: 'Invitation sent to {{ result.email }}',
// [#27843] The copy per delivery outcome invite-member answers: `sent`,
// or `link_only` when this deployment does not deliver mail. The
// `successMessage` above stays the fallback for an answer without one.
outcomeMessages: { ...INVITE_USER_OUTCOME_MESSAGES },
refreshAfter: true,
params: [
{ field: 'email', required: true },
// [ADR-0105 D8] The role picker offers only what this caller may
// grant: each option's `visibleWhen` is built from the same grant
// table the server's invitation role cap enforces
// (`INVITATION_ROLE_GRANTORS`), so a delegated_admin is offered
// `member` alone. Declared on the param, not inherited from the
// field, so the gate narrows this dialog and no other picker.
{ field: 'role', required: true, options: [...INVITATION_ROLE_OPTIONS], helpText: MEMBERSHIP_ROLE_PARAM_HELP },
],
// ADR-0011 identity-actions note, bucket E: exposed by plain declaration.
ai: {
exposed: true,
description:
'Invite a person by email address to join the current organization with a role (params: email, role). They join when they accept the invitation. Use when the user asks to invite someone who is not a member yet; the role options are only the roles the caller may grant.',
},
},
{
name: 'cancel_invitation',
label: 'Cancel Invitation',
icon: 'x-circle',
variant: 'danger',
mode: 'delete',
locations: ['list_item'],
type: 'api',
target: '/api/v1/auth/organization/cancel-invitation',
recordIdParam: 'invitationId',
requiresFeature: 'organization',
requiresMembershipReach: 'cancel_invitation',
confirmText: 'Cancel this invitation? The recipient will no longer be able to accept it.',
// The dismiss button names what dismissing keeps: beside a "Cancel
// Invitation" confirm button, a bare "Cancel" reads as the same verb.
cancelText: 'Keep invitation',
successMessage: 'Invitation canceled',
refreshAfter: true,
// ADR-0011 identity-actions note, bucket C: exposed, and the
// confirmation is never relaxed.
ai: {
exposed: true,
description:
'Cancel a pending invitation (the record), so its recipient can no longer accept it. Ask the human to confirm before calling.',
requiresConfirmation: true,
},
},
{
name: 'resend_invitation',
label: 'Resend Invitation',
// A confirmation, not a form: the question rides `description` (one
// dialog, see `action-confirm-one-dialog.test.ts`) and both params are
// carried over from the row. invite-member renews a pending invitation
// with its stored role whatever role is sent, and another email would
// invite a different person, so neither is the user's to edit here.
// [#28540] True for both rows Resend is offered on: an unexpired
// invitation is renewed, and an expired one is replaced by a new
// invitation while the old row moves to `expired` (plugin-auth's
// `invitation-expired-supersede.ts`), so one pending row remains.
description:
'Resend the invitation to {{ record.email }}? The expiry date starts over, and an invitation that has already expired is replaced by a new one.',
icon: 'send',
variant: 'secondary',
locations: ['list_item'],
type: 'api',
target: '/api/v1/auth/organization/invite-member',
bodyExtra: { resend: true },
// Hidden while cloud-managed, as the four invite mirrors and
// `copy_invitation_link` are: a resend IS a call to invite-member,
// which a managed environment refuses outright (409, resends
// included — plugin-auth's `auth-manager-before-hook.ts`).
visible: 'features.cloudManaged != true',
requiresFeature: 'organization',
// A resend IS a call to invite-member, so it is reached by the grades
// that reach that endpoint — delegated_admin included.
requiresMembershipReach: 'invite_member',
successMessage: 'Invitation resent',
// [#27843] A resend answers the same delivery `outcome` as an invite.
outcomeMessages: { ...RESEND_INVITATION_OUTCOME_MESSAGES },
refreshAfter: true,
// Both seeded from the row, so every list view that offers this action
// projects `email` and `role` (`invitation-screens-copy.test.ts`).
params: [
{ field: 'email', required: true, defaultFromRow: true, carryOver: true },
{ field: 'role', required: true, defaultFromRow: true, carryOver: true },
],
// ADR-0011 identity-actions note, bucket E: exposed by plain declaration.
ai: {
exposed: true,
description:
'Send a pending invitation (the record) again (params: its email and role, copied from the invitation; the stored role is kept). The expiry date starts over, and an invitation that has already expired is replaced by a new one. Use when the invitee lost the invitation or never received it.',
},
},
{
// [#27843, ruling E on #27797] The pending invitation's accept link, for
// a deployment whose mail is not delivered (invite-member answers
// `outcome: 'link_only'` there): the one way the invitee is reached.
// The handler is plugin-auth's (`invitation-link-action.ts`), registered
// under `target`; it builds the link the invitation mail carries, and
// enforces this action's gates itself, because the link is a bearer
// credential and `visible` is courtesy.
name: 'copy_invitation_link',
label: 'Copy Invite Link',
icon: 'link',
variant: 'secondary',
locations: ['list_item', 'record_header'],
type: 'script',
target: 'copy_invitation_link',
// The gates of `resend_invitation` (the organization capability and the
// grades that reach invite-member), hidden while cloud-managed as the
// invite mirrors are, and offered on a pending row only, before its
// `expires_at`: a row can still read `pending` after it expires, and
// its link admits no one (the handler refuses it too). `has()` opens
// each operand for the sparse `list_item` face (#8990), as on the
// recipient-side actions below; `expires_at` is compared by ordering,
// so it also needs its `!= null` half (`materializeDeclaredFields`).
visible: "features.cloudManaged != true && has(record.status) && record.status == 'pending' && has(record.expires_at) && record.expires_at != null && datetime(record.expires_at) > now()",
requiresFeature: 'organization',
requiresMembershipReach: 'invite_member',
resultDialog: {
title: 'Invite link',
description:
'Anyone who opens this link can accept the invitation, so share it only with the person you invited. '
+ 'It stops working once the invitation is accepted, declined, canceled or expires.',
format: 'text',
fields: [{ path: 'acceptUrl', label: 'Invite link' }],
acknowledge: 'Done',
},
// ADR-0011 identity-actions note, bucket H: human-only, no `ai` block.
// It answers the accept link, a bearer credential.
},
// ── Recipient-side actions (the invited user) ────────────────────
//
// These two are the counterpart to invite/cancel/resend: they are
// visible only on invitations addressed to the current user. Used
// by an "Inbox / Pending invitations" list opened from the user's
// own account page. The recipient-only `visible` predicate keeps
// them out of the admin org-management view.
//
// Both predicates open each operand with `has()` for the SPARSE action
// face (#8990): they reach `list_item`, so the bound record is the row the
// inbox view projected, and an unprojected `email` / `status` aborts the
// whole predicate at key resolution instead of reading null — fail-closed,
// so the Accept/Decline pair vanishes with no way to tell that from the
// gate having said no. `has()` alone suffices because both operands are
// compared by bare equality against a literal; `materializeDeclaredFields`
// in `@objectstack/objectql` states the rule and when the `!= null` half
// is additionally required.
{
name: 'accept_invitation',
label: 'Accept Invitation',
icon: 'check',
variant: 'primary',
locations: ['list_item', 'record_header'],
type: 'api',
target: '/api/v1/auth/organization/accept-invitation',
recordIdParam: 'invitationId',
// Hidden while cloud-managed: accepting creates a membership, which is
// the hosting organisation's there; the door refuses (409
// RESOURCE_CONFLICT). Decline stays: it writes no membership.
visible: "has(record.email) && record.email == ctx.user.email && has(record.status) && record.status == 'pending' && features.cloudManaged != true",
successMessage: 'Invitation accepted',
refreshAfter: true,
// ADR-0011 identity-actions note, bucket E: exposed by plain declaration.
ai: {
exposed: true,
description:
'Accept an invitation addressed to the current user (the record), joining its organization with the invited role. Works only on a pending invitation sent to the caller\'s own email address. '
+ 'While this deployment delivers email, the caller\'s address must also be verified: an unverified caller is refused with EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION and nothing is written, so ask the human to verify their email address first, then accept.',
},
},
{
name: 'reject_invitation',
label: 'Decline Invitation',
icon: 'x',
variant: 'ghost',
locations: ['list_item', 'record_header'],
type: 'api',
target: '/api/v1/auth/organization/reject-invitation',
recordIdParam: 'invitationId',
visible: "has(record.email) && record.email == ctx.user.email && has(record.status) && record.status == 'pending'",
confirmText: 'Decline this invitation? The inviter will be notified and you will need a new invitation to join.',
successMessage: 'Invitation declined',
refreshAfter: true,
// ADR-0011 identity-actions note, bucket C: exposed, and the
// confirmation is never relaxed.
ai: {
exposed: true,
description:
'Decline an invitation addressed to the current user (the record). The inviter is notified, and joining later needs a new invitation. Ask the human to confirm before calling.',
requiresConfirmation: true,
},
},
],
listViews: {
pending: {
type: 'grid',
name: 'pending',
label: 'Pending',
data: { provider: 'object', object: 'sys_invitation' },
columns: ['email', 'role', 'organization_id', 'inviter_id', 'expires_at'],
filter: [{ field: 'status', operator: 'equals', value: 'pending' }],
sort: [{ field: 'expires_at', order: 'asc' }],
pagination: { pageSize: 50 },
// A view-filtered empty state names its view: "No invitations" here
// would read as "nobody was ever invited" on the page Setup opens first.
emptyState: {
title: 'No pending invitations',
message: 'An invitation stays here until it is accepted, declined or canceled, or until it expires.',
},
},
accepted: {
type: 'grid',
name: 'accepted',
label: 'Accepted',
data: { provider: 'object', object: 'sys_invitation' },
columns: ['email', 'role', 'organization_id', 'inviter_id', 'created_at'],
filter: [{ field: 'status', operator: 'equals', value: 'accepted' }],
sort: [{ field: 'created_at', order: 'desc' }],
pagination: { pageSize: 50 },
emptyState: {
title: 'No accepted invitations',
message: 'An invitation moves here when the person accepts it and joins the organization.',
},
},
expired: {
type: 'grid',
name: 'expired',
label: 'Expired / Canceled',
data: { provider: 'object', object: 'sys_invitation' },
columns: ['email', 'status', 'role', 'organization_id', 'expires_at'],
filter: [{ field: 'status', operator: 'in', value: ['expired', 'rejected', 'canceled'] }],
sort: [{ field: 'expires_at', order: 'desc' }],
pagination: { pageSize: 50 },
emptyState: {
title: 'No expired or canceled invitations',
message: 'Invitations that expired, were declined or were canceled are kept here.',
},
},
all_invitations: {
type: 'grid',
name: 'all_invitations',
label: 'All',
data: { provider: 'object', object: 'sys_invitation' },
columns: ['email', 'status', 'role', 'organization_id', 'inviter_id', 'created_at'],
sort: [{ field: 'created_at', order: 'desc' }],
pagination: { pageSize: 50 },
emptyState: {
title: 'No invitations yet',
message: 'Every invitation to join an organization is listed here, whatever its status.',
},
},
},
fields: {
id: Field.text({
label: 'Invitation ID',
required: true,
readonly: true,
}),
// [ADR-0079] The record title (`nameField` above). A formula is computed on
// read and has no stored column. `email` is required, so the expression
// needs no null guard.
display_title: Field.formula({
label: 'Title',
returnType: 'text',
expression: F`'Invitation for ' + record.email`,
description: 'Record title: the invited email address (computed on read)',
}),
created_at: Field.datetime({
label: 'Created At',
defaultValue: 'NOW()',
readonly: true,
}),
organization_id: Field.lookup('sys_organization', {
label: 'Organization',
// Optional: single-tenant has no sys_organization row and no auto-stamp
// (org-scoping is multi-tenant-only). Multi-tenant: OrgScopingPlugin stamps it
// and tenant-isolation RLS hides null-org rows (fail-closed). ADR-0057 addendum.
required: false,
}),
email: Field.email({
label: 'Email',
required: true,
description: 'Email address of the invited user',
}),
// [ADR-0108 / #3723] Same list as `sys_member.role`, from the same
// constant — this is the value that lands there on acceptance, so the two
// can never be allowed to drift. The vocabulary is CLOSED: an app's own
// business roles are positions, carried by this invitation's `positions`
// placement field (ADR-0105 D8), which is authorized against the issuer's
// `adminScope` instead of riding in un-gated on the role name.
role: Field.select({
label: 'Role',
required: false,
description: 'Role to assign upon acceptance',
options: [...BUILTIN_MEMBERSHIP_ROLE_OPTIONS],
defaultValue: MEMBERSHIP_ROLE_MEMBER,
}),
// [#7726] Same list as the spec's `InvitationStatus`, from that enum — the
// two definitions of this vocabulary had already drifted once (the object
// shipped `canceled`, which better-auth writes on cancel-invitation, while
// the enum stopped at four values and so rejected a canceled row). Reading
// the options from the enum makes a repeat impossible rather than merely
// discouraged; `sys-invitation.status-vocabulary.test.ts` pins the rest.
// Each value carries a display label (`INVITATION_STATUS_LABELS`): the
// bare-string shorthand labelled every option with its stored value, so
// the list drew `pending` / `canceled` beside title-case tabs.
status: Field.select({
label: 'Status',
required: true,
defaultValue: 'pending',
options: InvitationStatus.options.map((value) => ({ value, label: INVITATION_STATUS_LABELS[value] })),
}),
inviter_id: Field.lookup('sys_user', {
label: 'Inviter',
required: true,
description: 'User who sent the invitation',
}),
expires_at: Field.datetime({
label: 'Expires At',
required: true,
}),
team_id: Field.lookup('sys_team', {
label: 'Team',
required: false,
description: 'Optional team to assign upon acceptance',
}),
// ── [ADR-0105 D8] Placement intent (ObjectStack extension fields) ──
// Carried on the invitation and applied WITH the better-auth membership
// on acceptance, so a delegated (plant) admin's invitee arrives already
// in the right unit and role instead of waiting on a platform admin.
// Issuance is authorized against the issuer's `adminScope` (ADR-0090
// D12) by the `invitation-placement` service — an invitation can never
// place what its issuer could not have assigned directly.
business_unit_id: Field.lookup('sys_business_unit', {
label: 'Placement Business Unit',
required: false,
description:
'Business unit the invitee is placed under on acceptance. Must lie inside the issuer\'s delegated subtree.',
}),
positions: Field.json({
label: 'Placement Positions',
required: false,
description:
'Position names assigned on acceptance. Every position\'s permission sets must be allowlisted by the issuer\'s adminScope.',
}),
},
indexes: [
{ fields: ['organization_id'] },
{ fields: ['email'] },
{ fields: ['expires_at'] },
],
enable: {
trackHistory: true,
searchable: false,
apiEnabled: true,
// #1591 — reads only: writes are refused by the identity write guard
// (ADR-0092 D2) and owned by better-auth. HTTP answers 405 before the 403.
apiMethods: ['get', 'list'],
},
});