@segmentstream/ontology 0.94.1 → 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/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
|
@@ -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
|
}
|
|
@@ -111,11 +111,22 @@ export declare function resolveWorkflowUser(ontology: Ontology, input: {
|
|
|
111
111
|
export declare function reconcileWorkflowUsers(ontology: Ontology, input: {
|
|
112
112
|
readonly workspaceId: string;
|
|
113
113
|
}): Effect.Effect<void, SqlError, SqlClient.SqlClient>;
|
|
114
|
+
/**
|
|
115
|
+
* An API key, verified: its user's principal, and whether it acts with `delegation`, only for the
|
|
116
|
+
* member each request names, instead of with that principal's roles.
|
|
117
|
+
*/
|
|
118
|
+
export interface ApiKeyCredential {
|
|
119
|
+
readonly principal: Principal;
|
|
120
|
+
readonly delegation: boolean;
|
|
121
|
+
}
|
|
114
122
|
/**
|
|
115
123
|
* The principal of an API key, with the permissions its roles have in the ontology. Unknown and
|
|
116
|
-
* revoked keys and inactive users are rejected.
|
|
124
|
+
* revoked keys and inactive users are rejected. A key with delegation resolves to its user too: the
|
|
125
|
+
* service authenticates its requests as the member they name, and refuses them otherwise.
|
|
117
126
|
*/
|
|
118
127
|
export declare function resolvePrincipalByApiKey(ontology: Ontology, key: string): Effect.Effect<Principal, PrincipalRejected, SqlClient.SqlClient>;
|
|
128
|
+
/** An API key's principal and whether it acts with delegation; see {@link resolvePrincipalByApiKey}. */
|
|
129
|
+
export declare function resolveApiKeyCredential(ontology: Ontology, key: string): Effect.Effect<ApiKeyCredential, PrincipalRejected, SqlClient.SqlClient>;
|
|
119
130
|
/**
|
|
120
131
|
* A member by user id, with the roles they hold now: whom an OAuth grant acts for. `undefined` for
|
|
121
132
|
* an unknown user, a service and an inactive member.
|
|
@@ -126,10 +137,15 @@ export interface CreatedApiKey {
|
|
|
126
137
|
/** The key itself. It is not stored and cannot be shown again. */
|
|
127
138
|
readonly key: string;
|
|
128
139
|
}
|
|
129
|
-
/**
|
|
140
|
+
/**
|
|
141
|
+
* Issues an API key for a user. With `delegation` the key acts only for the member each request
|
|
142
|
+
* names; the column is written only then, so that keys without it can still be issued on a
|
|
143
|
+
* database an earlier SDK migrated.
|
|
144
|
+
*/
|
|
130
145
|
export declare function createApiKey(input: {
|
|
131
146
|
readonly userId: string;
|
|
132
147
|
readonly label: string;
|
|
148
|
+
readonly delegation?: boolean;
|
|
133
149
|
}): Effect.Effect<CreatedApiKey, never, SqlClient.SqlClient>;
|
|
134
150
|
/** Revokes an API key. Revoking it again changes nothing. */
|
|
135
151
|
export declare function revokeApiKey(input: {
|
|
@@ -142,12 +158,15 @@ export declare function setUserRoles(ontology: Ontology, input: {
|
|
|
142
158
|
}): Effect.Effect<void, UnknownRole, SqlClient.SqlClient>;
|
|
143
159
|
/**
|
|
144
160
|
* Creates a service user with roles and a first API key, as the app or the CLI does for the
|
|
145
|
-
* website's intake key.
|
|
161
|
+
* website's intake key. With `delegation` the service holds no role and its key acts only for the
|
|
162
|
+
* member each request names, as an external agent the workspace trusts does: roles and delegation
|
|
163
|
+
* never come together, so that such a key has no authority of its own.
|
|
146
164
|
*/
|
|
147
165
|
export declare function createServiceUser(ontology: Ontology, input: {
|
|
148
166
|
readonly name: string;
|
|
149
167
|
readonly roles: ReadonlyArray<string>;
|
|
150
168
|
readonly keyLabel: string;
|
|
169
|
+
readonly delegation?: boolean;
|
|
151
170
|
}): Effect.Effect<{
|
|
152
171
|
readonly user: StoredRecord;
|
|
153
172
|
readonly apiKey: CreatedApiKey;
|
|
@@ -199,6 +218,8 @@ export interface ApiKeySummary {
|
|
|
199
218
|
readonly active: boolean;
|
|
200
219
|
};
|
|
201
220
|
readonly roles: ReadonlyArray<string>;
|
|
221
|
+
/** The key acts only for the member each request names, with that member's roles. */
|
|
222
|
+
readonly delegation: boolean;
|
|
202
223
|
}
|
|
203
224
|
/** Every API key, oldest first, revoked ones included. */
|
|
204
225
|
export declare function listApiKeys(): Effect.Effect<ReadonlyArray<ApiKeySummary>, never, SqlClient.SqlClient>;
|
|
@@ -661,9 +661,14 @@ export function reconcileWorkflowUsers(ontology, input) {
|
|
|
661
661
|
}
|
|
662
662
|
/**
|
|
663
663
|
* The principal of an API key, with the permissions its roles have in the ontology. Unknown and
|
|
664
|
-
* revoked keys and inactive users are rejected.
|
|
664
|
+
* revoked keys and inactive users are rejected. A key with delegation resolves to its user too: the
|
|
665
|
+
* service authenticates its requests as the member they name, and refuses them otherwise.
|
|
665
666
|
*/
|
|
666
667
|
export function resolvePrincipalByApiKey(ontology, key) {
|
|
668
|
+
return resolveApiKeyCredential(ontology, key).pipe(Effect.map(({ principal }) => principal));
|
|
669
|
+
}
|
|
670
|
+
/** An API key's principal and whether it acts with delegation; see {@link resolvePrincipalByApiKey}. */
|
|
671
|
+
export function resolveApiKeyCredential(ontology, key) {
|
|
667
672
|
return Effect.gen(function* () {
|
|
668
673
|
const sql = yield* SqlClient.SqlClient;
|
|
669
674
|
const unknownKey = (diagnostic) => new PrincipalRejected({
|
|
@@ -676,7 +681,8 @@ export function resolvePrincipalByApiKey(ontology, key) {
|
|
|
676
681
|
return yield* unknownKey("malformed_api_key");
|
|
677
682
|
}
|
|
678
683
|
const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."kind"::text AS "kind", "u"."active" AS "active", ` +
|
|
679
|
-
`"k"."salt" AS "salt", "k"."hash" AS "hash", "k"."revoked_at" IS NOT NULL AS "revoked" ` +
|
|
684
|
+
`"k"."salt" AS "salt", "k"."hash" AS "hash", "k"."revoked_at" IS NOT NULL AS "revoked", ` +
|
|
685
|
+
`${API_KEY_DELEGATION} AS "delegation" ` +
|
|
680
686
|
`FROM "${API_KEYS_TABLE}" AS "k" JOIN "${USER_TABLE}" AS "u" ON "u"."id" = "k"."user_id" ` +
|
|
681
687
|
`WHERE "k"."key_id" = $1::text`, [parts.keyId]);
|
|
682
688
|
// An unknown key id costs one KDF too, so that timing does not tell which key ids exist.
|
|
@@ -699,9 +705,17 @@ export function resolvePrincipalByApiKey(ontology, key) {
|
|
|
699
705
|
message: "The API key was revoked.",
|
|
700
706
|
});
|
|
701
707
|
}
|
|
702
|
-
|
|
708
|
+
const principal = yield* activePrincipal(ontology, sql, decodeUser({ id: row.id, kind: row.kind, active: row.active }));
|
|
709
|
+
return { principal, delegation: row.delegation === true };
|
|
703
710
|
}).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
|
|
704
711
|
}
|
|
712
|
+
/**
|
|
713
|
+
* Whether the API key `"k"` acts with delegation.
|
|
714
|
+
* @legacy ontology.pre-upgrade-database-tolerance
|
|
715
|
+
* Read through the row's JSON, so that a database an earlier SDK migrated, which has no such
|
|
716
|
+
* column until its next migration, reads every key as one without delegation.
|
|
717
|
+
*/
|
|
718
|
+
const API_KEY_DELEGATION = `COALESCE((to_jsonb("k") ->> 'delegation')::boolean, false)`;
|
|
705
719
|
/**
|
|
706
720
|
* A member by user id, with the roles they hold now: whom an OAuth grant acts for. `undefined` for
|
|
707
721
|
* an unknown user, a service and an inactive member.
|
|
@@ -720,7 +734,11 @@ export function resolveMemberById(ontology, userId) {
|
|
|
720
734
|
return yield* rolesOf(ontology, sql, decodeUser(row));
|
|
721
735
|
}).pipe(Effect.orDie);
|
|
722
736
|
}
|
|
723
|
-
/**
|
|
737
|
+
/**
|
|
738
|
+
* Issues an API key for a user. With `delegation` the key acts only for the member each request
|
|
739
|
+
* names; the column is written only then, so that keys without it can still be issued on a
|
|
740
|
+
* database an earlier SDK migrated.
|
|
741
|
+
*/
|
|
724
742
|
export function createApiKey(input) {
|
|
725
743
|
return Effect.gen(function* () {
|
|
726
744
|
const sql = yield* SqlClient.SqlClient;
|
|
@@ -729,9 +747,13 @@ export function createApiKey(input) {
|
|
|
729
747
|
const { keyId, secret } = parseApiKey(key);
|
|
730
748
|
const salt = randomBytes(SALT_BYTES).toString("hex");
|
|
731
749
|
const hash = yield* Effect.promise(() => hashApiKeySecret(secret, salt));
|
|
750
|
+
const delegation = input.delegation === true;
|
|
732
751
|
yield* sql.unsafe(`INSERT INTO "${API_KEYS_TABLE}" ` +
|
|
733
|
-
`("id", "user_id", "key_id", "salt", "hash", "label", "created_at"
|
|
734
|
-
|
|
752
|
+
`("id", "user_id", "key_id", "salt", "hash", "label", "created_at"` +
|
|
753
|
+
(delegation ? `, "delegation"` : "") +
|
|
754
|
+
") VALUES ($1::uuid, $2::uuid, $3::text, $4::text, $5::text, $6::text, now()" +
|
|
755
|
+
(delegation ? ", true" : "") +
|
|
756
|
+
")", [id, input.userId, keyId, salt, hash, input.label]);
|
|
735
757
|
return { id, key };
|
|
736
758
|
}).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
|
|
737
759
|
}
|
|
@@ -777,7 +799,9 @@ export function setUserRoles(ontology, input) {
|
|
|
777
799
|
}
|
|
778
800
|
/**
|
|
779
801
|
* Creates a service user with roles and a first API key, as the app or the CLI does for the
|
|
780
|
-
* website's intake key.
|
|
802
|
+
* website's intake key. With `delegation` the service holds no role and its key acts only for the
|
|
803
|
+
* member each request names, as an external agent the workspace trusts does: roles and delegation
|
|
804
|
+
* never come together, so that such a key has no authority of its own.
|
|
781
805
|
*/
|
|
782
806
|
export function createServiceUser(ontology, input) {
|
|
783
807
|
return Effect.gen(function* () {
|
|
@@ -788,8 +812,15 @@ export function createServiceUser(ontology, input) {
|
|
|
788
812
|
const user = yield* runtime
|
|
789
813
|
.create({ entity: "user", values: { name: input.name, kind: "service" } })
|
|
790
814
|
.pipe(Effect.orDie);
|
|
815
|
+
if (input.delegation === true && input.roles.length > 0) {
|
|
816
|
+
return yield* Effect.die(new Error("A key with delegation acts with its member's roles and holds none of its own."));
|
|
817
|
+
}
|
|
791
818
|
yield* setUserRoles(ontology, { userId: user.id, roles: input.roles });
|
|
792
|
-
const apiKey = yield* createApiKey({
|
|
819
|
+
const apiKey = yield* createApiKey({
|
|
820
|
+
userId: user.id,
|
|
821
|
+
label: input.keyLabel,
|
|
822
|
+
...(input.delegation === true ? { delegation: true } : {}),
|
|
823
|
+
});
|
|
793
824
|
return { user, apiKey };
|
|
794
825
|
}));
|
|
795
826
|
}).pipe(Effect.catchIf(isSqlError, (error) => Effect.die(error)));
|
|
@@ -872,6 +903,7 @@ const ApiKeyRow = Schema.Struct({
|
|
|
872
903
|
user_name: Schema.String,
|
|
873
904
|
user_active: Schema.Boolean,
|
|
874
905
|
roles: Schema.Array(Schema.String),
|
|
906
|
+
delegation: Schema.Boolean,
|
|
875
907
|
});
|
|
876
908
|
const decodeApiKeyRow = Schema.decodeUnknownSync(ApiKeyRow);
|
|
877
909
|
function apiKeySummary(raw) {
|
|
@@ -884,6 +916,7 @@ function apiKeySummary(raw) {
|
|
|
884
916
|
revokedAt: row.revoked_at ?? undefined,
|
|
885
917
|
user: { id: row.user_id, name: row.user_name, active: row.user_active },
|
|
886
918
|
roles: row.roles.filter((assigned) => toSnakeCase(assigned) !== FEEDBACK_REPORTER_ROLE),
|
|
919
|
+
delegation: row.delegation,
|
|
887
920
|
};
|
|
888
921
|
}
|
|
889
922
|
/** The roles assigned to the user `"u"`, sorted, as one text array. */
|
|
@@ -894,6 +927,7 @@ const API_KEY_COLUMNS = `"k"."id"::text AS "id", "k"."key_id" AS "key_id", "k"."
|
|
|
894
927
|
`to_char("k"."created_at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "created_at", ` +
|
|
895
928
|
`to_char("k"."revoked_at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "revoked_at", ` +
|
|
896
929
|
`"u"."id"::text AS "user_id", "u"."name" AS "user_name", "u"."active" AS "user_active", ` +
|
|
930
|
+
`${API_KEY_DELEGATION} AS "delegation", ` +
|
|
897
931
|
ROLES_OF_USER;
|
|
898
932
|
const API_KEY_FROM = `FROM "${API_KEYS_TABLE}" AS "k" JOIN "${USER_TABLE}" AS "u" ON "u"."id" = "k"."user_id"`;
|
|
899
933
|
/** Every API key, oldest first, revoked ones included. */
|
|
@@ -20,7 +20,7 @@ import { sqlChannelSessionStore } from "./channel-sessions.js";
|
|
|
20
20
|
import { sqlOAuthStore } from "./oauth.js";
|
|
21
21
|
import { sqlFederationStore } from "./federation.js";
|
|
22
22
|
import { runAction } from "./pipeline.js";
|
|
23
|
-
import { checkSignIn, resolvePrincipalByApiKey, resolvePrincipalByIdentity, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
|
|
23
|
+
import { checkSignIn, resolveApiKeyCredential, resolvePrincipalByApiKey, resolvePrincipalByIdentity, resolvePipelineWorker, resolveHookService, resolveWorkflowUser, } from "./principals.js";
|
|
24
24
|
import { postgresTls } from "./postgres-tls.js";
|
|
25
25
|
import { makeOntologyRuntime } from "./sql-runtime.js";
|
|
26
26
|
import { NEON_AUTH_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, } from "./user-identity-sql.js";
|
|
@@ -221,6 +221,7 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
|
|
|
221
221
|
? Effect.succeed({ allowed: false })
|
|
222
222
|
: withSql(checkSignIn(ontology, email)),
|
|
223
223
|
resolveApiKey: (key) => withSql(resolvePrincipalByApiKey(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
|
|
224
|
+
resolveApiKeyCredential: (key) => withSql(resolveApiKeyCredential(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
|
|
224
225
|
appliedHash: readCatalog({ sql }).pipe(Effect.map((manifest) => manifest?.hash), Effect.orDie),
|
|
225
226
|
replicationEnabled: Effect.gen(function* () {
|
|
226
227
|
const [presence] = yield* sql.unsafe("SELECT to_regclass('_ontology_replication') IS NOT NULL AS present");
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
2
|
import type { SqlClient } from "effect/unstable/sql";
|
|
3
3
|
import { type SqlError } from "effect/unstable/sql/SqlError";
|
|
4
|
-
import { Conflict, type NotFound } from "../errors.js";
|
|
4
|
+
import { ActionRejected, Conflict, type NotFound } from "../errors.js";
|
|
5
5
|
import type { Ontology } from "../ontology.js";
|
|
6
6
|
import type { Query, QueryResult } from "../query.js";
|
|
7
7
|
import type { OntologyRuntimeService, StoredRecord, StoredValues } from "../runtime.js";
|
|
8
|
+
import { type AttachIdentityInput } from "./channel-identity-admin.js";
|
|
8
9
|
import { type BatchOperation } from "./batch.js";
|
|
9
10
|
import { InvalidQuery, UnknownRole } from "./errors.js";
|
|
10
11
|
import type { Edit, HistoryEntry, HistoryScope } from "./history.js";
|
|
@@ -103,6 +104,18 @@ export interface SqlOntologyRuntime extends OntologyRuntimeService {
|
|
|
103
104
|
readonly active: boolean;
|
|
104
105
|
}) => Effect.Effect<StoredRecord, NotFound>;
|
|
105
106
|
};
|
|
107
|
+
/**
|
|
108
|
+
* The writes behind the built-in `user_identity.attach` and `user_identity.revoke`: an
|
|
109
|
+
* administrator attaching a member's chat account and revoking one. Only those two actions run
|
|
110
|
+
* them; anything else that reaches them is a defect, so that no other action, handler or
|
|
111
|
+
* workflow binds an account to a member.
|
|
112
|
+
*/
|
|
113
|
+
readonly identities: {
|
|
114
|
+
readonly attach: (input: AttachIdentityInput) => Effect.Effect<StoredRecord, ActionRejected | Conflict | NotFound>;
|
|
115
|
+
readonly revoke: (input: {
|
|
116
|
+
readonly id: string;
|
|
117
|
+
}) => Effect.Effect<StoredRecord, NotFound>;
|
|
118
|
+
};
|
|
106
119
|
}
|
|
107
120
|
/** A unique violation becomes Conflict, naming the property when the index covers one column. */
|
|
108
121
|
export declare function uniqueConflict(entity: EntityModel, error: SqlError, batch?: {
|
|
@@ -5,6 +5,7 @@ import { ActionRejected, Conflict } from "../errors.js";
|
|
|
5
5
|
import { toSnakeCase } from "../names.js";
|
|
6
6
|
import { User } from "../user.js";
|
|
7
7
|
import { UserIdentity } from "../user-identity.js";
|
|
8
|
+
import { ATTACH_IDENTITY_ACTION, attachChannelIdentity, REVOKE_IDENTITY_ACTION, revokeChannelIdentity, } from "./channel-identity-admin.js";
|
|
8
9
|
import { ACTION_MAX_BATCH_ROWS, BATCH_MAX_BYTES, BATCH_MAX_ROWS, batchInputBytes, executeBatch, planBatch, } from "./batch.js";
|
|
9
10
|
import { logBatchConflict } from "./batch-diagnostics.js";
|
|
10
11
|
import { runMetricQuery } from "./metric-query.js";
|
|
@@ -269,6 +270,10 @@ export function makeOntologyRuntime(ontology, sql, scope) {
|
|
|
269
270
|
outcome: Exit.isSuccess(exit) ? "success" : "failure",
|
|
270
271
|
}))));
|
|
271
272
|
});
|
|
273
|
+
// Sign-in identities change only through the platform; these two are its actions' writes.
|
|
274
|
+
const identityAction = (action, operation) => scope?.action === action && scope.principalId !== null
|
|
275
|
+
? operation(scope)
|
|
276
|
+
: Effect.die(new Error(`Sign-in identities change only through ${action}, never in another action.`));
|
|
272
277
|
const declaredRoles = ontology.roles.map((candidate) => candidate.name);
|
|
273
278
|
const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles }, entity));
|
|
274
279
|
const members = {
|
|
@@ -358,5 +363,9 @@ export function makeOntologyRuntime(ontology, sql, scope) {
|
|
|
358
363
|
setUserActive: members.setActive,
|
|
359
364
|
sendUserSignInLink: (input) => memberWrite((context, entity) => queueSignInEmail(context, entity, ontology.manifest.emails ?? {}, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error)), Effect.flatMap((queued) => Effect.sync(() => scope?.onSignInEmail?.(queued)))),
|
|
360
365
|
members,
|
|
366
|
+
identities: {
|
|
367
|
+
attach: (input) => identityAction(ATTACH_IDENTITY_ACTION, (actionScope) => attachChannelIdentity(ontology, sql, actionScope, input)),
|
|
368
|
+
revoke: (input) => identityAction(REVOKE_IDENTITY_ACTION, (actionScope) => revokeChannelIdentity(ontology, sql, actionScope, input)),
|
|
369
|
+
},
|
|
361
370
|
};
|
|
362
371
|
}
|
|
@@ -23,13 +23,15 @@ export interface IdentityCreate extends IdentityAccount {
|
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
25
|
* The platform's writes of `user_identity`: each runs in its own savepoint of the caller's
|
|
26
|
-
* transaction and records history under `scope`, without a principal
|
|
27
|
-
*
|
|
28
|
-
*
|
|
26
|
+
* transaction and records history under `scope`, without a principal unless `scope` names the
|
|
27
|
+
* administrator whose `user_identity` action it runs. Only these writes change the entity; the
|
|
28
|
+
* general runtime refuses to. They change `user_identity` alone: callers write the legacy stores
|
|
29
|
+
* beside them.
|
|
29
30
|
*/
|
|
30
31
|
export declare function makeIdentityWriter(ontology: Ontology, sql: SqlClient.SqlClient, scope: {
|
|
31
32
|
readonly action: string;
|
|
32
33
|
readonly actionId: string;
|
|
34
|
+
readonly principalId?: string | null;
|
|
33
35
|
}): {
|
|
34
36
|
/** Creates a live identity; Conflict when its account or member key is held. */
|
|
35
37
|
create: (input: IdentityCreate) => Effect.Effect<StoredRecord, Conflict | NotFound>;
|
|
@@ -24,9 +24,10 @@ export function userIdentitiesAvailable(sql) {
|
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
26
|
* The platform's writes of `user_identity`: each runs in its own savepoint of the caller's
|
|
27
|
-
* transaction and records history under `scope`, without a principal
|
|
28
|
-
*
|
|
29
|
-
*
|
|
27
|
+
* transaction and records history under `scope`, without a principal unless `scope` names the
|
|
28
|
+
* administrator whose `user_identity` action it runs. Only these writes change the entity; the
|
|
29
|
+
* general runtime refuses to. They change `user_identity` alone: callers write the legacy stores
|
|
30
|
+
* beside them.
|
|
30
31
|
*/
|
|
31
32
|
export function makeIdentityWriter(ontology, sql, scope) {
|
|
32
33
|
const model = ontologyModel(ontology);
|
|
@@ -34,7 +35,11 @@ export function makeIdentityWriter(ontology, sql, scope) {
|
|
|
34
35
|
const client = sql.withoutTransforms();
|
|
35
36
|
const context = () => ({
|
|
36
37
|
model,
|
|
37
|
-
scope: {
|
|
38
|
+
scope: {
|
|
39
|
+
action: scope.action,
|
|
40
|
+
actionId: scope.actionId,
|
|
41
|
+
principalId: scope.principalId ?? null,
|
|
42
|
+
},
|
|
38
43
|
edits: [],
|
|
39
44
|
run: (text, params) => client.unsafe(text, params.values),
|
|
40
45
|
});
|
|
@@ -17,7 +17,10 @@ export declare const OIDC_PROVIDER = "oidc";
|
|
|
17
17
|
export declare const LEGACY_OIDC_PREFIX = "oidc:";
|
|
18
18
|
/** Origins of the identities a member signs in with, which the member's user columns mirror. */
|
|
19
19
|
export declare const SIGN_IN_ORIGINS: ReadonlyArray<UserIdentityOrigin>;
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Origins of channel accounts, which `_agent_identities` mirrors with the same ids: paired by the
|
|
22
|
+
* member, created by an open channel, or attached by an administrator.
|
|
23
|
+
*/
|
|
21
24
|
export declare const CHANNEL_ORIGINS: ReadonlyArray<UserIdentityOrigin>;
|
|
22
25
|
/** `origin IN (…)` of sign-in identities, for SQL on the alias `i`. */
|
|
23
26
|
export declare const SIGN_IN_ORIGIN_SQL: string;
|
|
@@ -17,8 +17,11 @@ export const OIDC_PROVIDER = "oidc";
|
|
|
17
17
|
export const LEGACY_OIDC_PREFIX = "oidc:";
|
|
18
18
|
/** Origins of the identities a member signs in with, which the member's user columns mirror. */
|
|
19
19
|
export const SIGN_IN_ORIGINS = ["invite", "sign_in", "link"];
|
|
20
|
-
/**
|
|
21
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Origins of channel accounts, which `_agent_identities` mirrors with the same ids: paired by the
|
|
22
|
+
* member, created by an open channel, or attached by an administrator.
|
|
23
|
+
*/
|
|
24
|
+
export const CHANNEL_ORIGINS = ["pairing", "channel", "attach"];
|
|
22
25
|
const originList = (origins) => `(${origins.map((origin) => `'${origin}'`).join(", ")})`;
|
|
23
26
|
/** `origin IN (…)` of sign-in identities, for SQL on the alias `i`. */
|
|
24
27
|
export const SIGN_IN_ORIGIN_SQL = originList(SIGN_IN_ORIGINS);
|
package/dist/runtime-source.d.ts
CHANGED
|
@@ -8,6 +8,12 @@ export declare const RuntimeSource: Schema.Union<readonly [Schema.Struct<{
|
|
|
8
8
|
readonly reply_to_message_id: Schema.optionalKey<Schema.String>;
|
|
9
9
|
readonly callback_query_id: Schema.optionalKey<Schema.String>;
|
|
10
10
|
readonly sender: Schema.optionalKey<Schema.String>;
|
|
11
|
+
readonly location: Schema.optionalKey<Schema.Struct<{
|
|
12
|
+
readonly latitude: Schema.Number;
|
|
13
|
+
readonly longitude: Schema.Number;
|
|
14
|
+
readonly horizontal_accuracy: Schema.optionalKey<Schema.Number>;
|
|
15
|
+
readonly live_period: Schema.optionalKey<Schema.Int>;
|
|
16
|
+
}>>;
|
|
11
17
|
readonly attachments: Schema.optionalKey<Schema.$Array<Schema.Struct<{
|
|
12
18
|
readonly file_id: Schema.String;
|
|
13
19
|
readonly file_unique_id: Schema.optionalKey<Schema.String>;
|
package/dist/runtime-source.js
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
const Id = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
|
|
3
|
+
/**
|
|
4
|
+
* The location a Telegram message shared, as the Bot API sends it: a live location's latest update
|
|
5
|
+
* or a pinned point. Only the runtime that received the message reports it, never a model.
|
|
6
|
+
*/
|
|
7
|
+
const TelegramLocation = Schema.Struct({
|
|
8
|
+
latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
|
|
9
|
+
longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
|
|
10
|
+
horizontal_accuracy: Schema.optionalKey(Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1500 }))),
|
|
11
|
+
live_period: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
|
12
|
+
});
|
|
3
13
|
/** A Telegram chat, with the references Telegram's own actions and attachments use. */
|
|
4
14
|
const TelegramRuntimeSource = Schema.Struct({
|
|
5
15
|
provider: Schema.Literal("telegram"),
|
|
@@ -9,6 +19,7 @@ const TelegramRuntimeSource = Schema.Struct({
|
|
|
9
19
|
reply_to_message_id: Schema.optionalKey(Id),
|
|
10
20
|
callback_query_id: Schema.optionalKey(Id),
|
|
11
21
|
sender: Schema.optionalKey(Id),
|
|
22
|
+
location: Schema.optionalKey(TelegramLocation),
|
|
12
23
|
attachments: Schema.optionalKey(Schema.Array(Schema.Struct({
|
|
13
24
|
file_id: Id,
|
|
14
25
|
file_unique_id: Schema.optionalKey(Id),
|
|
@@ -117,6 +117,9 @@ export function attachmentsLayer(options) {
|
|
|
117
117
|
agents,
|
|
118
118
|
verify: verifyRuntime,
|
|
119
119
|
allowUnpairedMember: true,
|
|
120
|
+
...(backend.resolveApiKeyCredential === undefined
|
|
121
|
+
? {}
|
|
122
|
+
: { resolveApiKey: backend.resolveApiKeyCredential }),
|
|
120
123
|
});
|
|
121
124
|
return authenticated.ok
|
|
122
125
|
? yield* answer(request, authenticated.caller, attachments)
|
|
@@ -171,6 +174,7 @@ export function attachmentsLayer(options) {
|
|
|
171
174
|
const metadata = yield* consumeChatEnvelope(promotion._meta ?? {}, {
|
|
172
175
|
kind: "runtime",
|
|
173
176
|
subjectId: caller.principal.id,
|
|
177
|
+
...(caller.delegatedBy === undefined ? {} : { delegatedBy: caller.delegatedBy }),
|
|
174
178
|
});
|
|
175
179
|
const attachmentId = yield* idOf;
|
|
176
180
|
const envelopeSource = metadata.envelope?.source;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
1
|
+
import { Effect, Redacted } from "effect";
|
|
2
2
|
import { HttpServerRequest } from "effect/unstable/http";
|
|
3
3
|
import type { AttachmentCaller } from "../../storage/attachments.js";
|
|
4
4
|
import { RequestId } from "../errors.js";
|
|
5
|
-
import type { AgentStore } from "../runtime-contract.js";
|
|
5
|
+
import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
|
|
6
6
|
import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
7
7
|
export declare const CONVERSATION_HEADER = "x-segmentstream-agent-conversation";
|
|
8
8
|
export declare const SESSION_HEADER = "x-segmentstream-agent-session";
|
|
@@ -13,10 +13,82 @@ export declare function authenticateAgentCaller(input: {
|
|
|
13
13
|
readonly verify: RuntimeTokenVerifier;
|
|
14
14
|
/** Temporary attachments authorize active members against the chat registry, without a pairing. */
|
|
15
15
|
readonly allowUnpairedMember?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Resolves `ssk_` keys, so that an external runtime holding an API key with delegation reaches
|
|
18
|
+
* these routes for a member with a live account of the provider it names.
|
|
19
|
+
*/
|
|
20
|
+
readonly resolveApiKey?: ApiKeyCredentialResolver;
|
|
16
21
|
}): Effect.Effect<{
|
|
17
22
|
readonly ok: false;
|
|
18
23
|
readonly response: import("effect/unstable/http/HttpServerResponse").HttpServerResponse;
|
|
19
24
|
} | {
|
|
20
25
|
readonly ok: true;
|
|
21
26
|
readonly caller: AttachmentCaller;
|
|
27
|
+
readonly response?: undefined;
|
|
22
28
|
}, never, RequestId | HttpServerRequest.ParsedSearchParams>;
|
|
29
|
+
/** Resolves an `ssk_` key to its user and whether it acts with delegation. */
|
|
30
|
+
export type ApiKeyCredentialResolver = NonNullable<OntologyBackend["Service"]["resolveApiKeyCredential"]>;
|
|
31
|
+
/**
|
|
32
|
+
* The member an external runtime with an API key with delegation acts for on an agent route: the
|
|
33
|
+
* member `X-SegmentStream-Act-As` names, who must be active and hold a live account of the provider
|
|
34
|
+
* `X-SegmentStream-Identity-Provider` names, even where the app's own agent needs no pairing. An
|
|
35
|
+
* ordinary API key, and a task's secret, are refused.
|
|
36
|
+
*/
|
|
37
|
+
export declare function delegatedAgentMember(request: HttpServerRequest.HttpServerRequest, agents: AgentStore, resolveApiKey: ApiKeyCredentialResolver, bearer: Redacted.Redacted<string>): Effect.Effect<{
|
|
38
|
+
readonly status: "rejected";
|
|
39
|
+
readonly detail?: undefined;
|
|
40
|
+
readonly member?: undefined;
|
|
41
|
+
client?: undefined;
|
|
42
|
+
} | {
|
|
43
|
+
readonly status: "refused";
|
|
44
|
+
readonly detail: string;
|
|
45
|
+
readonly member?: undefined;
|
|
46
|
+
client?: undefined;
|
|
47
|
+
} | {
|
|
48
|
+
readonly status: "member";
|
|
49
|
+
readonly member: {
|
|
50
|
+
authenticatedVia: string;
|
|
51
|
+
execution?: import("../../index.js").WorkloadExecution;
|
|
52
|
+
workflow?: {
|
|
53
|
+
readonly name: string;
|
|
54
|
+
readonly subject: string;
|
|
55
|
+
};
|
|
56
|
+
id: string;
|
|
57
|
+
kind: "member" | "service";
|
|
58
|
+
roles: ReadonlyArray<string>;
|
|
59
|
+
permissions: ReadonlyArray<string>;
|
|
60
|
+
scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
|
|
61
|
+
};
|
|
62
|
+
readonly client: {
|
|
63
|
+
readonly id: string;
|
|
64
|
+
readonly account: {
|
|
65
|
+
provider: string;
|
|
66
|
+
subject: string;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
readonly detail?: undefined;
|
|
70
|
+
}, never, never>;
|
|
71
|
+
/**
|
|
72
|
+
* The active, unblocked member an API key with delegation acts for, with their roles now and
|
|
73
|
+
* `authenticatedVia` the provider, and the live chat account of that provider it acts through;
|
|
74
|
+
* `undefined` for anyone else.
|
|
75
|
+
*/
|
|
76
|
+
export declare function delegatedAccount(agents: AgentStore, actAs: string, provider: string): Effect.Effect<{
|
|
77
|
+
member: {
|
|
78
|
+
authenticatedVia: string;
|
|
79
|
+
execution?: import("../../index.js").WorkloadExecution;
|
|
80
|
+
workflow?: {
|
|
81
|
+
readonly name: string;
|
|
82
|
+
readonly subject: string;
|
|
83
|
+
};
|
|
84
|
+
id: string;
|
|
85
|
+
kind: "member" | "service";
|
|
86
|
+
roles: ReadonlyArray<string>;
|
|
87
|
+
permissions: ReadonlyArray<string>;
|
|
88
|
+
scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
|
|
89
|
+
};
|
|
90
|
+
account: {
|
|
91
|
+
provider: string;
|
|
92
|
+
subject: string;
|
|
93
|
+
};
|
|
94
|
+
} | undefined, never, never>;
|