@segmentstream/ontology 0.94.0 → 0.95.0
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/README.md +24 -3
- package/dist/analyze.js +9 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/manifest-compatibility.d.ts +7 -0
- package/dist/manifest-compatibility.js +12 -0
- package/dist/migrate/apply.d.ts +3 -2
- package/dist/migrate/apply.js +6 -2
- package/dist/migrate/plan.js +9 -1
- package/dist/migrate/storage.d.ts +7 -0
- package/dist/migrate/storage.js +22 -12
- package/dist/permissions.d.ts +9 -0
- package/dist/permissions.js +8 -0
- package/dist/runtime/channel-identity-admin.d.ts +41 -0
- package/dist/runtime/channel-identity-admin.js +223 -0
- package/dist/runtime/generated-actions.d.ts +2 -1
- package/dist/runtime/generated-actions.js +71 -3
- package/dist/runtime/principals.d.ts +24 -3
- package/dist/runtime/principals.js +42 -8
- package/dist/runtime/service-binding.js +2 -1
- package/dist/runtime/sql-runtime.d.ts +14 -1
- package/dist/runtime/sql-runtime.js +9 -0
- package/dist/runtime/user-identities.d.ts +5 -3
- package/dist/runtime/user-identities.js +9 -4
- package/dist/runtime/user-identity-sql.d.ts +4 -1
- package/dist/runtime/user-identity-sql.js +5 -2
- package/dist/runtime-source.d.ts +6 -0
- package/dist/runtime-source.js +11 -0
- package/dist/service/agent/attachments.js +4 -0
- package/dist/service/agent/authentication.d.ts +74 -2
- package/dist/service/agent/authentication.js +93 -11
- package/dist/service/agent/files.js +8 -1
- package/dist/service/agent/server.js +13 -2
- package/dist/service/authentication.js +58 -2
- package/dist/service/caller-context.d.ts +16 -0
- package/dist/service/chat/envelope.d.ts +18 -0
- package/dist/service/chat/envelope.js +10 -0
- package/dist/service/errors.d.ts +3 -2
- package/dist/service/errors.js +9 -3
- package/dist/service/runtime-contract.d.ts +9 -0
- package/dist/storage/attachments.d.ts +11 -0
- package/dist/user-identity.d.ts +14 -5
- package/dist/user-identity.js +25 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1230,6 +1230,19 @@ The agent acts for a member by adding `X-SegmentStream-Act-As: <user id>` on any
|
|
|
1230
1230
|
`/mcp` included: the request runs with the member's current roles and history names the
|
|
1231
1231
|
member, as if they had called. A member who is inactive or has no live pairing is a 403.
|
|
1232
1232
|
|
|
1233
|
+
An agent runtime outside the deployment acts for members the same way with an API key with
|
|
1234
|
+
delegation (`createServiceUser(ontology, { name, roles: [], keyLabel, delegation: true })`, or
|
|
1235
|
+
`segmentstream ontology api-key create NAME --delegation`): `Authorization: Bearer ssk_…`, the
|
|
1236
|
+
member in `X-SegmentStream-Act-As` and, required here, the provider of the account they wrote
|
|
1237
|
+
from in `X-SegmentStream-Identity-Provider`. The member must hold a live chat account of that
|
|
1238
|
+
provider; the key's own service user holds no role and grants nothing. Such a key reaches the
|
|
1239
|
+
routes that accept the runtime's act-as header, `GET /api/ontology/agent/identities/{provider}/{external_id}`
|
|
1240
|
+
and the agent's attachment and file routes, and no other agent route; it never presents
|
|
1241
|
+
`X-SegmentStream-Agent-Task`. Its `_segmentstream` source must name the member's own account as
|
|
1242
|
+
`sender`. The caller is `{ kind: "runtime", delegatedBy: { id, account } }`, and the service logs
|
|
1243
|
+
`ontology.delegation.authenticated` or `ontology.delegation.refused`. An ordinary key ignores
|
|
1244
|
+
both headers. `resolveApiKeyCredential` returns a key's principal and whether it delegates.
|
|
1245
|
+
|
|
1233
1246
|
Running a task a workflow handed it (see [Agent tasks](#agent-tasks)), the agent instead presents
|
|
1234
1247
|
the task's secret in `X-SegmentStream-Agent-Task: <secret>`, on `/mcp` and the two task routes
|
|
1235
1248
|
only. While the task is live, neither ended nor past its deadline, the request runs as the
|
|
@@ -1476,7 +1489,13 @@ maintained in its own repository.
|
|
|
1476
1489
|
### Member identity inspection
|
|
1477
1490
|
|
|
1478
1491
|
Platform member summaries include optional live `identities` with `provider`, `subject` and
|
|
1479
|
-
`username` metadata, and a `blocked` flag.
|
|
1492
|
+
`username` metadata, and a `blocked` flag. An administrator whose role names
|
|
1493
|
+
`user_identity:attach` attaches a known Telegram, WhatsApp or Slack account to an active member
|
|
1494
|
+
with the built-in action `user_identity.attach({ user, provider, subject, username?, display? })`
|
|
1495
|
+
(origin `attach`), and one naming `user_identity:revoke` revokes any chat account with
|
|
1496
|
+
`user_identity.revoke({ id })`. Attaching grants no role, is idempotent for the member's own
|
|
1497
|
+
account, and is a conflict for another member's live account or a second account of the
|
|
1498
|
+
provider. No other action writes `user_identity`. Revoked bindings are omitted; identity subjects are
|
|
1480
1499
|
stable and usernames are mutable display metadata. Older databases without channel tables
|
|
1481
1500
|
remain readable. Use `segmentstream ontology member list --via PROVIDER` to find a member UUID.
|
|
1482
1501
|
|
|
@@ -1680,8 +1699,10 @@ cannot undo the originating action. Workspaces own recursion prevention, deliver
|
|
|
1680
1699
|
any retry policy.
|
|
1681
1700
|
|
|
1682
1701
|
Authenticated runtime actions can read `context.runtime?.source`. It is populated only from
|
|
1683
|
-
verified runtime metadata, including Telegram source
|
|
1684
|
-
|
|
1702
|
+
verified runtime metadata, including Telegram source, staged attachment bindings and a shared
|
|
1703
|
+
`location` (`latitude`, `longitude`, optional `horizontal_accuracy` and `live_period`), and is
|
|
1704
|
+
absent for ordinary OAuth/API-key input. An API key with delegation sends it only for messages
|
|
1705
|
+
of the member's own account. Do not trust an action input property named `source`.
|
|
1685
1706
|
|
|
1686
1707
|
### Replication lifecycle and freshness
|
|
1687
1708
|
|
package/dist/analyze.js
CHANGED
|
@@ -8,7 +8,7 @@ import { CONNECTION_KEY, isConnection } from "./connection.js";
|
|
|
8
8
|
import { isEntity } from "./entity.js";
|
|
9
9
|
import { QUERY_METRICS_ROUTE, LEGACY_MEMBER_NAME, ENTITY_ID, GENERATED_ACTIONS, GENERATED_UPSERT_PREFIX, HISTORY_SUFFIX, MCP_METRIC_TOOLS, MCP_READ_TOOLS, MCP_TOOL_NAME_MAX_LENGTH, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, mcpToolName, RESERVED_ENTITY_NAMES, RESERVED_MEMBER_NAMES, RESERVED_RELATIONSHIP_NAMES, SNAKE_CASE_NAME, SYSTEM_PROPERTIES, isSystemProperty, toCamelCase, } from "./names.js";
|
|
10
10
|
import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownPropertyOptions, referenceTarget, } from "./property.js";
|
|
11
|
-
import { generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
|
|
11
|
+
import { generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
|
|
12
12
|
import { ON_DELETE, isRelationship } from "./relationship.js";
|
|
13
13
|
import { isRole, member, role } from "./role.js";
|
|
14
14
|
import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isSignInPolicy, } from "./sign-in.js";
|
|
@@ -790,6 +790,7 @@ function toolOperations(candidate) {
|
|
|
790
790
|
: []),
|
|
791
791
|
...(permissions.link !== undefined ? ["link", "unlink"] : []),
|
|
792
792
|
...(candidate.builtIn && candidate.name === User.name ? USER_MEMBER_VERBS : []),
|
|
793
|
+
...(candidate.builtIn && candidate.name === UserIdentity.name ? USER_IDENTITY_VERBS : []),
|
|
793
794
|
];
|
|
794
795
|
return [
|
|
795
796
|
...[...MCP_READ_TOOLS, ...generated].map((operation) => ({ operation, path: candidate.name })),
|
|
@@ -1823,7 +1824,8 @@ function ownMembers(candidate, entitiesByName) {
|
|
|
1823
1824
|
}
|
|
1824
1825
|
/**
|
|
1825
1826
|
* The verbs each entity has: `read`, its generated actions, and what its actions require. The
|
|
1826
|
-
* built-in user also has its member management verbs,
|
|
1827
|
+
* built-in user also has its member management verbs, and the built-in sign-in identities their
|
|
1828
|
+
* attach and revoke, which roles may grant.
|
|
1827
1829
|
*/
|
|
1828
1830
|
function knownVerbs(entities) {
|
|
1829
1831
|
const verbs = new Map();
|
|
@@ -1840,6 +1842,11 @@ function knownVerbs(entities) {
|
|
|
1840
1842
|
own.add(verb);
|
|
1841
1843
|
}
|
|
1842
1844
|
}
|
|
1845
|
+
if (candidate.builtIn && candidate.name === UserIdentity.name) {
|
|
1846
|
+
for (const verb of USER_IDENTITY_VERBS) {
|
|
1847
|
+
own.add(verb);
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1843
1850
|
verbs.set(candidate.name, own);
|
|
1844
1851
|
}
|
|
1845
1852
|
for (const candidate of entities) {
|
package/dist/index.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ export { check, defineOntology } from "./ontology.js";
|
|
|
31
31
|
export { webhookDeliveryJsonSchema } from "./analyze.js";
|
|
32
32
|
export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
|
|
33
33
|
export type { Ontology } from "./ontology.js";
|
|
34
|
-
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
34
|
+
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
35
35
|
export type { ParsedPermission, PermissionHolder, RolePermissions, ScopedPermission, ScopeFilter, ScopeValue, ScopeWhere, UserMemberVerb, } from "./permissions.js";
|
|
36
36
|
export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
|
|
37
37
|
export type { AnyProperty, NumberOptions, Property, PropertyDefinition, PropertyOf, PropertyOptions, BlobOptions, ListOptions, PropertyType, ReferenceOptions, SelectOption, SelectOptionInput, TextOptions, } from "./property.js";
|
|
@@ -55,8 +55,8 @@ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, Batc
|
|
|
55
55
|
export { User } from "./user.js";
|
|
56
56
|
export type { UserHandle, UserMemberWrites } from "./user.js";
|
|
57
57
|
export { AgentChat } from "./agent-chat.js";
|
|
58
|
-
export { UserIdentity, USER_IDENTITY_ORIGINS } from "./user-identity.js";
|
|
59
|
-
export type { UserIdentityOrigin } from "./user-identity.js";
|
|
58
|
+
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
|
59
|
+
export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
|
|
60
60
|
export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
|
|
61
61
|
export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
|
|
62
62
|
export { DEFAULT_QUERY_LIMIT, entityQueryResultSchema, entityQuerySchema, entityQuerySchemas, entityRecordSchema, FILTER_OPERATORS, LIST_FILTER_OPERATORS, MANY_QUANTIFIERS, MAX_IN_VALUES, MAX_QUERY_LIMIT, OrderBy, Query, queryFields, queryJsonSchema, queryLinks, QueryResult, queryResultJsonSchema, queryResultSchema, SortDirection, WHERE_COMBINATORS, } from "./query.js";
|
|
@@ -67,8 +67,8 @@ export type { GeneratedActionManifest, GeneratedActions } from "./runtime/genera
|
|
|
67
67
|
export { Change, Edit, EditKind, HistoryEntry } from "./runtime/history.js";
|
|
68
68
|
export { ActionOutcome, ActionValidation, findAction, PREPARE_TIMEOUT, resolveAction, runAction, } from "./runtime/pipeline.js";
|
|
69
69
|
export type { ActionRequest, AfterCommit, CommittedAction, FoundAction, } from "./runtime/pipeline.js";
|
|
70
|
-
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, } from "./runtime/principals.js";
|
|
71
|
-
export type { ApiKeyParts, ApiKeySummary, CreatedApiKey, IdentityClaims, MemberKey, MemberRolesChange, MemberStatus, MemberSummary, PrincipalsManifest, } from "./runtime/principals.js";
|
|
70
|
+
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, } from "./runtime/principals.js";
|
|
71
|
+
export type { ApiKeyCredential, ApiKeyParts, ApiKeySummary, CreatedApiKey, IdentityClaims, MemberKey, MemberRolesChange, MemberStatus, MemberSummary, PrincipalsManifest, } from "./runtime/principals.js";
|
|
72
72
|
export { backendLayer, postgresLayer, sqlServiceRuntime } from "./runtime/service-binding.js";
|
|
73
73
|
export { makeOntologyRuntime } from "./runtime/sql-runtime.js";
|
|
74
74
|
export type { SqlOntologyRuntime, WriteScope } from "./runtime/sql-runtime.js";
|
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire
|
|
|
18
18
|
export { check, defineOntology } from "./ontology.js";
|
|
19
19
|
export { webhookDeliveryJsonSchema } from "./analyze.js";
|
|
20
20
|
export { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
|
|
21
|
-
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
21
|
+
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
22
22
|
export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
|
|
23
23
|
export { ON_DELETE, rel } from "./relationship.js";
|
|
24
24
|
export { renderCatalog } from "./render.js";
|
|
@@ -29,7 +29,7 @@ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POL
|
|
|
29
29
|
export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
|
|
30
30
|
export { User } from "./user.js";
|
|
31
31
|
export { AgentChat } from "./agent-chat.js";
|
|
32
|
-
export { UserIdentity, USER_IDENTITY_ORIGINS } from "./user-identity.js";
|
|
32
|
+
export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
|
|
33
33
|
export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
|
|
34
34
|
export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
|
|
35
35
|
// The query language of `find` and of the service's list, query and traversal routes.
|
|
@@ -39,7 +39,7 @@ export { InvalidQuery, InvalidValues, MemberNotFound, PrincipalRejected, StoredR
|
|
|
39
39
|
export { generatedActionManifests, generatedActions, upsertActionName, } from "./runtime/generated-actions.js";
|
|
40
40
|
export { Change, Edit, EditKind, HistoryEntry } from "./runtime/history.js";
|
|
41
41
|
export { ActionOutcome, ActionValidation, findAction, PREPARE_TIMEOUT, resolveAction, runAction, } from "./runtime/pipeline.js";
|
|
42
|
-
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, } from "./runtime/principals.js";
|
|
42
|
+
export { API_KEY_ITERATIONS, API_KEY_PREFIX, checkSignIn, createApiKey, createServiceUser, findApiKey, generateApiKey, grantMemberRoles, hashApiKeySecret, listApiKeys, listMembers, countUsersWithoutEmailIdentity, countUsersWithoutSegmentStreamIdentity, MEMBER_HISTORY_ACTIONS, parseApiKey, principalsOntology, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, reconcileWorkflowUsers, resolveWorkflowUser, revokeApiKey, WORKFLOW_USER_PROVIDER, workflowSubject, revokeMemberRoles, setMemberActive, setMemberBlocked, revokeMemberSessions, setUserRoles, SIGN_IN_RECORD_INTERVAL_MS, updateMemberRoles, } from "./runtime/principals.js";
|
|
43
43
|
export { backendLayer, postgresLayer, sqlServiceRuntime } from "./runtime/service-binding.js";
|
|
44
44
|
export { makeOntologyRuntime } from "./runtime/sql-runtime.js";
|
|
45
45
|
// The HTTP service derived from the ontology.
|
|
@@ -6,3 +6,10 @@ import { type OntologyManifest } from "./manifest.js";
|
|
|
6
6
|
* live users, exact roles and revocations still apply.
|
|
7
7
|
*/
|
|
8
8
|
export declare function browserAuthenticationCompatible(left: OntologyManifest, right: OntologyManifest): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Whether a deployed manifest comes from an ontology SDK whose service acts for members with API
|
|
11
|
+
* keys with delegation, and whose migration gave `_api_keys` its `delegation` column. That SDK
|
|
12
|
+
* also introduced the `attach` origin of the built-in sign-in identities, which its manifest lists:
|
|
13
|
+
* the platform reads that, as any reader of any manifest version can, instead of a version.
|
|
14
|
+
*/
|
|
15
|
+
export declare function supportsDelegatedApiKeys(manifest: OntologyManifest): boolean;
|
|
@@ -85,3 +85,15 @@ export function browserAuthenticationCompatible(left, right) {
|
|
|
85
85
|
const b = withoutPresentation(right);
|
|
86
86
|
return a !== undefined && b !== undefined && canonicalJson(a) === canonicalJson(b);
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Whether a deployed manifest comes from an ontology SDK whose service acts for members with API
|
|
90
|
+
* keys with delegation, and whose migration gave `_api_keys` its `delegation` column. That SDK
|
|
91
|
+
* also introduced the `attach` origin of the built-in sign-in identities, which its manifest lists:
|
|
92
|
+
* the platform reads that, as any reader of any manifest version can, instead of a version.
|
|
93
|
+
*/
|
|
94
|
+
export function supportsDelegatedApiKeys(manifest) {
|
|
95
|
+
return (manifest.entities
|
|
96
|
+
.find((entity) => entity.name === "user_identity")
|
|
97
|
+
?.properties.find((property) => property.name === "origin")
|
|
98
|
+
?.options?.some((option) => option.value === "attach") === true);
|
|
99
|
+
}
|
package/dist/migrate/apply.d.ts
CHANGED
|
@@ -82,8 +82,9 @@ export declare const RUNTIME_TABLES: ReadonlyArray<string>;
|
|
|
82
82
|
* The runtime tables the database has, for `planMigration`'s `existingTables`: a database that an
|
|
83
83
|
* earlier SDK migrated lacks the tables added since.
|
|
84
84
|
* A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
|
|
85
|
-
* also upgrades an unchanged manifest, and so is an
|
|
86
|
-
* one of {@link ATTACHMENT_SOURCES}, which the
|
|
85
|
+
* also upgrades an unchanged manifest, and so is an API keys table without `delegation` and an
|
|
86
|
+
* attachments table whose source check predates one of {@link ATTACHMENT_SOURCES}, which the
|
|
87
|
+
* idempotent API key and attachment DDL add and widen.
|
|
87
88
|
*/
|
|
88
89
|
export declare const readRuntimeTables: (input: CatalogInput) => Effect.Effect<ReadonlySet<string>, SqlError>;
|
|
89
90
|
/** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
|
package/dist/migrate/apply.js
CHANGED
|
@@ -478,8 +478,9 @@ export const RUNTIME_TABLES = [
|
|
|
478
478
|
* The runtime tables the database has, for `planMigration`'s `existingTables`: a database that an
|
|
479
479
|
* earlier SDK migrated lacks the tables added since.
|
|
480
480
|
* A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
|
|
481
|
-
* also upgrades an unchanged manifest, and so is an
|
|
482
|
-
* one of {@link ATTACHMENT_SOURCES}, which the
|
|
481
|
+
* also upgrades an unchanged manifest, and so is an API keys table without `delegation` and an
|
|
482
|
+
* attachments table whose source check predates one of {@link ATTACHMENT_SOURCES}, which the
|
|
483
|
+
* idempotent API key and attachment DDL add and widen.
|
|
483
484
|
*/
|
|
484
485
|
export const readRuntimeTables = (input) => input.sql
|
|
485
486
|
.unsafe(`SELECT "tablename" AS "name" FROM "pg_catalog"."pg_tables" ` +
|
|
@@ -488,6 +489,9 @@ export const readRuntimeTables = (input) => input.sql
|
|
|
488
489
|
`AND ("tablename" <> '_oauth_grants' OR EXISTS (` +
|
|
489
490
|
`SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
|
|
490
491
|
`AND table_name = '_oauth_grants' AND column_name = 'identity_id')) ` +
|
|
492
|
+
`AND ("tablename" <> ${quoteLiteral(API_KEYS_TABLE)} OR EXISTS (` +
|
|
493
|
+
`SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
|
|
494
|
+
`AND table_name = ${quoteLiteral(API_KEYS_TABLE)} AND column_name = 'delegation')) ` +
|
|
491
495
|
`AND ("tablename" <> ${quoteLiteral(ATTACHMENTS_TABLE)} OR EXISTS (` +
|
|
492
496
|
`SELECT 1 FROM pg_catalog.pg_constraint c ` +
|
|
493
497
|
`JOIN pg_catalog.pg_class t ON t.oid = c.conrelid ` +
|
package/dist/migrate/plan.js
CHANGED
|
@@ -4,7 +4,7 @@ import { EMAIL_LINK_FENCE_SQL, SEGMENTSTREAM_LINK_FENCE_SQL, USER_IDENTITY_ENTIT
|
|
|
4
4
|
import { AGENT_TASKS_DDL, AGENT_TASKS_TABLE, SIGN_IN_EMAILS_DDL, SIGN_IN_EMAILS_TABLE, ATTACHMENTS_TABLE, ATTACHMENT_TABLES_DDL, BLOB_TABLES_DDL, WORKFLOW_STARTS_DDL, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
|
|
5
5
|
import { SNAKE_CASE_NAME, isSystemProperty, toSnakeCase } from "../names.js";
|
|
6
6
|
import { NO_RETAINED_STORAGE, retainedEntityManifest, } from "./model.js";
|
|
7
|
-
import { ACTION_ATTRIBUTION_TABLE, ACTION_ATTRIBUTION_DDL, AGENT_TABLES, AGENT_TABLES_DDL, CATALOG_TABLE_DDL, MAX_IDENTIFIER_LENGTH, OAUTH_TABLES, OAUTH_TABLES_DDL, USER_TABLE, addConstraintStatement, columnName, columnDefinition, constraintDefinition, createEnumStatement, createIndexStatement, createTableStatement, defaultExpression, entityStorage, historyActivityIndex, enumTypeName, isStoredProperty, fieldColumnName, joinTable, propertyCheck, blobForeignKey, propertyColumn, propertyEnum, quoteIdentifier, quoteLiteral, relationshipColumn, relationshipColumnName, RUNTIME_TABLES_DDL, relationshipForeignKey, SYSTEM_COLUMNS, storedEntity, tableName, } from "./storage.js";
|
|
7
|
+
import { ACTION_ATTRIBUTION_TABLE, ACTION_ATTRIBUTION_DDL, AGENT_TABLES, AGENT_TABLES_DDL, API_KEYS_DDL, API_KEYS_TABLE, CATALOG_TABLE_DDL, MAX_IDENTIFIER_LENGTH, OAUTH_TABLES, OAUTH_TABLES_DDL, USER_TABLE, addConstraintStatement, columnName, columnDefinition, constraintDefinition, createEnumStatement, createIndexStatement, createTableStatement, defaultExpression, entityStorage, historyActivityIndex, enumTypeName, isStoredProperty, fieldColumnName, joinTable, propertyCheck, blobForeignKey, propertyColumn, propertyEnum, quoteIdentifier, quoteLiteral, relationshipColumn, relationshipColumnName, RUNTIME_TABLES_DDL, relationshipForeignKey, SYSTEM_COLUMNS, storedEntity, tableName, } from "./storage.js";
|
|
8
8
|
const NO_MEMBERS = { properties: new Set(), relationships: new Set() };
|
|
9
9
|
const GLOBAL_KINDS = new Set(["table", "type", "index"]);
|
|
10
10
|
function step(input) {
|
|
@@ -169,6 +169,14 @@ export function planMigration(input) {
|
|
|
169
169
|
sql: FEDERATION_TABLES_DDL,
|
|
170
170
|
}));
|
|
171
171
|
}
|
|
172
|
+
if (lacks([API_KEYS_TABLE])) {
|
|
173
|
+
draft.runtimeTables.push(step({
|
|
174
|
+
kind: "createCatalog",
|
|
175
|
+
classification: "additive",
|
|
176
|
+
description: "Let API keys act for members with delegation, beside the keys that act with roles.",
|
|
177
|
+
sql: API_KEYS_DDL,
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
172
180
|
if (lacks(OAUTH_TABLES)) {
|
|
173
181
|
draft.runtimeTables.push(step({
|
|
174
182
|
kind: "createCatalog",
|
|
@@ -211,6 +211,13 @@ export declare const AGENT_TABLES_DDL: ReadonlyArray<string>;
|
|
|
211
211
|
export declare const ACTION_ATTRIBUTION_TABLE = "_ontology_action_attribution";
|
|
212
212
|
/** Runtime audit metadata deliberately has no foreign key: deleted records retain their history. */
|
|
213
213
|
export declare const ACTION_ATTRIBUTION_DDL: ReadonlyArray<string>;
|
|
214
|
+
/**
|
|
215
|
+
* The API keys of the app's services: each names a `user` and holds the PBKDF2 hash of its secret.
|
|
216
|
+
* A key with `delegation` acts only for the member each request names, with that member's roles,
|
|
217
|
+
* never with its own user's. Idempotent: a database an earlier SDK migrated gains `delegation` on
|
|
218
|
+
* its next migration.
|
|
219
|
+
*/
|
|
220
|
+
export declare const API_KEYS_DDL: ReadonlyArray<string>;
|
|
214
221
|
export declare const RUNTIME_TABLES_DDL: ReadonlyArray<string>;
|
|
215
222
|
export declare function columnDefinition(column: ColumnStorage): string;
|
|
216
223
|
export declare function constraintDefinition(constraint: {
|
package/dist/migrate/storage.js
CHANGED
|
@@ -701,18 +701,13 @@ export const ACTION_ATTRIBUTION_DDL = [
|
|
|
701
701
|
"at" timestamptz NOT NULL DEFAULT now()
|
|
702
702
|
)`,
|
|
703
703
|
];
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
` CONSTRAINT "${USER_ROLES_TABLE}_pkey" PRIMARY KEY ("user_id", "role"),`,
|
|
712
|
-
` CONSTRAINT "${USER_ROLES_TABLE}_user_id_fkey" FOREIGN KEY ("user_id") ` +
|
|
713
|
-
`REFERENCES ${quoteIdentifier(USER_TABLE)} ("id") ON DELETE CASCADE`,
|
|
714
|
-
`)`,
|
|
715
|
-
].join("\n"),
|
|
704
|
+
/**
|
|
705
|
+
* The API keys of the app's services: each names a `user` and holds the PBKDF2 hash of its secret.
|
|
706
|
+
* A key with `delegation` acts only for the member each request names, with that member's roles,
|
|
707
|
+
* never with its own user's. Idempotent: a database an earlier SDK migrated gains `delegation` on
|
|
708
|
+
* its next migration.
|
|
709
|
+
*/
|
|
710
|
+
export const API_KEYS_DDL = [
|
|
716
711
|
[
|
|
717
712
|
`CREATE TABLE IF NOT EXISTS ${quoteIdentifier(API_KEYS_TABLE)} (`,
|
|
718
713
|
` "id" uuid NOT NULL,`,
|
|
@@ -730,6 +725,21 @@ export const RUNTIME_TABLES_DDL = [
|
|
|
730
725
|
`)`,
|
|
731
726
|
].join("\n"),
|
|
732
727
|
`CREATE INDEX IF NOT EXISTS "${API_KEYS_TABLE}_user_id_idx" ON ${quoteIdentifier(API_KEYS_TABLE)} ("user_id")`,
|
|
728
|
+
`ALTER TABLE ${quoteIdentifier(API_KEYS_TABLE)} ADD COLUMN IF NOT EXISTS "delegation" boolean NOT NULL DEFAULT false`,
|
|
729
|
+
];
|
|
730
|
+
export const RUNTIME_TABLES_DDL = [
|
|
731
|
+
...FEDERATION_TABLES_DDL,
|
|
732
|
+
...ACTION_ATTRIBUTION_DDL,
|
|
733
|
+
[
|
|
734
|
+
`CREATE TABLE IF NOT EXISTS ${quoteIdentifier(USER_ROLES_TABLE)} (`,
|
|
735
|
+
` "user_id" uuid NOT NULL,`,
|
|
736
|
+
` "role" text NOT NULL,`,
|
|
737
|
+
` CONSTRAINT "${USER_ROLES_TABLE}_pkey" PRIMARY KEY ("user_id", "role"),`,
|
|
738
|
+
` CONSTRAINT "${USER_ROLES_TABLE}_user_id_fkey" FOREIGN KEY ("user_id") ` +
|
|
739
|
+
`REFERENCES ${quoteIdentifier(USER_TABLE)} ("id") ON DELETE CASCADE`,
|
|
740
|
+
`)`,
|
|
741
|
+
].join("\n"),
|
|
742
|
+
...API_KEYS_DDL,
|
|
733
743
|
...OAUTH_TABLES_DDL,
|
|
734
744
|
...AGENT_TABLES_DDL,
|
|
735
745
|
];
|
package/dist/permissions.d.ts
CHANGED
|
@@ -28,6 +28,15 @@ export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
|
|
|
28
28
|
*/
|
|
29
29
|
export declare const USER_MEMBER_VERBS: readonly ["invite", "grant_roles", "revoke_roles", "deactivate", "reactivate"];
|
|
30
30
|
export type UserMemberVerb = (typeof USER_MEMBER_VERBS)[number];
|
|
31
|
+
/** The built-in sign-in identities' entity name in permissions. */
|
|
32
|
+
export declare const USER_IDENTITY_ENTITY = "user_identity";
|
|
33
|
+
/**
|
|
34
|
+
* The verbs of the built-in sign-in identities' platform actions: an administrator attaching a
|
|
35
|
+
* member's chat account and revoking one. `user_identity` is in {@link EXPLICIT_GRANT_ENTITIES}, so
|
|
36
|
+
* only `user_identity:<verb>` or `user_identity:*` grants them.
|
|
37
|
+
*/
|
|
38
|
+
export declare const USER_IDENTITY_VERBS: readonly ["attach", "revoke"];
|
|
39
|
+
export type UserIdentityVerb = (typeof USER_IDENTITY_VERBS)[number];
|
|
31
40
|
/**
|
|
32
41
|
* Entities of which a wildcard entity (`*:*`, `*:<verb>`) covers only the listed verbs; any other
|
|
33
42
|
* verb needs a permission that names the entity. A role written for business data must not
|
package/dist/permissions.js
CHANGED
|
@@ -39,6 +39,14 @@ export const USER_MEMBER_VERBS = [
|
|
|
39
39
|
"deactivate",
|
|
40
40
|
"reactivate",
|
|
41
41
|
];
|
|
42
|
+
/** The built-in sign-in identities' entity name in permissions. */
|
|
43
|
+
export const USER_IDENTITY_ENTITY = "user_identity";
|
|
44
|
+
/**
|
|
45
|
+
* The verbs of the built-in sign-in identities' platform actions: an administrator attaching a
|
|
46
|
+
* member's chat account and revoking one. `user_identity` is in {@link EXPLICIT_GRANT_ENTITIES}, so
|
|
47
|
+
* only `user_identity:<verb>` or `user_identity:*` grants them.
|
|
48
|
+
*/
|
|
49
|
+
export const USER_IDENTITY_VERBS = ["attach", "revoke"];
|
|
42
50
|
/**
|
|
43
51
|
* Entities of which a wildcard entity (`*:*`, `*:<verb>`) covers only the listed verbs; any other
|
|
44
52
|
* verb needs a permission that names the entity. A role written for business data must not
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { SqlClient } from "effect/unstable/sql";
|
|
3
|
+
import { ActionRejected, Conflict, NotFound } from "../errors.js";
|
|
4
|
+
import type { Ontology } from "../ontology.js";
|
|
5
|
+
import type { StoredRecord } from "../runtime.js";
|
|
6
|
+
import type { HistoryScope } from "./history.js";
|
|
7
|
+
/** The action that attaches a chat account, and the one that revokes one. */
|
|
8
|
+
export declare const ATTACH_IDENTITY_ACTION: string;
|
|
9
|
+
export declare const REVOKE_IDENTITY_ACTION: string;
|
|
10
|
+
export interface AttachIdentityInput {
|
|
11
|
+
/** The member the account is attached to. */
|
|
12
|
+
readonly user: string;
|
|
13
|
+
readonly provider: string;
|
|
14
|
+
/** The account's id at the provider. */
|
|
15
|
+
readonly subject: string;
|
|
16
|
+
readonly username?: string | undefined;
|
|
17
|
+
readonly display?: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Attaches a chat account to a member as an administrator's `user_identity.attach` does, inside
|
|
21
|
+
* the action's transaction, with history under the action and its principal. It takes the locks
|
|
22
|
+
* pairing takes, so that it never races a pairing, a block or another attach of the same account
|
|
23
|
+
* or member, and it fails closed where pairing would replace something:
|
|
24
|
+
*
|
|
25
|
+
* - the account is live on another member, or a blocked member ever held it: Conflict;
|
|
26
|
+
* - the member already holds a live account of the provider: Conflict, until it is revoked;
|
|
27
|
+
* - the member is a service, inactive or blocked: ActionRejected.
|
|
28
|
+
*
|
|
29
|
+
* Attaching the account the member already holds changes nothing but its username and display.
|
|
30
|
+
* It grants no role: the member keeps exactly the permissions they had.
|
|
31
|
+
*/
|
|
32
|
+
export declare function attachChannelIdentity(ontology: Ontology, sql: SqlClient.SqlClient, scope: HistoryScope, input: AttachIdentityInput): Effect.Effect<StoredRecord, ActionRejected | Conflict | NotFound>;
|
|
33
|
+
/**
|
|
34
|
+
* Revokes a member's chat account as `user_identity.revoke` does: the account stops acting for
|
|
35
|
+
* them at once, through the agent and through every external runtime, and their channel sessions
|
|
36
|
+
* end. A sign-in identity (email, SegmentStream) is not a chat account and is NotFound here; one
|
|
37
|
+
* already revoked is returned unchanged.
|
|
38
|
+
*/
|
|
39
|
+
export declare function revokeChannelIdentity(ontology: Ontology, sql: SqlClient.SqlClient, scope: HistoryScope, input: {
|
|
40
|
+
readonly id: string;
|
|
41
|
+
}): Effect.Effect<StoredRecord, NotFound>;
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { isSqlError } from "effect/unstable/sql/SqlError";
|
|
3
|
+
import { ActionRejected, Conflict, NotFound } from "../errors.js";
|
|
4
|
+
import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE, USER_TABLE } from "../migrate/storage.js";
|
|
5
|
+
import { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, } from "../user-identity.js";
|
|
6
|
+
import { revokeChannelSessions } from "./channel-session-revocation.js";
|
|
7
|
+
import { isMemberBlocked } from "./principals.js";
|
|
8
|
+
import { isRecordId } from "./records.js";
|
|
9
|
+
import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
|
|
10
|
+
/** The legacy channel accounts, written beside `user_identity` for earlier SDKs. */
|
|
11
|
+
const LEGACY_IDENTITIES = `"${AGENT_IDENTITIES_TABLE}"`;
|
|
12
|
+
const CHANNEL_ACCOUNT = `"i"."origin"::text IN ${CHANNEL_ORIGIN_SQL}`;
|
|
13
|
+
/** The action that attaches a chat account, and the one that revokes one. */
|
|
14
|
+
export const ATTACH_IDENTITY_ACTION = `${UserIdentity.name}.attach`;
|
|
15
|
+
export const REVOKE_IDENTITY_ACTION = `${UserIdentity.name}.revoke`;
|
|
16
|
+
/**
|
|
17
|
+
* What an account id looks like on each provider: Telegram's numeric user id, WhatsApp's phone
|
|
18
|
+
* number id and Slack's member id. A typo is refused before anything is locked or written.
|
|
19
|
+
*/
|
|
20
|
+
const SUBJECT_PATTERNS = {
|
|
21
|
+
telegram: /^[1-9][0-9]{0,19}$/,
|
|
22
|
+
whatsapp: /^[1-9][0-9]{5,19}$/,
|
|
23
|
+
slack: /^[A-Z0-9]{2,32}$/,
|
|
24
|
+
};
|
|
25
|
+
/** At most this many characters of a username or a display name are kept. */
|
|
26
|
+
const MAX_DESCRIPTION_LENGTH = 256;
|
|
27
|
+
function isAttachableProvider(provider) {
|
|
28
|
+
return ATTACHABLE_IDENTITY_PROVIDERS.includes(provider);
|
|
29
|
+
}
|
|
30
|
+
function described(value) {
|
|
31
|
+
const trimmed = value?.trim();
|
|
32
|
+
return trimmed === undefined || trimmed === ""
|
|
33
|
+
? undefined
|
|
34
|
+
: trimmed.slice(0, MAX_DESCRIPTION_LENGTH);
|
|
35
|
+
}
|
|
36
|
+
const conflict = (message) => new Conflict({ entity: UserIdentity.name, message });
|
|
37
|
+
/**
|
|
38
|
+
* Attaches a chat account to a member as an administrator's `user_identity.attach` does, inside
|
|
39
|
+
* the action's transaction, with history under the action and its principal. It takes the locks
|
|
40
|
+
* pairing takes, so that it never races a pairing, a block or another attach of the same account
|
|
41
|
+
* or member, and it fails closed where pairing would replace something:
|
|
42
|
+
*
|
|
43
|
+
* - the account is live on another member, or a blocked member ever held it: Conflict;
|
|
44
|
+
* - the member already holds a live account of the provider: Conflict, until it is revoked;
|
|
45
|
+
* - the member is a service, inactive or blocked: ActionRejected.
|
|
46
|
+
*
|
|
47
|
+
* Attaching the account the member already holds changes nothing but its username and display.
|
|
48
|
+
* It grants no role: the member keeps exactly the permissions they had.
|
|
49
|
+
*/
|
|
50
|
+
export function attachChannelIdentity(ontology, sql, scope, input) {
|
|
51
|
+
const rows = (statement, values = []) => sql.unsafe(statement, values);
|
|
52
|
+
return Effect.gen(function* () {
|
|
53
|
+
const { provider, subject, user: userId } = input;
|
|
54
|
+
if (!isAttachableProvider(provider)) {
|
|
55
|
+
return yield* new ActionRejected({
|
|
56
|
+
message: `${provider} is not a chat provider whose accounts can be attached; use one of ` +
|
|
57
|
+
`${ATTACHABLE_IDENTITY_PROVIDERS.join(", ")}.`,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
if (!SUBJECT_PATTERNS[provider].test(subject)) {
|
|
61
|
+
return yield* new ActionRejected({
|
|
62
|
+
message: `${subject} is not a ${provider} account id.`,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
if (!isRecordId(userId)) {
|
|
66
|
+
return yield* new NotFound({
|
|
67
|
+
entity: USER_TABLE,
|
|
68
|
+
id: userId,
|
|
69
|
+
message: `No member ${userId}.`,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
// The locks of pairing, in the same order: one attach, pairing or displacement of this
|
|
73
|
+
// account or of this member's account of the provider runs at a time.
|
|
74
|
+
yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1)), pg_advisory_xact_lock(hashtext($2))`, [
|
|
75
|
+
`account:${provider}:${subject}`,
|
|
76
|
+
`member:${userId}:${provider}`,
|
|
77
|
+
]);
|
|
78
|
+
// The member and everyone who holds or held the account stay as they are until this commits.
|
|
79
|
+
const owners = yield* rows(`SELECT "id"::text AS "id", "kind"::text AS "kind", "active" FROM "${USER_TABLE}"
|
|
80
|
+
WHERE "id" = $3::uuid OR "id" IN (
|
|
81
|
+
SELECT "user_id" FROM "${USER_IDENTITY_TABLE}" AS "i"
|
|
82
|
+
WHERE "i"."provider" = $1 AND "i"."subject" = $2 AND ${CHANNEL_ACCOUNT}
|
|
83
|
+
) OR "id" IN (
|
|
84
|
+
SELECT "user_id" FROM ${LEGACY_IDENTITIES} WHERE "provider" = $1 AND "external_id" = $2
|
|
85
|
+
) ORDER BY "id" FOR SHARE`, [provider, subject, userId]);
|
|
86
|
+
const target = owners.find((owner) => owner.id === userId);
|
|
87
|
+
if (target === undefined) {
|
|
88
|
+
return yield* new NotFound({
|
|
89
|
+
entity: USER_TABLE,
|
|
90
|
+
id: userId,
|
|
91
|
+
message: `No member ${userId}.`,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
if (target.kind !== "member") {
|
|
95
|
+
return yield* new ActionRejected({
|
|
96
|
+
message: "Chat accounts are attached to members; a service has none.",
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (target.active !== true || (yield* isMemberBlocked(sql, userId))) {
|
|
100
|
+
return yield* new ActionRejected({
|
|
101
|
+
message: "The member is inactive or blocked; reactivate them first.",
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
// Any member who ever held the account and is blocked keeps it from being attached, as from
|
|
105
|
+
// being paired.
|
|
106
|
+
const [blocked] = yield* rows(`SELECT 1 FROM "${CHANNEL_USERS_TABLE}" c WHERE c."user_id" IN (` +
|
|
107
|
+
owners.map((_, index) => `$${index + 1}::uuid`).join(", ") +
|
|
108
|
+
`) AND c."blocked_at" IS NOT NULL LIMIT 1`, owners.map((owner) => String(owner.id)));
|
|
109
|
+
if (blocked !== undefined) {
|
|
110
|
+
return yield* conflict(`The ${provider} account belongs to a blocked member.`);
|
|
111
|
+
}
|
|
112
|
+
const writer = makeIdentityWriter(ontology, sql, scope);
|
|
113
|
+
const description = {
|
|
114
|
+
...(described(input.username) === undefined
|
|
115
|
+
? {}
|
|
116
|
+
: { username: described(input.username).replace(/^@/, "") }),
|
|
117
|
+
...(described(input.display) === undefined ? {} : { display: described(input.display) }),
|
|
118
|
+
};
|
|
119
|
+
const [bound] = yield* rows(`SELECT "i"."id"::text AS "id", "i"."user_id"::text AS "user_id" FROM ${CHANNEL_IDENTITIES_FROM}
|
|
120
|
+
WHERE "i"."provider" = $1 AND "i"."subject" = $2 AND ${LIVE_CHANNEL_IDENTITY}`, [provider, subject]);
|
|
121
|
+
if (bound !== undefined) {
|
|
122
|
+
if (String(bound.user_id) !== userId) {
|
|
123
|
+
return yield* conflict(`The ${provider} account is attached to another member.`);
|
|
124
|
+
}
|
|
125
|
+
// Replayed: the member holds this very account. Only its description may change, in both
|
|
126
|
+
// stores, or the next migration's sync would copy the legacy one back. `user_identity` is
|
|
127
|
+
// written first, as every revocation locks it before the legacy row.
|
|
128
|
+
const described = yield* writer.describe(String(bound.id), description);
|
|
129
|
+
if (description.username !== undefined || description.display !== undefined) {
|
|
130
|
+
// @legacy identities.legacy-stores-dual-write
|
|
131
|
+
yield* rows(`UPDATE ${LEGACY_IDENTITIES} SET "username" = COALESCE($2, "username"),
|
|
132
|
+
"display" = COALESCE($3, "display")
|
|
133
|
+
WHERE "id" = $1::uuid`, [String(bound.id), description.username ?? null, description.display ?? null]);
|
|
134
|
+
}
|
|
135
|
+
return described;
|
|
136
|
+
}
|
|
137
|
+
const [legacyBound] = yield* rows(`SELECT "user_id"::text AS "user_id" FROM ${LEGACY_IDENTITIES}
|
|
138
|
+
WHERE "provider" = $1 AND "external_id" = $2 AND "revoked_at" IS NULL`, [provider, subject]);
|
|
139
|
+
// Paired only in the legacy store, by an earlier SDK: the next migration copies it.
|
|
140
|
+
if (legacyBound !== undefined && String(legacyBound.user_id) !== userId) {
|
|
141
|
+
return yield* conflict(`The ${provider} account is attached to another member.`);
|
|
142
|
+
}
|
|
143
|
+
const [held] = yield* rows(`SELECT 1 FROM ${CHANNEL_IDENTITIES_FROM}
|
|
144
|
+
WHERE "i"."user_id" = $1::uuid AND "i"."provider" = $2 AND ${LIVE_CHANNEL_IDENTITY}
|
|
145
|
+
UNION ALL
|
|
146
|
+
SELECT 1 FROM ${LEGACY_IDENTITIES}
|
|
147
|
+
WHERE "user_id" = $1::uuid AND "provider" = $2 AND "revoked_at" IS NULL
|
|
148
|
+
LIMIT 1`, [userId, provider]);
|
|
149
|
+
if (held !== undefined) {
|
|
150
|
+
return yield* conflict(`The member already has a ${provider} account; revoke it before attaching another.`);
|
|
151
|
+
}
|
|
152
|
+
// A record of this account or of this member's account of the provider that the legacy store
|
|
153
|
+
// revoked or no longer holds is revoked too, freeing its keys.
|
|
154
|
+
const stale = yield* rows(`SELECT "i"."id"::text AS "id" FROM ${CHANNEL_IDENTITIES_FROM}
|
|
155
|
+
WHERE "i"."revoked_at" IS NULL AND ${CHANNEL_ACCOUNT} AND "i"."provider" = $1
|
|
156
|
+
AND ("i"."user_id" = $2::uuid OR "i"."subject" = $3)
|
|
157
|
+
AND ("a"."id" IS NULL OR "a"."revoked_at" IS NOT NULL)
|
|
158
|
+
ORDER BY "i"."id" FOR UPDATE OF "i"`, [provider, userId, subject]);
|
|
159
|
+
const at = new Date().toISOString();
|
|
160
|
+
for (const identity of stale) {
|
|
161
|
+
yield* writer.revoke(String(identity.id), at);
|
|
162
|
+
yield* revokeChannelSessions(sql, String(identity.id));
|
|
163
|
+
}
|
|
164
|
+
const created = yield* writer.create({
|
|
165
|
+
provider,
|
|
166
|
+
issuer: null,
|
|
167
|
+
subject,
|
|
168
|
+
userId,
|
|
169
|
+
origin: "attach",
|
|
170
|
+
username: description.username ?? null,
|
|
171
|
+
display: description.display ?? null,
|
|
172
|
+
});
|
|
173
|
+
// @legacy identities.legacy-stores-dual-write
|
|
174
|
+
yield* rows(`INSERT INTO ${LEGACY_IDENTITIES} ("id", "provider", "external_id", "user_id", "display", "username")
|
|
175
|
+
VALUES ($1::uuid, $2, $3, $4::uuid, $5, $6)`, [
|
|
176
|
+
String(created.id),
|
|
177
|
+
provider,
|
|
178
|
+
subject,
|
|
179
|
+
userId,
|
|
180
|
+
description.display ?? null,
|
|
181
|
+
description.username ?? null,
|
|
182
|
+
]);
|
|
183
|
+
return created;
|
|
184
|
+
}).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Revokes a member's chat account as `user_identity.revoke` does: the account stops acting for
|
|
188
|
+
* them at once, through the agent and through every external runtime, and their channel sessions
|
|
189
|
+
* end. A sign-in identity (email, SegmentStream) is not a chat account and is NotFound here; one
|
|
190
|
+
* already revoked is returned unchanged.
|
|
191
|
+
*/
|
|
192
|
+
export function revokeChannelIdentity(ontology, sql, scope, input) {
|
|
193
|
+
const rows = (statement, values = []) => sql.unsafe(statement, values);
|
|
194
|
+
const missing = new NotFound({
|
|
195
|
+
entity: UserIdentity.name,
|
|
196
|
+
id: input.id,
|
|
197
|
+
message: `No chat account ${input.id}.`,
|
|
198
|
+
});
|
|
199
|
+
return Effect.gen(function* () {
|
|
200
|
+
if (!isRecordId(input.id)) {
|
|
201
|
+
return yield* missing;
|
|
202
|
+
}
|
|
203
|
+
const [identity] = yield* rows(`SELECT "i"."id"::text AS "id", "i"."user_id"::text AS "user_id",
|
|
204
|
+
${LIVE_CHANNEL_IDENTITY} AS "live"
|
|
205
|
+
FROM ${CHANNEL_IDENTITIES_FROM}
|
|
206
|
+
WHERE "i"."id" = $1::uuid AND ${CHANNEL_ACCOUNT}
|
|
207
|
+
FOR UPDATE OF "i"`, [input.id]);
|
|
208
|
+
if (identity === undefined) {
|
|
209
|
+
return yield* missing;
|
|
210
|
+
}
|
|
211
|
+
const writer = makeIdentityWriter(ontology, sql, scope);
|
|
212
|
+
if (identity.live !== true) {
|
|
213
|
+
return yield* writer.describe(input.id, {});
|
|
214
|
+
}
|
|
215
|
+
const at = new Date().toISOString();
|
|
216
|
+
const revoked = yield* writer.revoke(input.id, at);
|
|
217
|
+
// @legacy identities.legacy-stores-dual-write
|
|
218
|
+
yield* rows(`UPDATE ${LEGACY_IDENTITIES} SET "revoked_at" = $2::timestamptz
|
|
219
|
+
WHERE "id" = $1::uuid AND "revoked_at" IS NULL`, [input.id, at]);
|
|
220
|
+
yield* revokeChannelSessions(sql, input.id);
|
|
221
|
+
return revoked;
|
|
222
|
+
}).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error)), Effect.catchIf(isSqlError, (error) => Effect.die(error)));
|
|
223
|
+
}
|
|
@@ -15,7 +15,8 @@ export declare function upsertActionName(property: string): string;
|
|
|
15
15
|
* as `generatedActionPermissions` says. The built-in User has only its member management: `invite`,
|
|
16
16
|
* `grant_roles`, `revoke_roles`, `deactivate` and `reactivate`; members are otherwise created by
|
|
17
17
|
* sign-in and services by the app or the CLI. The built-in agent chat has only `update`, for its
|
|
18
|
-
* unmanaged properties: the agent records chats and their members.
|
|
18
|
+
* unmanaged properties: the agent records chats and their members. The built-in sign-in
|
|
19
|
+
* identities have only `attach` and `revoke`, an administrator's writes of members' chat accounts.
|
|
19
20
|
*/
|
|
20
21
|
export declare function generatedActions(ontology: Ontology, entityName: string): GeneratedActions;
|
|
21
22
|
/**
|