@segmentstream/ontology 0.189.1 → 0.190.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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.190.0
4
+
5
+ Let a linked member authorize source reads for selected workspaces in a private conversation, with an expiry and revocation.
6
+
3
7
  ## 0.189.1
4
8
 
5
9
  `segmentstream-ontology check` first compares its own release with the one the component's
package/dist/analyze.js CHANGED
@@ -3141,7 +3141,7 @@ function ownMembers(candidate, entitiesByName) {
3141
3141
  * The verbs each entity has: `read`, its generated actions, and what its actions require. The
3142
3142
  * built-in user also has its member management verbs, and the built-in sign-in identities their
3143
3143
  * attach and revoke, which roles may grant. The built-in `workspace_source`, which is no entity,
3144
- * has `read` only, and the built-in `agent_tool`, no entity either, the agent's own tools.
3144
+ * has `read` and `connect`, and the built-in `agent_tool`, no entity either, the agent's own tools.
3145
3145
  */
3146
3146
  function knownVerbs(entities, toolsets = []) {
3147
3147
  const verbs = new Map();
@@ -3178,7 +3178,7 @@ function knownVerbs(entities, toolsets = []) {
3178
3178
  }
3179
3179
  }
3180
3180
  // Last, so that an entity or a toolset of the name, which check refuses, adds no verb to it.
3181
- verbs.set(WORKSPACE_SOURCE, new Set([READ_VERB]));
3181
+ verbs.set(WORKSPACE_SOURCE, new Set([READ_VERB, "connect"]));
3182
3182
  verbs.set(AGENT_TOOL, new Set(AGENT_TOOL_VERBS));
3183
3183
  return verbs;
3184
3184
  }
@@ -3741,9 +3741,8 @@ function checkScope(input) {
3741
3741
  "permission by name, such as staff_member:update, or list the wildcard as a string.");
3742
3742
  return;
3743
3743
  }
