@segmentstream/ontology 0.94.1 → 0.96.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 +52 -7
- package/dist/analyze.d.ts +15 -3
- package/dist/analyze.js +217 -5
- package/dist/authoring.js +3 -0
- package/dist/index.d.ts +8 -8
- package/dist/index.js +5 -5
- package/dist/manifest-compatibility.d.ts +7 -0
- package/dist/manifest-compatibility.js +12 -0
- package/dist/manifest.d.ts +102 -18
- package/dist/manifest.js +41 -2
- package/dist/migrate/apply.d.ts +3 -2
- package/dist/migrate/apply.js +11 -3
- package/dist/migrate/model.d.ts +60 -12
- package/dist/migrate/plan.js +9 -1
- package/dist/migrate/storage.d.ts +7 -0
- package/dist/migrate/storage.js +24 -12
- package/dist/ontology.d.ts +2 -2
- 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/member-tables.d.ts +7 -2
- package/dist/runtime/member-tables.js +18 -3
- package/dist/runtime/new-user-hook.d.ts +11 -1
- package/dist/runtime/new-user-hook.js +69 -29
- package/dist/runtime/pipeline.d.ts +2 -0
- package/dist/runtime/pipeline.js +11 -3
- package/dist/runtime/principals.d.ts +37 -3
- package/dist/runtime/principals.js +140 -36
- package/dist/runtime/resolve-agent-identity.js +43 -12
- package/dist/runtime/service-binding.js +11 -4
- 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 +20 -2
- package/dist/service/chat/envelope.js +10 -0
- package/dist/service/runtime-contract.d.ts +9 -0
- package/dist/service/schemas.d.ts +12 -0
- package/dist/sign-in.d.ts +32 -1
- package/dist/sign-in.js +12 -1
- 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
|
@@ -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
|
@@ -663,6 +663,8 @@ export const AGENT_TABLES_DDL = [
|
|
|
663
663
|
"blocked_at" timestamptz,
|
|
664
664
|
"on_new_user_completed_at" timestamptz
|
|
665
665
|
)`,
|
|
666
|
+
// A user `signUp` created holds exactly the roles sign-up granted, never `member`.
|
|
667
|
+
`ALTER TABLE "${CHANNEL_USERS_TABLE}" ADD COLUMN IF NOT EXISTS "signed_up" boolean NOT NULL DEFAULT false`,
|
|
666
668
|
`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via")
|
|
667
669
|
SELECT DISTINCT ON ("user_id") "user_id", "provider" FROM "${AGENT_IDENTITIES_TABLE}"
|
|
668
670
|
WHERE "origin" = 'provisioned' ORDER BY "user_id", "created_at", "id"
|
|
@@ -701,18 +703,13 @@ export const ACTION_ATTRIBUTION_DDL = [
|
|
|
701
703
|
"at" timestamptz NOT NULL DEFAULT now()
|
|
702
704
|
)`,
|
|
703
705
|
];
|
|
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"),
|
|
706
|
+
/**
|
|
707
|
+
* The API keys of the app's services: each names a `user` and holds the PBKDF2 hash of its secret.
|
|
708
|
+
* A key with `delegation` acts only for the member each request names, with that member's roles,
|
|
709
|
+
* never with its own user's. Idempotent: a database an earlier SDK migrated gains `delegation` on
|
|
710
|
+
* its next migration.
|
|
711
|
+
*/
|
|
712
|
+
export const API_KEYS_DDL = [
|
|
716
713
|
[
|
|
717
714
|
`CREATE TABLE IF NOT EXISTS ${quoteIdentifier(API_KEYS_TABLE)} (`,
|
|
718
715
|
` "id" uuid NOT NULL,`,
|
|
@@ -730,6 +727,21 @@ export const RUNTIME_TABLES_DDL = [
|
|
|
730
727
|
`)`,
|
|
731
728
|
].join("\n"),
|
|
732
729
|
`CREATE INDEX IF NOT EXISTS "${API_KEYS_TABLE}_user_id_idx" ON ${quoteIdentifier(API_KEYS_TABLE)} ("user_id")`,
|
|
730
|
+
`ALTER TABLE ${quoteIdentifier(API_KEYS_TABLE)} ADD COLUMN IF NOT EXISTS "delegation" boolean NOT NULL DEFAULT false`,
|
|
731
|
+
];
|
|
732
|
+
export const RUNTIME_TABLES_DDL = [
|
|
733
|
+
...FEDERATION_TABLES_DDL,
|
|
734
|
+
...ACTION_ATTRIBUTION_DDL,
|
|
735
|
+
[
|
|
736
|
+
`CREATE TABLE IF NOT EXISTS ${quoteIdentifier(USER_ROLES_TABLE)} (`,
|
|
737
|
+
` "user_id" uuid NOT NULL,`,
|
|
738
|
+
` "role" text NOT NULL,`,
|
|
739
|
+
` CONSTRAINT "${USER_ROLES_TABLE}_pkey" PRIMARY KEY ("user_id", "role"),`,
|
|
740
|
+
` CONSTRAINT "${USER_ROLES_TABLE}_user_id_fkey" FOREIGN KEY ("user_id") ` +
|
|
741
|
+
`REFERENCES ${quoteIdentifier(USER_TABLE)} ("id") ON DELETE CASCADE`,
|
|
742
|
+
`)`,
|
|
743
|
+
].join("\n"),
|
|
744
|
+
...API_KEYS_DDL,
|
|
733
745
|
...OAUTH_TABLES_DDL,
|
|
734
746
|
...AGENT_TABLES_DDL,
|
|
735
747
|
];
|
package/dist/ontology.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { AnyEntity } from "./entity.js";
|
|
|
4
4
|
import { type OntologyManifest, type WorkflowManifest } from "./manifest.js";
|
|
5
5
|
import type { ModelMetrics } from "./metric.js";
|
|
6
6
|
import type { Role } from "./role.js";
|
|
7
|
-
import type {
|
|
7
|
+
import type { ResolvedSignInOptions } from "./sign-in.js";
|
|
8
8
|
/** A checked ontology: the resolved definitions and the manifest built from them. */
|
|
9
9
|
export interface Ontology<Entities extends ReadonlyArray<AnyEntity> = ReadonlyArray<AnyEntity>, Metrics extends ModelMetrics = ModelMetrics> {
|
|
10
10
|
/** The definition as given to `defineOntology`. */
|
|
@@ -14,7 +14,7 @@ export interface Ontology<Entities extends ReadonlyArray<AnyEntity> = ReadonlyAr
|
|
|
14
14
|
/** The workspace-owned `member` role first, declared roles, then the implicit reporter when enabled. */
|
|
15
15
|
readonly roles: ReadonlyArray<Role>;
|
|
16
16
|
/** Who may become a member by signing in, with the default policy when the definition sets none. */
|
|
17
|
-
readonly signIn:
|
|
17
|
+
readonly signIn: ResolvedSignInOptions;
|
|
18
18
|
/** The connections the actions call, as `defineOntology({ connections })` lists them. */
|
|
19
19
|
readonly connections: ReadonlyArray<ResolvedConnection>;
|
|
20
20
|
/** The workflows, with wire names and their triggers' input in wire form, as the manifest lists them. */
|
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
|
/**
|
|
@@ -7,6 +7,7 @@ import { p, REFERENCE_ANNOTATION } from "../property.js";
|
|
|
7
7
|
import { isCalendarDate, isInstant } from "../query.js";
|
|
8
8
|
import { OntologyWrites } from "../runtime.js";
|
|
9
9
|
import { User } from "../user.js";
|
|
10
|
+
import { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity } from "../user-identity.js";
|
|
10
11
|
import { entityModel, ontologyModel, propertyValueSchema, } from "./model.js";
|
|
11
12
|
/** Generated actions, built once per ontology and entity. */
|
|
12
13
|
const builtActions = new WeakMap();
|
|
@@ -101,12 +102,15 @@ function valuesOf(input, omit) {
|
|
|
101
102
|
* as `generatedActionPermissions` says. The built-in User has only its member management: `invite`,
|
|
102
103
|
* `grant_roles`, `revoke_roles`, `deactivate` and `reactivate`; members are otherwise created by
|
|
103
104
|
* sign-in and services by the app or the CLI. The built-in agent chat has only `update`, for its
|
|
104
|
-
* unmanaged properties: the agent records chats and their members.
|
|
105
|
+
* unmanaged properties: the agent records chats and their members. The built-in sign-in
|
|
106
|
+
* identities have only `attach` and `revoke`, an administrator's writes of members' chat accounts.
|
|
105
107
|
*/
|
|
106
108
|
export function generatedActions(ontology, entityName) {
|
|
107
109
|
const declared = ontology.manifest.entities.find((e) => e.name === entityName);
|
|
108
|
-
// A warehouse-backed entity has no writes; one with `writes: "actions"` only authored ones.
|
|
109
|
-
|
|
110
|
+
// A warehouse-backed entity has no writes; one with `writes: "actions"` only authored ones. The
|
|
111
|
+
// built-in sign-in identities declare `writes: "actions"` too: they have only the platform's.
|
|
112
|
+
if (declared?.source !== undefined ||
|
|
113
|
+
(declared?.writes === "actions" && entityName !== UserIdentity.name)) {
|
|
110
114
|
return {};
|
|
111
115
|
}
|
|
112
116
|
const byEntity = builtActions.get(ontology) ?? new Map();
|
|
@@ -208,11 +212,75 @@ function memberActions(ontology, entity) {
|
|
|
208
212
|
}),
|
|
209
213
|
};
|
|
210
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* The identity writes of the SQL runtime that runs the action. Only `user_identity.attach` and
|
|
217
|
+
* `user_identity.revoke` reach them, and only the SQL runtime has them: any other runtime refuses.
|
|
218
|
+
*/
|
|
219
|
+
function withIdentityWrites(write) {
|
|
220
|
+
return Effect.flatMap(OntologyWrites, (runtime) => {
|
|
221
|
+
const identities = runtime.identities;
|
|
222
|
+
return identities === undefined
|
|
223
|
+
? Effect.die(new Error("Sign-in identities change only through the ontology's SQL runtime."))
|
|
224
|
+
: write(identities);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The built-in sign-in identities' platform actions: an administrator attaching a member's chat
|
|
229
|
+
* account, such as their Telegram account, and revoking one. Their permissions name the entity
|
|
230
|
+
* (`user_identity:attach`, `user_identity:revoke`), which no wildcard covers. Attaching grants no
|
|
231
|
+
* role; the member acts with exactly the roles they hold.
|
|
232
|
+
*/
|
|
233
|
+
function identityActions() {
|
|
234
|
+
const providers = Schema.Literals(ATTACHABLE_IDENTITY_PROVIDERS).annotate({
|
|
235
|
+
description: `The chat provider of the account: ${ATTACHABLE_IDENTITY_PROVIDERS.join(", ")}.`,
|
|
236
|
+
});
|
|
237
|
+
return {
|
|
238
|
+
attach: action({
|
|
239
|
+
description: "Attach a chat account, such as a Telegram account, to a member whose account you know " +
|
|
240
|
+
"is theirs, so that the app's agent, and an external agent the workspace trusts with a " +
|
|
241
|
+
"delegated API key, act for the member when the account writes. It grants no role. " +
|
|
242
|
+
"Refused when another member holds the account or the member already has an account of " +
|
|
243
|
+
"the provider; attaching the account the member holds again changes nothing.",
|
|
244
|
+
input: Schema.Struct({
|
|
245
|
+
user: p.ref(User.name, { description: "The member the account belongs to." }),
|
|
246
|
+
provider: providers,
|
|
247
|
+
subject: p.text({
|
|
248
|
+
description: "The account's id at the provider: the numeric Telegram user id, the WhatsApp " +
|
|
249
|
+
"phone number id or the Slack member id. Never a username or a phone number with " +
|
|
250
|
+
"spaces or a plus sign.",
|
|
251
|
+
}),
|
|
252
|
+
username: Schema.optionalKey(p.text({ description: "The account's username at the provider, without @." })),
|
|
253
|
+
display: Schema.optionalKey(p.text({ description: "The name the provider shows for the account." })),
|
|
254
|
+
}),
|
|
255
|
+
hints: { destructive: false, idempotent: true },
|
|
256
|
+
handler: ({ input }) => withIdentityWrites((identities) => identities.attach({
|
|
257
|
+
user: input.user,
|
|
258
|
+
provider: input.provider,
|
|
259
|
+
subject: input.subject,
|
|
260
|
+
username: input.username,
|
|
261
|
+
display: input.display,
|
|
262
|
+
})),
|
|
263
|
+
}),
|
|
264
|
+
revoke: action({
|
|
265
|
+
description: "Revoke a member's chat account: from the next message on, neither the app's agent nor " +
|
|
266
|
+
"any external agent acts for the member through it, and its channel sessions end. A " +
|
|
267
|
+
"revoked account changes nothing.",
|
|
268
|
+
input: Schema.Struct({
|
|
269
|
+
id: p.ref(UserIdentity.name, { description: "The chat account to revoke." }),
|
|
270
|
+
}),
|
|
271
|
+
hints: { destructive: true, idempotent: true },
|
|
272
|
+
handler: ({ input }) => withIdentityWrites((identities) => identities.revoke({ id: input.id })),
|
|
273
|
+
}),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
211
276
|
function buildGeneratedActions(ontology, entityName) {
|
|
212
277
|
const entity = entityModel(ontologyModel(ontology), entityName);
|
|
213
278
|
if (entity.resolved.builtIn && entity.name === User.name) {
|
|
214
279
|
return memberActions(ontology, entity);
|
|
215
280
|
}
|
|
281
|
+
if (entity.resolved.builtIn && entity.name === UserIdentity.name) {
|
|
282
|
+
return identityActions();
|
|
283
|
+
}
|
|
216
284
|
if (entity.resolved.builtIn && entity.resolved.permissions.update === undefined) {
|
|
217
285
|
return {};
|
|
218
286
|
}
|
|
@@ -2,7 +2,12 @@ import { Effect } from "effect";
|
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
3
|
/** Legacy workspace databases remain readable before their next additive migration. */
|
|
4
4
|
export declare function channelUsersAvailable(sql: SqlClient.SqlClient): Effect.Effect<boolean, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Records how a user came to be: `invite`, `email` or a channel's sign-up. The first record stays.
|
|
7
|
+
* `signedUp` marks a user `signUp` created, who never holds `member`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function recordUserCreation(sql: SqlClient.SqlClient, userId: string, via: string, signedUp?: boolean): Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
7
10
|
/** Session revocation integration point for every channel-app issuer (including Mini Apps). */
|
|
8
11
|
export declare function revokeMemberSessions(sql: SqlClient.SqlClient, userId: string): Effect.Effect<void, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
12
|
+
/** Whether a user sign-up created still waits for `onSignUp`: not completed and not blocked. */
|
|
13
|
+
export declare function signUpPending(sql: SqlClient.SqlClient, userId: string): Effect.Effect<boolean, import("effect/unstable/sql/SqlError").SqlError, never>;
|
|
@@ -9,10 +9,17 @@ export function channelUsersAvailable(sql) {
|
|
|
9
9
|
])
|
|
10
10
|
.pipe(Effect.map(([table]) => table?.present === true));
|
|
11
11
|
}
|
|
12
|
-
/**
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Records how a user came to be: `invite`, `email` or a channel's sign-up. The first record stays.
|
|
14
|
+
* `signedUp` marks a user `signUp` created, who never holds `member`.
|
|
15
|
+
*/
|
|
16
|
+
export function recordUserCreation(sql, userId, via, signedUp = false) {
|
|
14
17
|
return Effect.gen(function* () {
|
|
15
|
-
if (
|
|
18
|
+
if (signedUp) {
|
|
19
|
+
yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via", "signed_up")
|
|
20
|
+
VALUES ($1::uuid, $2, true) ON CONFLICT ("user_id") DO NOTHING`, [userId, via]);
|
|
21
|
+
}
|
|
22
|
+
else if (yield* channelUsersAvailable(sql)) {
|
|
16
23
|
yield* sql.unsafe(`INSERT INTO "${CHANNEL_USERS_TABLE}" ("user_id", "created_via") VALUES ($1::uuid, $2)
|
|
17
24
|
ON CONFLICT ("user_id") DO NOTHING`, [userId, via]);
|
|
18
25
|
}
|
|
@@ -31,3 +38,11 @@ export function revokeMemberSessions(sql, userId) {
|
|
|
31
38
|
}
|
|
32
39
|
});
|
|
33
40
|
}
|
|
41
|
+
/** Whether a user sign-up created still waits for `onSignUp`: not completed and not blocked. */
|
|
42
|
+
export function signUpPending(sql, userId) {
|
|
43
|
+
return sql
|
|
44
|
+
.unsafe(`SELECT true AS "pending" FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid
|
|
45
|
+
AND COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true'
|
|
46
|
+
AND "c"."on_new_user_completed_at" IS NULL AND "c"."blocked_at" IS NULL`, [userId])
|
|
47
|
+
.pipe(Effect.map((rows) => rows.length > 0));
|
|
48
|
+
}
|
|
@@ -2,5 +2,15 @@ import { Effect } from "effect";
|
|
|
2
2
|
import { SqlClient } from "effect/unstable/sql";
|
|
3
3
|
import type { Ontology } from "../ontology.js";
|
|
4
4
|
import type { Principal } from "../runtime.js";
|
|
5
|
-
|
|
5
|
+
import type { FederationStore } from "./federation.js";
|
|
6
|
+
/**
|
|
7
|
+
* Runs after admission commits, before a model turn or app session. True means retry pending.
|
|
8
|
+
* A user `signUp` created runs `onSignUp` with the roles they hold; a user an open
|
|
9
|
+
* `signIn.channels` created runs `onNewUser` with only `member`. Workload authority never applies.
|
|
10
|
+
*/
|
|
6
11
|
export declare function runNewUserHook(ontology: Ontology, sql: SqlClient.SqlClient, principal: Principal): Effect.Effect<boolean>;
|
|
12
|
+
/**
|
|
13
|
+
* The federation store, running a signed-up user's pending `onSignUp` once they enroll through a
|
|
14
|
+
* SegmentStream account and on each later federated request until it completes.
|
|
15
|
+
*/
|
|
16
|
+
export declare function withSignUpOnboarding(ontology: Ontology, sql: SqlClient.SqlClient, store: FederationStore): FederationStore;
|