3744
- if (parsed.entity === WORKSPACE_SOURCE && parsed.verb === READ_VERB) {
3745
- report("invalid-scope", path, `${permission} reads the workspace's code, which has no records to scope; list ` +
3746
- `${WORKSPACE_SOURCE_PERMISSION} as a string in the roles that may read the code.`);
3744
+ if (parsed.entity === WORKSPACE_SOURCE) {
3745
+ report("invalid-scope", path, `${permission} has no records to scope; grant it as a string to the roles that may use it.`);
3747
3746
  return;
3748
3747
  }
3749
3748
  if (parsed.entity === AGENT_TOOL && verbs.get(AGENT_TOOL)?.has(parsed.verb) === true) {
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export { check, defineOntology } from "./ontology.js";
33
33
  export { webhookDeliveryJsonSchema } from "./analyze.js";
34
34
  export { webhookSigningKey, webhookSigningSecret, webhookToken, webhookTokenMatches, webhookUrl, WebhookUrlUnavailable, WEBHOOK_ORIGIN_VARIABLE, WEBHOOK_SIGNING_CONTEXT, WEBHOOK_TOKEN_CONTEXT, } from "./webhook-token.js";
35
35
  export type { Ontology } from "./ontology.js";
36
- export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, 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, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
36
+ export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, 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, WORKSPACE_SOURCE_PERMISSION, WORKSPACE_SOURCE_CONNECT, } from "./permissions.js";
37
37
  export type { AgentToolVerb, ParsedPermission, PermissionHolder, RolePermissions, ScopedPermission, ScopeFilter, ScopeValue, ScopeWhere, UserMemberVerb, } from "./permissions.js";
38
38
  export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
39
39
  export type { AnyProperty, NumberOptions, Property, PropertyDefinition, PropertyOf, PropertyOptions, BlobOptions, ListOptions, PropertyType, ReferenceOptions, SelectOption, SelectOptionInput, TextOptions, } from "./property.js";
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire
19
19
  export { check, defineOntology } from "./ontology.js";
20
20
  export { webhookDeliveryJsonSchema } from "./analyze.js";
21
21
  export { webhookSigningKey, webhookSigningSecret, webhookToken, webhookTokenMatches, webhookUrl, WebhookUrlUnavailable, WEBHOOK_ORIGIN_VARIABLE, WEBHOOK_SIGNING_CONTEXT, WEBHOOK_TOKEN_CONTEXT, } from "./webhook-token.js";
22
- export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, 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, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
22
+ export { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, 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, WORKSPACE_SOURCE_PERMISSION, WORKSPACE_SOURCE_CONNECT, } from "./permissions.js";
23
23
  export { p, PROPERTY_TYPES, propertyDefinition } from "./property.js";
24
24
  export { ON_DELETE, rel } from "./relationship.js";
25
25
  export { renderCatalog } from "./render.js";
@@ -28,14 +28,15 @@ export declare const READ_VERB = "read";
28
28
  export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
29
29
  /**
30
30
  * The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
31
- * refuses an entity or a toolset of this name, and any verb of it but `read`.
31
+ * refuses an entity or a toolset of this name, and any verb of it but `read` or `connect`.
32
32
  */
33
33
  export declare const WORKSPACE_SOURCE = "workspace_source";
34
34
  /**
35
- * Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
36
- * member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
35
+ * Reading the workspace's deployed code, through the agent's list, search and read tools. Only a role that names it grants it.
37
36
  */
38
37
  export declare const WORKSPACE_SOURCE_PERMISSION = "workspace_source:read";
38
+ /** Use source access that this member granted to the receiving workspace. */
39
+ export declare const WORKSPACE_SOURCE_CONNECT = "workspace_source:connect";
39
40
  /**
40
41
  * The built-in permissions' entity for the tools the app's agent has of its own, beside the
41
42
  * ontology's: `agent_tool:<tool>`. It names no entity: `check` refuses an entity or a toolset of
@@ -36,14 +36,15 @@ export const EXPLICIT_GRANT_ENTITIES = new Set([
36
36
  ]);
37
37
  /**
38
38
  * The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
39
- * refuses an entity or a toolset of this name, and any verb of it but `read`.
39
+ * refuses an entity or a toolset of this name, and any verb of it but `read` or `connect`.
40
40
  */
41
41
  export const WORKSPACE_SOURCE = "workspace_source";
42
42
  /**
43
- * Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
44
- * member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
43
+ * Reading the workspace's deployed code, through the agent's list, search and read tools. Only a role that names it grants it.
45
44
  */
46
45
  export const WORKSPACE_SOURCE_PERMISSION = `${WORKSPACE_SOURCE}:${READ_VERB}`;
46
+ /** Use source access that this member granted to the receiving workspace. */
47
+ export const WORKSPACE_SOURCE_CONNECT = `${WORKSPACE_SOURCE}:connect`;
47
48
  /**
48
49
  * The built-in permissions' entity for the tools the app's agent has of its own, beside the
49
50
  * ontology's: `agent_tool:<tool>`. It names no entity: `check` refuses an entity or a toolset of
@@ -28,7 +28,7 @@ import { ACTION_TRANSACTION_LIMITS, ActionTransactions } from "./action-transact
28
28
  import { actionTransaction } from "./action-deadlocks.js";
29
29
  import { canonicalInstant } from "./records.js";
30
30
  import { actionTriggers, evaluateTriggers, insertStarts, startCommitted, WorkflowStarter, } from "./workflow-starts.js";
31
- import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
31
+ import { liveSignInIdentities, CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
32
32
  const PAIRINGS = `"${AGENT_PAIRINGS_TABLE}"`;
33
33
  /** The legacy channel accounts, written beside `user_identity` for earlier SDKs. */
34
34
  const LEGACY_IDENTITIES = `"${AGENT_IDENTITIES_TABLE}"`;
@@ -546,6 +546,10 @@ export function sqlAgentStore(ontology, sql) {
546
546
  `ORDER BY ${REVOKED_AT} IS NOT NULL, ${REVOKED_AT} DESC`,
547
547
  `LIMIT 1`,
548
548
  ].join("\n"), [provider, externalId]).pipe(Effect.map(([row]) => (row === undefined ? undefined : identityOf(row)))),
549
+ segmentStreamSubject: (userId, issuer) => liveSignInIdentities(sql, userId).pipe(Effect.map((rows) => {
550
+ const identities = rows.filter((row) => row.provider === "oidc" && row.issuer === issuer);
551
+ return identities.length === 1 ? identities[0].subject : undefined;
552
+ }), Effect.orDie),
549
553
  listIdentities: (userId) => isRecordId(userId)
550
554
  ? rows([
551
555
  `SELECT ${IDENTITY_COLUMNS}`,
@@ -10,6 +10,10 @@ export interface WorkspaceSourceEnvironment {
10
10
  readonly segmentstreamUrl: string;
11
11
  readonly workspaceId: string;
12
12
  readonly organizationId: string;
13
+ readonly oidc?: {
14
+ readonly issuer: string;
15
+ readonly clientId: string;
16
+ };
13
17
  }
14
18
  /**
15
19
  * The agent's source endpoint rechecks the current paired member's explicit permission for every
@@ -1,6 +1,6 @@
1
1
  import { Effect, Layer, Result } from "effect";
2
2
  import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
3
- import { isAllowed, WORKSPACE_SOURCE_PERMISSION } from "../../permissions.js";
3
+ import { isAllowed, WORKSPACE_SOURCE_CONNECT, WORKSPACE_SOURCE_PERMISSION, } from "../../permissions.js";
4
4
  import { RequestId, errorBodyForWire } from "../errors.js";
5
5
  import { describeError } from "../metric-query-platform.js";
6
6
  import { identityToken } from "../operations.js";
@@ -20,7 +20,7 @@ function refusal(status, error, detail, requestId) {
20
20
  function fetchQuery(input) {
21
21
  const { environment, token, member, requestId } = input;
22
22
  const url = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
23
- `${encodeURIComponent(environment.workspaceId)}/ontology/source/query`;
23
+ `${encodeURIComponent(environment.workspaceId)}/ontology/source/${input.delegated ? "authorized" : "query"}`;
24
24
  return Effect.tryPromise({
25
25
  try: async (signal) => {
26
26
  const response = await input.fetch(url, {
@@ -57,7 +57,7 @@ export function workspaceSourceLayer(options) {
57
57
  if (agents === undefined || verify === undefined) {
58
58
  return;
59
59
  }
60
- const query = (request) => Effect.gen(function* () {
60
+ const query = (request, delegated = false) => Effect.gen(function* () {
61
61
  const requestId = yield* RequestId;
62
62
  const authenticated = yield* authenticateAgentRuntimeMember({ request, agents, verify });
63
63
  if (!authenticated.ok) {
@@ -67,8 +67,9 @@ export function workspaceSourceLayer(options) {
67
67
  if (member === undefined) {
68
68
  return refusal(403, "permission_denied", "The member is inactive or has not paired with the agent.", requestId);
69
69
  }
70
- if (!isAllowed(WORKSPACE_SOURCE_PERMISSION, member)) {
71
- return refusal(403, "permission_denied", `${WORKSPACE_SOURCE_PERMISSION} is required.`, requestId);
70
+ const permission = delegated ? WORKSPACE_SOURCE_CONNECT : WORKSPACE_SOURCE_PERMISSION;
71
+ if (!isAllowed(permission, member)) {
72
+ return refusal(403, "permission_denied", `${permission} is required.`, requestId);
72
73
  }
73
74
  const token = identityToken(request);
74
75
  if (token === undefined || token === "") {
@@ -79,12 +80,42 @@ export function workspaceSourceLayer(options) {
79
80
  if (Result.isFailure(input) || !input.success || input.success.length > 8192) {
80
81
  return refusal(400, "invalid_request", "Invalid source query.", requestId);
81
82
  }
83
+ let queryBody = input.success;
84
+ let manageUrl;
85
+ if (delegated) {
86
+ const oidc = options.environment.oidc;
87
+ const subject = oidc && agents.segmentStreamSubject
88
+ ? yield* agents.segmentStreamSubject(member.id, oidc.issuer)
89
+ : undefined;
90
+ if (!oidc || !subject) {
91
+ return refusal(403, "identity_required", "Connect your SegmentStream account first.", requestId);
92
+ }
93
+ let body;
94
+ try {
95
+ body = JSON.parse(queryBody);
96
+ }
97
+ catch {
98
+ return refusal(400, "invalid_request", "Invalid source request.", requestId);
99
+ }
100
+ if (!body || typeof body !== "object" || !("operation" in body)) {
101
+ return refusal(400, "invalid_request", "Invalid source request.", requestId);
102
+ }
103
+ queryBody = JSON.stringify({ ...body, subject });
104
+ if (body.operation === "connections") {
105
+ const link = new URL("/auth/workspace-access", "https://segmentstream.com");
106
+ link.searchParams.set("recipient", options.environment.workspaceId);
107
+ link.searchParams.set("org", options.environment.organizationId);
108
+ link.searchParams.set("subject", subject);
109
+ manageUrl = link.href;
110
+ }
111
+ }
82
112
  const answered = yield* Effect.result(fetchQuery({
83
113
  environment: options.environment,
84
114
  fetch: fetchImpl,
85
115
  token,
86
116
  member,
87
- query: input.success,
117
+ query: queryBody,
118
+ delegated,
88
119
  requestId,
89
120
  }));
90
121
  if (Result.isFailure(answered)) {
@@ -99,11 +130,16 @@ export function workspaceSourceLayer(options) {
99
130
  requestId,
100
131
  memberId: member.id,
101
132
  }));
133
+ if (manageUrl && status === 200) {
134
+ const data = JSON.parse(new TextDecoder().decode(body));
135
+ return HttpServerResponse.jsonUnsafe({ manageUrl, workspaces: data.workspaces }, { headers: { "cache-control": "no-store" } });
136
+ }
102
137
  return HttpServerResponse.uint8Array(body, {
103
138
  status,
104
139
  headers: { "content-type": "application/json", "cache-control": "no-store" },
105
140
  });
106
141
  });
107
- yield* router.add("POST", WORKSPACE_SOURCE_PATH, query);
142
+ yield* router.add("POST", WORKSPACE_SOURCE_PATH, (request) => query(request));
143
+ yield* router.add("POST", `${AGENT_PATH}/source/authorized`, (request) => query(request, true));
108
144
  }));
109
145
  }
@@ -658,6 +658,7 @@ export interface AgentStore {
658
658
  readonly externalId: string;
659
659
  }) => Effect.Effect<AgentIdentity | undefined>;
660
660
  /** The member's live identities, oldest first. */
661
+ readonly segmentStreamSubject?: (userId: string, issuer: string) => Effect.Effect<string | undefined>;
661
662
  readonly listIdentities: (userId: string) => Effect.Effect<ReadonlyArray<AgentIdentity>>;
662
663
  /** Revokes one of the member's live identities; false when they have no such identity. */
663
664
  readonly revokeIdentity: (input: {
@@ -11,7 +11,7 @@ import { nameToWire } from "../authoring-names.js";
11
11
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
12
12
  import { parsePageCatalog } from "../navigation-catalog.js";
13
13
  import { chatRetentionDaysOf, declaredChatRetentionDaysOf, guestOf, signUpOriginsOf, signUpRolesOf, } from "../manifest.js";
14
- import { allowsAction, isAllowed, WORKSPACE_SOURCE_PERMISSION } from "../permissions.js";
14
+ import { allowsAction, isAllowed, WORKSPACE_SOURCE_CONNECT, WORKSPACE_SOURCE_PERMISSION, } from "../permissions.js";
15
15
  import { agentToolsFor } from "../runtime/guests.js";
16
16
  import { implicitMemberOf } from "../role.js";
17
17
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
@@ -435,9 +435,16 @@ export function createOntologyService(ontology, config) {
435
435
  // Every answer that tells the agent whom it acts for names the agent's own tools they hold.
436
436
  const agentTools = (principal) => {
437
437
  const tools = agentToolsFor(ontology, principal);
438
- return principal.kind === "member" && isAllowed(WORKSPACE_SOURCE_PERMISSION, principal)
439
- ? [...tools, "workspace_source"]
440
- : tools;
438
+ if (principal.kind !== "member") {
439
+ return tools;
440
+ }
441
+ return [
442
+ ...tools,
443
+ ...(isAllowed(WORKSPACE_SOURCE_PERMISSION, principal) ? ["workspace_source"] : []),
444
+ ...(federationConfig && isAllowed(WORKSPACE_SOURCE_CONNECT, principal)
445
+ ? ["workspace_source_connect"]
446
+ : []),
447
+ ];
441
448
  };
442
449
  const guest = guestOf(ontology.manifest);
443
450
  // A guest proves an address with the app's own code email, which needs the production app.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.189.1",
3
+ "version": "0.190.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",