@segmentstream/ontology 0.99.2 → 0.101.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 +25 -0
- package/README.md +23 -2
- package/dist/analyze.js +19 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +6 -3
- package/dist/permissions.d.ts +14 -2
- package/dist/permissions.js +20 -7
- package/dist/runtime/agent-web.d.ts +9 -0
- package/dist/runtime/agent-web.js +61 -0
- package/dist/runtime/agents.js +2 -0
- package/dist/service/agent/authentication.d.ts +26 -0
- package/dist/service/agent/authentication.js +82 -18
- package/dist/service/agent/server.d.ts +3 -0
- package/dist/service/agent/server.js +8 -0
- package/dist/service/agent/source.d.ts +29 -0
- package/dist/service/agent/source.js +128 -0
- package/dist/service/agent/web-tokens.d.ts +31 -0
- package/dist/service/agent/web-tokens.js +121 -0
- package/dist/service/authentication.js +14 -6
- package/dist/service/oauth/protocol.d.ts +1 -0
- package/dist/service/oauth/protocol.js +1 -0
- package/dist/service/runtime-contract.d.ts +25 -0
- package/dist/service/runtime-identity.d.ts +10 -0
- package/dist/service/runtime-identity.js +10 -0
- package/dist/service/service.js +2 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.101.0
|
|
4
|
+
|
|
5
|
+
A member signed in to the app can reach the app's agent from the browser with an agent token: an
|
|
6
|
+
ordinary OAuth access token (`sso_…`) of the member's grant to the first-party client `agent-web`,
|
|
7
|
+
for the resource `<app origin>/api/ontology/agent`. It works only there, so it is neither an app
|
|
8
|
+
session nor an MCP token.
|
|
9
|
+
|
|
10
|
+
- `POST /api/ontology/agent/tokens`, with the member's app sign-in, answers
|
|
11
|
+
`{ token, expires_at, chat }`: a new hour-long token of the member's one standing grant, for their
|
|
12
|
+
own chat `member:<id>`. API keys and the agent get none.
|
|
13
|
+
- `POST /api/ontology/agent/tokens/introspect`, for the agent only, answers whom a token stands for:
|
|
14
|
+
`{ active, member_id, name, roles, grant_id, chat }`, or `{ active: false }`.
|
|
15
|
+
- Acting for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`), the agent
|
|
16
|
+
names the grant in `X-SegmentStream-Agent-Grant`; the request runs as the member while the grant
|
|
17
|
+
stands and they are active. Deactivating or blocking the member revokes it.
|
|
18
|
+
|
|
19
|
+
The grants and tokens live in the existing OAuth tables; nothing is migrated.
|
|
20
|
+
|
|
21
|
+
## 0.100.0
|
|
22
|
+
|
|
23
|
+
The built-in permission `workspace_source:read` lets a role read the workspace's deployed code
|
|
24
|
+
through the agent. No wildcard grants it: `*:*` and `*:read` do not, `workspace_source:read` and
|
|
25
|
+
`workspace_source:*` do. `GET /api/ontology/agent/source` serves the agent runtime acting for a
|
|
26
|
+
member who holds it, page by page, from backend-next.
|
|
27
|
+
|
|
3
28
|
## 0.99.2
|
|
4
29
|
|
|
5
30
|
Replication reads a workspace's manifest from its database once per process instead of on every
|
package/README.md
CHANGED
|
@@ -928,8 +928,15 @@ configured. This preparation does not advertise or enable exact chat posting.
|
|
|
928
928
|
A permission is `<entity>:<verb>`. The verbs are `read`, the generated `create`, `update`,
|
|
929
929
|
`delete`, `link` and `unlink`, and the names of authored actions. A role may use `*` for the
|
|
930
930
|
entity, the verb or both: `lead:*`, `*:read`, `*:*`. An entity wildcard never covers the
|
|
931
|
-
built-in `agent_chat`, `agent_review`, `app_feedback`, `app_feedback_file` or
|
|
932
|
-
reading or changing them needs a permission that names them, such as
|
|
931
|
+
built-in `agent_chat`, `agent_review`, `app_feedback`, `app_feedback_file`, `user_identity` or
|
|
932
|
+
`workspace_source`: reading or changing them needs a permission that names them, such as
|
|
933
|
+
`agent_chat:read` or `agent_chat:*`.
|
|
934
|
+
|
|
935
|
+
`workspace_source:read` (`WORKSPACE_SOURCE_PERMISSION`) is the built-in permission to read the
|
|
936
|
+
workspace's deployed code through the agent (see [The workspace's code](#the-workspaces-code)).
|
|
937
|
+
`workspace_source` is no entity: `check` refuses any other verb of it, a scoped grant of it, and
|
|
938
|
+
an entity or toolset named `workspace_source`. Only `workspace_source:read` or
|
|
939
|
+
`workspace_source:*` grants it; `*:read`, `*:*` and a pipeline workload's `*:*` do not.
|
|
933
940
|
|
|
934
941
|
- Reads require `<entity>:read`: lists, queries, records, history, both entities of a
|
|
935
942
|
relationship traversal, and every entity a metric query touches. `include` and a filter through a relationship require `read` on
|
|
@@ -1535,6 +1542,20 @@ provider. No other action writes `user_identity`. Revoked bindings are omitted;
|
|
|
1535
1542
|
stable and usernames are mutable display metadata. Older databases without channel tables
|
|
1536
1543
|
remain readable. Use `segmentstream ontology member list --via PROVIDER` to find a member UUID.
|
|
1537
1544
|
|
|
1545
|
+
### The workspace's code
|
|
1546
|
+
|
|
1547
|
+
`GET /api/ontology/agent/source[?cursor=…]` (`WORKSPACE_SOURCE_PATH`) gives the app's agent one
|
|
1548
|
+
page of the workspace's deployed commit, to copy into its sandbox for the member it acts for. Only
|
|
1549
|
+
the production runtime bearer token authenticates, with `X-SegmentStream-Act-As` naming an
|
|
1550
|
+
active paired member; an API key, with delegation or not, and `X-SegmentStream-Agent-Task` are
|
|
1551
|
+
refused. A member who is inactive, unpaired or without `workspace_source:read` gets 403
|
|
1552
|
+
`permission_denied` before SegmentStream is called. The route forwards the cursor to
|
|
1553
|
+
SegmentStream with the request's Vercel OIDC token, the organization and the member's id, and
|
|
1554
|
+
answers with SegmentStream's status, body (a gzip-compressed tar archive, or a JSON error) and
|
|
1555
|
+
`x-segmentstream-source-*` headers unchanged. Without a Vercel OIDC token it answers 503
|
|
1556
|
+
`workspace_source_unavailable`. It logs `ontology.workspace_source.page` with the request, the
|
|
1557
|
+
member and the commit, never a path. It is no MCP tool.
|
|
1558
|
+
|
|
1538
1559
|
### Agent attachments
|
|
1539
1560
|
|
|
1540
1561
|
Attachments remain separate member-authorized capabilities. Chat posting accepts text only;
|
package/dist/analyze.js
CHANGED
|
@@ -8,7 +8,7 @@ import { CONNECTION_KEY, isConnection } from "./connection.js";
|
|
|
8
8
|
import { isEntity } from "./entity.js";
|
|
9
9
|
import { QUERY_METRICS_ROUTE, LEGACY_MEMBER_NAME, ENTITY_ID, GENERATED_ACTIONS, GENERATED_UPSERT_PREFIX, HISTORY_SUFFIX, MCP_METRIC_TOOLS, MCP_READ_TOOLS, MCP_TOOL_NAME_MAX_LENGTH, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, mcpToolName, RESERVED_ENTITY_NAMES, RESERVED_MEMBER_NAMES, RESERVED_RELATIONSHIP_NAMES, SNAKE_CASE_NAME, SYSTEM_PROPERTIES, humanize, isSystemProperty, toCamelCase, } from "./names.js";
|
|
10
10
|
import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownPropertyOptions, referenceTarget, } from "./property.js";
|
|
11
|
-
import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, } from "./permissions.js";
|
|
11
|
+
import { EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, WORKSPACE_SOURCE, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
|
|
12
12
|
import { ON_DELETE, isRelationship } from "./relationship.js";
|
|
13
13
|
import { isRole, member, role } from "./role.js";
|
|
14
14
|
import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isSignInPolicy, isSignUpChannel, } from "./sign-in.js";
|
|
@@ -920,6 +920,11 @@ function resolveToolsets(declared, entities, connections, report) {
|
|
|
920
920
|
report("reserved-name", path, `${name} is reserved: the service's own tools or routes start with it; rename the toolset.`);
|
|
921
921
|
return;
|
|
922
922
|
}
|
|
923
|
+
if (name === WORKSPACE_SOURCE) {
|
|
924
|
+
report("reserved-name", path, `${name} names the built-in permission ${WORKSPACE_SOURCE_PERMISSION}, which reads the ` +
|
|
925
|
+
"workspace's code; rename the toolset.");
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
923
928
|
const definition = candidate.definition;
|
|
924
929
|
if (!isPlainObject(definition)) {
|
|
925
930
|
report("invalid-toolset", path, "a toolset takes { connection, api, lock, description }.");
|
|
@@ -1503,6 +1508,10 @@ function resolveEntity(candidate, scope, resolvedProperties) {
|
|
|
1503
1508
|
else if (RESERVED_ENTITY_NAMES.includes(name)) {
|
|
1504
1509
|
report("reserved-name", name, `/api/ontology/${name} is a route of the ontology service.`);
|
|
1505
1510
|
}
|
|
1511
|
+
else if (name === WORKSPACE_SOURCE) {
|
|
1512
|
+
report("reserved-name", name, `${WORKSPACE_SOURCE} names the built-in permission ${WORKSPACE_SOURCE_PERMISSION}, which ` +
|
|
1513
|
+
"reads the workspace's code; choose another entity name.");
|
|
1514
|
+
}
|
|
1506
1515
|
else if (APP_FEEDBACK_ENTITIES.some((feedback) => feedback.name === name) &&
|
|
1507
1516
|
!scope.builtIns.has(definition)) {
|
|
1508
1517
|
report("reserved-name", name, `${name} is the SDK's app feedback; configure feedback on defineOntology ` +
|
|
@@ -2239,7 +2248,8 @@ function ownMembers(candidate, entitiesByName) {
|
|
|
2239
2248
|
/**
|
|
2240
2249
|
* The verbs each entity has: `read`, its generated actions, and what its actions require. The
|
|
2241
2250
|
* built-in user also has its member management verbs, and the built-in sign-in identities their
|
|
2242
|
-
* attach and revoke, which roles may grant.
|
|
2251
|
+
* attach and revoke, which roles may grant. The built-in `workspace_source`, which is no entity,
|
|
2252
|
+
* has `read` only.
|
|
2243
2253
|
*/
|
|
2244
2254
|
function knownVerbs(entities, toolsets = []) {
|
|
2245
2255
|
const verbs = new Map();
|
|
@@ -2275,6 +2285,8 @@ function knownVerbs(entities, toolsets = []) {
|
|
|
2275
2285
|
}
|
|
2276
2286
|
}
|
|
2277
2287
|
}
|
|
2288
|
+
// Last, so that an entity or a toolset of the name, which check refuses, adds no verb to it.
|
|
2289
|
+
verbs.set(WORKSPACE_SOURCE, new Set([READ_VERB]));
|
|
2278
2290
|
return verbs;
|
|
2279
2291
|
}
|
|
2280
2292
|
/** Why a role's permission matches nothing in the ontology, or `undefined` when it matches. */
|
|
@@ -2790,6 +2802,11 @@ function checkScope(input) {
|
|
|
2790
2802
|
"permission by name, such as staff_member:update, or list the wildcard as a string.");
|
|
2791
2803
|
return;
|
|
2792
2804
|
}
|
|
2805
|
+
if (parsed.entity === WORKSPACE_SOURCE && parsed.verb === READ_VERB) {
|
|
2806
|
+
report("invalid-scope", path, `${permission} reads the workspace's code, which has no records to scope; list ` +
|
|
2807
|
+
`${WORKSPACE_SOURCE_PERMISSION} as a string in the roles that may read the code.`);
|
|
2808
|
+
return;
|
|
2809
|
+
}
|
|
2793
2810
|
const entity = entities.find((candidate) => candidate.name === parsed.entity);
|
|
2794
2811
|
if (entity === undefined && verbs.get(parsed.entity)?.has(parsed.verb) === true) {
|
|
2795
2812
|
report("invalid-scope", path, `${parsed.entity} is a toolset, which has no records to scope; list ${permission} as a ` +
|
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 { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
|
|
35
35
|
export type { Ontology } from "./ontology.js";
|
|
36
|
-
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
36
|
+
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
|
|
37
37
|
export type { 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";
|
|
@@ -86,11 +86,13 @@ export { configFromEnv, ENVIRONMENT_VARIABLES, NEON_AUTH_ENVIRONMENT_VARIABLES,
|
|
|
86
86
|
export type { ActionCommitted, AfterCommitHook, NeonAuthEnvironment, OntologyEnvironment, OntologyServiceConfig, } from "./service/config.js";
|
|
87
87
|
export type { Decide, DecisionRequest } from "./service/decisions.js";
|
|
88
88
|
export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
|
|
89
|
-
export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
|
|
89
|
+
export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
|
|
90
90
|
export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
|
|
91
|
-
export { AGENT_PATH } from "./service/agent/server.js";
|
|
91
|
+
export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, } from "./service/agent/server.js";
|
|
92
92
|
export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
|
|
93
|
-
export {
|
|
93
|
+
export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
|
|
94
|
+
export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
|
|
95
|
+
export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
|
|
94
96
|
export type { RuntimeIdentityConfig } from "./service/runtime-identity.js";
|
|
95
97
|
export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
|
|
96
98
|
export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.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 { webhookToken, webhookTokenMatches, WEBHOOK_TOKEN_CONTEXT } from "./webhook-token.js";
|
|
22
|
-
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, } from "./permissions.js";
|
|
22
|
+
export { DEFAULT_MEMBER_PERMISSIONS, effectiveScope, generatedActionPermissions, grants, isAllowed, parsePermission, permissionsOf, principalScopes, READ_VERB, readScope, rolesGranting, scopesOf, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, WILDCARD_ENTITY_VERBS, WORKSPACE_SOURCE_PERMISSION, } 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";
|
|
@@ -54,9 +54,12 @@ export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-co
|
|
|
54
54
|
export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
|
|
55
55
|
// The app's own agent: pairing channel accounts with members, and acting as them, or as a
|
|
56
56
|
// workflow's user in the tasks workflows hand it.
|
|
57
|
-
export { AGENT_PATH } from "./service/agent/server.js";
|
|
57
|
+
export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, } from "./service/agent/server.js";
|
|
58
58
|
export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
|
|
59
|
-
export {
|
|
59
|
+
export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
|
|
60
|
+
// Agent tokens: access tokens of a member's grant to the agent, which a browser shows the agent.
|
|
61
|
+
export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
|
|
62
|
+
export { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, } from "./service/runtime-identity.js";
|
|
60
63
|
// The MCP server the service serves beside the HTTP API.
|
|
61
64
|
export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
|
|
62
65
|
export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.js";
|
package/dist/permissions.d.ts
CHANGED
|
@@ -20,9 +20,21 @@ export declare const READ_VERB = "read";
|
|
|
20
20
|
* identities hold every member's external accounts, such as their Telegram id and username: only a
|
|
21
21
|
* role that names `user_identity` reads them. The agent's held replies hold the workspace's
|
|
22
22
|
* chats with the people it serves, and approving one sends it: only a role that names
|
|
23
|
-
* `agent_review` reads, approves or rejects them.
|
|
23
|
+
* `agent_review` reads, approves or rejects them. The workspace's deployed code is no entity, but
|
|
24
|
+
* {@link WORKSPACE_SOURCE_PERMISSION} is covered the same way: `workspace_source:read` or
|
|
25
|
+
* `workspace_source:*` grants it, `*:read` and `*:*` do not.
|
|
24
26
|
*/
|
|
25
27
|
export declare const EXPLICIT_GRANT_ENTITIES: ReadonlySet<string>;
|
|
28
|
+
/**
|
|
29
|
+
* The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
|
|
30
|
+
* refuses an entity or a toolset of this name, and any verb of it but `read`.
|
|
31
|
+
*/
|
|
32
|
+
export declare const WORKSPACE_SOURCE = "workspace_source";
|
|
33
|
+
/**
|
|
34
|
+
* Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
|
|
35
|
+
* member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
|
|
36
|
+
*/
|
|
37
|
+
export declare const WORKSPACE_SOURCE_PERMISSION = "workspace_source:read";
|
|
26
38
|
/**
|
|
27
39
|
* The verbs of the built-in user's member management: inviting a member, granting and revoking
|
|
28
40
|
* roles, and deactivating and reactivating a member. Like every other verb on `user` but `read` and
|
|
@@ -153,7 +165,7 @@ export interface PermissionHolder {
|
|
|
153
165
|
/**
|
|
154
166
|
* Whether the principal may do what `required` names: one of its permissions equals it, or covers it
|
|
155
167
|
* through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
|
|
156
|
-
* replies and writes of sign-in identities.
|
|
168
|
+
* replies, the workspace's code and writes of sign-in identities.
|
|
157
169
|
*/
|
|
158
170
|
export declare function isAllowed(required: string, principal: PermissionHolder): boolean;
|
|
159
171
|
/**
|
package/dist/permissions.js
CHANGED
|
@@ -19,7 +19,9 @@ export const READ_VERB = "read";
|
|
|
19
19
|
* identities hold every member's external accounts, such as their Telegram id and username: only a
|
|
20
20
|
* role that names `user_identity` reads them. The agent's held replies hold the workspace's
|
|
21
21
|
* chats with the people it serves, and approving one sends it: only a role that names
|
|
22
|
-
* `agent_review` reads, approves or rejects them.
|
|
22
|
+
* `agent_review` reads, approves or rejects them. The workspace's deployed code is no entity, but
|
|
23
|
+
* {@link WORKSPACE_SOURCE_PERMISSION} is covered the same way: `workspace_source:read` or
|
|
24
|
+
* `workspace_source:*` grants it, `*:read` and `*:*` do not.
|
|
23
25
|
*/
|
|
24
26
|
export const EXPLICIT_GRANT_ENTITIES = new Set([
|
|
25
27
|
"agent_chat",
|
|
@@ -27,7 +29,18 @@ export const EXPLICIT_GRANT_ENTITIES = new Set([
|
|
|
27
29
|
"app_feedback",
|
|
28
30
|
"app_feedback_file",
|
|
29
31
|
"user_identity",
|
|
32
|
+
"workspace_source",
|
|
30
33
|
]);
|
|
34
|
+
/**
|
|
35
|
+
* The built-in permission's entity for the workspace's deployed code. It names no entity: `check`
|
|
36
|
+
* refuses an entity or a toolset of this name, and any verb of it but `read`.
|
|
37
|
+
*/
|
|
38
|
+
export const WORKSPACE_SOURCE = "workspace_source";
|
|
39
|
+
/**
|
|
40
|
+
* Reading the workspace's deployed code, which the app's agent copies into its sandbox for the
|
|
41
|
+
* member it acts for, through `GET /api/ontology/agent/source`. Only a role that names it grants it.
|
|
42
|
+
*/
|
|
43
|
+
export const WORKSPACE_SOURCE_PERMISSION = `${WORKSPACE_SOURCE}:${READ_VERB}`;
|
|
31
44
|
/** The built-in user's entity name in permissions. */
|
|
32
45
|
const USER_ENTITY = "user";
|
|
33
46
|
/**
|
|
@@ -154,10 +167,10 @@ function isUserAdministration(required) {
|
|
|
154
167
|
!wildcardEntityCovers(USER_ENTITY, toSnakeCase(wanted.verb)));
|
|
155
168
|
}
|
|
156
169
|
/**
|
|
157
|
-
* Feedback
|
|
158
|
-
* workloads: nothing a pipeline runs approves a reply to a person
|
|
159
|
-
* code reads sign-in identities, for example to address a
|
|
160
|
-
* writes them: only the platform does.
|
|
170
|
+
* Feedback, the agent's held replies and the workspace's code always need named grants, including
|
|
171
|
+
* for pipeline workloads: nothing a pipeline runs approves a reply to a person or reads the code it
|
|
172
|
+
* runs from. The workspace's own pipeline code reads sign-in identities, for example to address a
|
|
173
|
+
* member in a chat, but nothing it runs writes them: only the platform does.
|
|
161
174
|
*/
|
|
162
175
|
function workloadWildcardCovers(required) {
|
|
163
176
|
const wanted = parsePermission(required);
|
|
@@ -166,12 +179,12 @@ function workloadWildcardCovers(required) {
|
|
|
166
179
|
}
|
|
167
180
|
return (!isUserAdministration(required) &&
|
|
168
181
|
(wanted === undefined ||
|
|
169
|
-
!["app_feedback", "app_feedback_file", "agent_review"].includes(toSnakeCase(wanted.entity))));
|
|
182
|
+
!["app_feedback", "app_feedback_file", "agent_review", WORKSPACE_SOURCE].includes(toSnakeCase(wanted.entity))));
|
|
170
183
|
}
|
|
171
184
|
/**
|
|
172
185
|
* Whether the principal may do what `required` names: one of its permissions equals it, or covers it
|
|
173
186
|
* through a wildcard. Workload wildcards exclude user administration, feedback, the agent's held
|
|
174
|
-
* replies and writes of sign-in identities.
|
|
187
|
+
* replies, the workspace's code and writes of sign-in identities.
|
|
175
188
|
*/
|
|
176
189
|
export function isAllowed(required, principal) {
|
|
177
190
|
return (
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SqlClient } from "effect/unstable/sql";
|
|
2
|
+
import type { Ontology } from "../ontology.js";
|
|
3
|
+
import type { AgentWebStore } from "../service/runtime-contract.js";
|
|
4
|
+
/**
|
|
5
|
+
* Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
|
|
6
|
+
* member and resource for the first-party client `agent-web`, and a new access token on each
|
|
7
|
+
* request. Blocking or deactivating the member revokes the grant with every other one of theirs.
|
|
8
|
+
*/
|
|
9
|
+
export declare function sqlAgentWebStore(ontology: Ontology, sql: SqlClient.SqlClient): AgentWebStore;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, USER_TABLE } from "../migrate/storage.js";
|
|
4
|
+
import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
|
|
5
|
+
import { ACCESS_TOKEN_PREFIX, FULL_SCOPE, newSecret, secretHash, } from "../service/oauth/protocol.js";
|
|
6
|
+
import { sqlOAuthStore } from "./oauth.js";
|
|
7
|
+
import { isMemberBlocked } from "./principals.js";
|
|
8
|
+
import { isRecordId } from "./records.js";
|
|
9
|
+
const GRANTS = `"${OAUTH_GRANTS_TABLE}"`;
|
|
10
|
+
/**
|
|
11
|
+
* Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
|
|
12
|
+
* member and resource for the first-party client `agent-web`, and a new access token on each
|
|
13
|
+
* request. Blocking or deactivating the member revokes the grant with every other one of theirs.
|
|
14
|
+
*/
|
|
15
|
+
export function sqlAgentWebStore(ontology, sql) {
|
|
16
|
+
const oauth = sqlOAuthStore(ontology, sql);
|
|
17
|
+
return {
|
|
18
|
+
issue: ({ userId, resource, expiresAt }) => sql
|
|
19
|
+
.withTransaction(Effect.gen(function* () {
|
|
20
|
+
// Same lock as the member's lifecycle operations, so a blocked member never gets one.
|
|
21
|
+
const [member] = yield* sql.unsafe(`SELECT "kind"::text AS "kind", "active" FROM "${USER_TABLE}"
|
|
22
|
+
WHERE "id" = $1::uuid FOR SHARE`, [userId]);
|
|
23
|
+
if (member?.kind !== "member" ||
|
|
24
|
+
!member.active ||
|
|
25
|
+
(yield* isMemberBlocked(sql, userId))) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
yield* sql.unsafe(`INSERT INTO "${OAUTH_CLIENTS_TABLE}" ("id", "name", "redirect_uris", "auth_method")
|
|
29
|
+
VALUES ($1, $1, '[]'::jsonb, 'none') ON CONFLICT ("id") DO NOTHING`, [AGENT_WEB_CLIENT_ID]);
|
|
30
|
+
const [standing] = yield* sql.unsafe(`SELECT "id"::text AS "id" FROM ${GRANTS}
|
|
31
|
+
WHERE "user_id" = $1::uuid AND "client_id" = $2 AND "resource" = $3
|
|
32
|
+
AND "revoked_at" IS NULL ORDER BY "created_at" LIMIT 1`, [userId, AGENT_WEB_CLIENT_ID, resource]);
|
|
33
|
+
const grantId = standing?.id ?? randomUUID();
|
|
34
|
+
if (standing === undefined) {
|
|
35
|
+
yield* oauth.saveGrant({
|
|
36
|
+
id: grantId,
|
|
37
|
+
clientId: AGENT_WEB_CLIENT_ID,
|
|
38
|
+
userId,
|
|
39
|
+
scope: FULL_SCOPE,
|
|
40
|
+
resource,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const token = newSecret(ACCESS_TOKEN_PREFIX);
|
|
44
|
+
yield* oauth.saveTokens([
|
|
45
|
+
{ hash: secretHash(token), grantId, kind: "access", expiresAt },
|
|
46
|
+
]);
|
|
47
|
+
return token;
|
|
48
|
+
}))
|
|
49
|
+
.pipe(Effect.orDie),
|
|
50
|
+
grantMember: ({ grantId, userId }) => Effect.gen(function* () {
|
|
51
|
+
if (!isRecordId(grantId) || !isRecordId(userId)) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
const [standing] = yield* sql
|
|
55
|
+
.unsafe(`SELECT 1 FROM ${GRANTS} WHERE "id" = $1::uuid AND "user_id" = $2::uuid
|
|
56
|
+
AND "client_id" = $3 AND "revoked_at" IS NULL`, [grantId, userId, AGENT_WEB_CLIENT_ID])
|
|
57
|
+
.pipe(Effect.orDie);
|
|
58
|
+
return standing === undefined ? undefined : yield* oauth.memberPrincipal(userId);
|
|
59
|
+
}),
|
|
60
|
+
};
|
|
61
|
+
}
|
package/dist/runtime/agents.js
CHANGED
|
@@ -12,6 +12,7 @@ import { revokeChannelSessions } from "./channel-session-revocation.js";
|
|
|
12
12
|
import { resolveAgentIdentity } from "./resolve-agent-identity.js";
|
|
13
13
|
import { completeAgentLimitNotice } from "./agent-counters.js";
|
|
14
14
|
import { isMemberBlocked, setMemberBlocked, resolveMemberById } from "./principals.js";
|
|
15
|
+
import { sqlAgentWebStore } from "./agent-web.js";
|
|
15
16
|
import { isRecordId } from "./records.js";
|
|
16
17
|
import { makeOntologyRuntime } from "./sql-runtime.js";
|
|
17
18
|
import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
|
|
@@ -488,6 +489,7 @@ export function sqlAgentStore(ontology, sql) {
|
|
|
488
489
|
return { id: String(review.id), status: "pending", created: true };
|
|
489
490
|
}))
|
|
490
491
|
.pipe(Effect.orDie),
|
|
492
|
+
web: sqlAgentWebStore(ontology, sql),
|
|
491
493
|
};
|
|
492
494
|
return store;
|
|
493
495
|
}
|
|
@@ -2,6 +2,7 @@ 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 { Principal } from "../../runtime.js";
|
|
5
6
|
import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
|
|
6
7
|
import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
7
8
|
export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
|
|
@@ -26,6 +27,31 @@ export declare function authenticateAgentCaller(input: {
|
|
|
26
27
|
readonly caller: AttachmentCaller;
|
|
27
28
|
readonly response?: undefined;
|
|
28
29
|
}, never, RequestId | HttpServerRequest.ParsedSearchParams>;
|
|
30
|
+
/**
|
|
31
|
+
* The member the agent acts for on the web: the OAuth grant behind the agent token they showed
|
|
32
|
+
* names them and stands, and they are active. `undefined` on a store without web grants.
|
|
33
|
+
*/
|
|
34
|
+
export declare function webMember(agents: AgentStore, userId: string, grantId: string): Effect.Effect<Principal | undefined>;
|
|
35
|
+
/**
|
|
36
|
+
* Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
|
|
37
|
+
* on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
|
|
38
|
+
* refused. `member` is the member with the roles they hold now, or `undefined` when the header names
|
|
39
|
+
* nobody who is active and paired with the agent, or a web member without a live grant; the route
|
|
40
|
+
* decides how to refuse them.
|
|
41
|
+
*/
|
|
42
|
+
export declare function authenticateAgentRuntimeMember(input: {
|
|
43
|
+
readonly request: HttpServerRequest.HttpServerRequest;
|
|
44
|
+
readonly agents: AgentStore;
|
|
45
|
+
readonly verify: RuntimeTokenVerifier;
|
|
46
|
+
}): Effect.Effect<{
|
|
47
|
+
readonly ok: false;
|
|
48
|
+
readonly response: import("effect/unstable/http/HttpServerResponse").HttpServerResponse;
|
|
49
|
+
readonly member?: undefined;
|
|
50
|
+
} | {
|
|
51
|
+
readonly ok: true;
|
|
52
|
+
readonly member: Principal | undefined;
|
|
53
|
+
readonly response?: undefined;
|
|
54
|
+
}, never, RequestId | HttpServerRequest.ParsedSearchParams>;
|
|
29
55
|
/** Resolves an `ssk_` key to its user and whether it acts with delegation. */
|
|
30
56
|
export type ApiKeyCredentialResolver = NonNullable<OntologyBackend["Service"]["resolveApiKeyCredential"]>;
|
|
31
57
|
/**
|
|
@@ -3,7 +3,7 @@ import { HttpServerRequest } from "effect/unstable/http";
|
|
|
3
3
|
import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
|
|
4
4
|
import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
|
|
5
5
|
import { API_KEY_PREFIX } from "../../runtime/principals.js";
|
|
6
|
-
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
6
|
+
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
7
7
|
export const CHAT_HEADER = "x-segmentstream-agent-chat";
|
|
8
8
|
export const SESSION_HEADER = "x-segmentstream-agent-session";
|
|
9
9
|
/** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
|
|
@@ -29,34 +29,98 @@ export function authenticateAgentCaller(input) {
|
|
|
29
29
|
}
|
|
30
30
|
return agentCaller(request, requestId, delegated.member, delegated.client);
|
|
31
31
|
}
|
|
32
|
+
const refused = yield* refuseUnlessRuntime(request, token, verify);
|
|
33
|
+
if (refused !== undefined) {
|
|
34
|
+
return { ok: false, response: refused };
|
|
35
|
+
}
|
|
36
|
+
const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
|
|
37
|
+
const grant = request.headers[AGENT_GRANT_HEADER]?.trim() ?? "";
|
|
38
|
+
const member = actAs === ""
|
|
39
|
+
? undefined
|
|
40
|
+
: request.headers[ACT_AS_PROVIDER_HEADER]?.trim() === WEB_PROVIDER
|
|
41
|
+
? grant === ""
|
|
42
|
+
? undefined
|
|
43
|
+
: yield* webMember(agents, actAs, grant)
|
|
44
|
+
: input.allowUnpairedMember
|
|
45
|
+
? (yield* agents.member(actAs))?.principal
|
|
46
|
+
: yield* agents.actingMember(actAs);
|
|
47
|
+
if (member === undefined) {
|
|
48
|
+
return denied(input.allowUnpairedMember
|
|
49
|
+
? notFound(requestId, "Attachment not found.")
|
|
50
|
+
: forbidden(requestId, "The member is inactive or has not paired with the agent."));
|
|
51
|
+
}
|
|
52
|
+
return agentCaller(request, requestId, member);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The member the agent acts for on the web: the OAuth grant behind the agent token they showed
|
|
57
|
+
* names them and stands, and they are active. `undefined` on a store without web grants.
|
|
58
|
+
*/
|
|
59
|
+
export function webMember(agents, userId, grantId) {
|
|
60
|
+
return agents.web === undefined
|
|
61
|
+
? Effect.succeed(undefined)
|
|
62
|
+
: Effect.map(agents.web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The member the runtime acts for: a web member by the grant their agent token stands for, anyone
|
|
66
|
+
* else by their pairing with the agent. `undefined` when the headers name nobody admitted.
|
|
67
|
+
*/
|
|
68
|
+
function runtimeActingMember(request, agents) {
|
|
69
|
+
const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
|
|
70
|
+
const grant = request.headers[AGENT_GRANT_HEADER]?.trim() ?? "";
|
|
71
|
+
if (actAs === "") {
|
|
72
|
+
return Effect.succeed(undefined);
|
|
73
|
+
}
|
|
74
|
+
return request.headers[ACT_AS_PROVIDER_HEADER]?.trim() === WEB_PROVIDER
|
|
75
|
+
? grant === ""
|
|
76
|
+
? Effect.succeed(undefined)
|
|
77
|
+
: webMember(agents, actAs, grant)
|
|
78
|
+
: agents.actingMember(actAs);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The answer refusing an agent route's bearer token unless it is the deployment's own runtime token
|
|
82
|
+
* and the request presents no task's secret; `undefined` when it is admitted.
|
|
83
|
+
*/
|
|
84
|
+
function refuseUnlessRuntime(request, token, verify) {
|
|
85
|
+
return Effect.gen(function* () {
|
|
86
|
+
const requestId = yield* RequestId;
|
|
32
87
|
const verified = token === "" ? undefined : yield* Effect.promise(() => verify(token));
|
|
33
88
|
switch (verified?.status) {
|
|
34
89
|
case "valid":
|
|
35
90
|
break;
|
|
36
91
|
case "invalid":
|
|
37
92
|
yield* logRuntimeRejection(verified.reason);
|
|
38
|
-
return
|
|
93
|
+
return toServerResponse(unauthorized(requestId, "The bearer token is invalid, expired or revoked."));
|
|
39
94
|
case "unavailable":
|
|
40
|
-
return
|
|
95
|
+
return toServerResponse(unavailable(requestId));
|
|
41
96
|
default:
|
|
42
|
-
return
|
|
43
|
-
}
|
|
44
|
-
// Attachments and member files are a member's; a task, acting as a workflow's user, has none.
|
|
45
|
-
if (agentTaskSecret(request) !== undefined) {
|
|
46
|
-
return denied(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
|
|
97
|
+
return toServerResponse(forbidden(requestId, "Only the app's agent calls this route."));
|
|
47
98
|
}
|
|
48
|
-
|
|
49
|
-
|
|
99
|
+
// Attachments, member files and the workspace's code are a member's; a task, acting as a
|
|
100
|
+
// workflow's user, has none.
|
|
101
|
+
return agentTaskSecret(request) === undefined
|
|
50
102
|
? undefined
|
|
51
|
-
:
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
103
|
+
: toServerResponse(forbidden(requestId, `This route does not accept ${AGENT_TASK_HEADER}.`));
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
|
|
108
|
+
* on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
|
|
109
|
+
* refused. `member` is the member with the roles they hold now, or `undefined` when the header names
|
|
110
|
+
* nobody who is active and paired with the agent, or a web member without a live grant; the route
|
|
111
|
+
* decides how to refuse them.
|
|
112
|
+
*/
|
|
113
|
+
export function authenticateAgentRuntimeMember(input) {
|
|
114
|
+
return Effect.gen(function* () {
|
|
115
|
+
const { request, agents, verify } = input;
|
|
116
|
+
const credential = HttpApiBuilder.securityDecode(HttpApiSecurity.bearer);
|
|
117
|
+
const bearer = yield* Effect.provideService(credential, HttpServerRequest.HttpServerRequest, request);
|
|
118
|
+
const refused = yield* refuseUnlessRuntime(request, Redacted.value(bearer), verify);
|
|
119
|
+
if (refused !== undefined) {
|
|
120
|
+
return { ok: false, response: refused };
|
|
58
121
|
}
|
|
59
|
-
|
|
122
|
+
const member = yield* runtimeActingMember(request, agents);
|
|
123
|
+
return { ok: true, member: member?.kind === "member" ? member : undefined };
|
|
60
124
|
});
|
|
61
125
|
}
|
|
62
126
|
/** The chat and session every agent request names, with the member it acts for. */
|
|
@@ -7,6 +7,9 @@ import { OntologyBackend } from "../runtime-contract.js";
|
|
|
7
7
|
import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
8
8
|
/** The agent's endpoints, under the ontology service's path. */
|
|
9
9
|
export declare const AGENT_PATH = "/api/ontology/agent";
|
|
10
|
+
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
11
|
+
export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
|
|
12
|
+
export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
|
|
10
13
|
/**
|
|
11
14
|
* Pairings one client address may start per minute; each one is a row in the database. The agent's
|
|
12
15
|
* functions share a few egress addresses, so the limit leaves room for a busy channel.
|
|
@@ -13,12 +13,16 @@ import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
|
13
13
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
14
14
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
15
15
|
import { ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
16
|
+
import { AGENT_TOKEN_LIMIT, introspectAgentToken, issueAgentToken } from "./web-tokens.js";
|
|
16
17
|
/** The agent's endpoints, under the ontology service's path. */
|
|
17
18
|
export const AGENT_PATH = `${BASE_PATH}/agent`;
|
|
18
19
|
const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
|
|
19
20
|
const IDENTITIES_PATH = `${AGENT_PATH}/identities`;
|
|
20
21
|
const CHATS_SEEN_PATH = `${AGENT_PATH}/chats/seen`;
|
|
21
22
|
const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
|
|
23
|
+
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
24
|
+
export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
|
|
25
|
+
export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
|
|
22
26
|
/**
|
|
23
27
|
* Pairings one client address may start per minute; each one is a row in the database. The agent's
|
|
24
28
|
* functions share a few egress addresses, so the limit leaves room for a busy channel.
|
|
@@ -428,5 +432,9 @@ export function agentLayer(options) {
|
|
|
428
432
|
yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
|
|
429
433
|
yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
|
|
430
434
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
435
|
+
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
436
|
+
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
437
|
+
yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, backend.oauth)));
|
|
438
|
+
}
|
|
431
439
|
}));
|
|
432
440
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Layer } from "effect";
|
|
2
|
+
import { HttpRouter } from "effect/unstable/http";
|
|
3
|
+
import { RequestId } from "../errors.js";
|
|
4
|
+
import { OntologyBackend } from "../runtime-contract.js";
|
|
5
|
+
import type { RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
6
|
+
/** `GET /api/ontology/agent/source[?cursor=…]`: a page of the workspace's deployed code. */
|
|
7
|
+
export declare const WORKSPACE_SOURCE_PATH = "/api/ontology/agent/source";
|
|
8
|
+
/** Where the deployed ontology service reaches backend-next, as its connection calls do. */
|
|
9
|
+
export interface WorkspaceSourceEnvironment {
|
|
10
|
+
readonly segmentstreamUrl: string;
|
|
11
|
+
readonly workspaceId: string;
|
|
12
|
+
readonly organizationId: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* `GET /api/ontology/agent/source[?cursor=…]` (runtime): the app's agent, acting for a member,
|
|
16
|
+
* reads the workspace's deployed code a page at a time to copy it into its sandbox. Only the
|
|
17
|
+
* deployment's runtime token authenticates, never an API key or a task's secret; the member named
|
|
18
|
+
* by `X-SegmentStream-Act-As` must be active, paired with the agent and hold
|
|
19
|
+
* `workspace_source:read`, which no wildcard grants, before backend-next is called. The route
|
|
20
|
+
* forwards the cursor with the request's Vercel OIDC token and answers with backend-next's status,
|
|
21
|
+
* body and `x-segmentstream-source-*` headers as they are. It is no MCP tool, and it is not served
|
|
22
|
+
* without runtime authentication or the agent's tables.
|
|
23
|
+
*/
|
|
24
|
+
export declare function workspaceSourceLayer(options: {
|
|
25
|
+
readonly environment: WorkspaceSourceEnvironment;
|
|
26
|
+
readonly verifyRuntime: RuntimeTokenVerifier | undefined;
|
|
27
|
+
/** How the route calls backend-next: `fetch` by default. Tests replace it. */
|
|
28
|
+
readonly fetch?: typeof fetch;
|
|
29
|
+
}): Layer.Layer<never, never, OntologyBackend | HttpRouter.HttpRouter | HttpRouter.Request<"Requires", RequestId>>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { Effect, Layer, Result } from "effect";
|
|
2
|
+
import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
|
|
3
|
+
import { isAllowed, WORKSPACE_SOURCE_PERMISSION } from "../../permissions.js";
|
|
4
|
+
import { RequestId, errorBodyForWire } from "../errors.js";
|
|
5
|
+
import { describeError } from "../metric-query-platform.js";
|
|
6
|
+
import { identityToken } from "../operations.js";
|
|
7
|
+
import { OntologyBackend } from "../runtime-contract.js";
|
|
8
|
+
import { authenticateAgentRuntimeMember } from "./authentication.js";
|
|
9
|
+
import { AGENT_PATH } from "./server.js";
|
|
10
|
+
/** `GET /api/ontology/agent/source[?cursor=…]`: a page of the workspace's deployed code. */
|
|
11
|
+
export const WORKSPACE_SOURCE_PATH = `${AGENT_PATH}/source`;
|
|
12
|
+
/** The headers of a page that the route passes on as backend-next sent them. */
|
|
13
|
+
const SOURCE_HEADER_PREFIX = "x-segmentstream-source-";
|
|
14
|
+
const COMMIT_HEADER = `${SOURCE_HEADER_PREFIX}commit`;
|
|
15
|
+
/** A page is at most a few megabytes, which backend-next reads from the workspace's repository. */
|
|
16
|
+
const PAGE_TIMEOUT_MS = 60_000;
|
|
17
|
+
const UNAVAILABLE = "workspace_source_unavailable";
|
|
18
|
+
function refusal(status, error, detail, requestId) {
|
|
19
|
+
return HttpServerResponse.jsonUnsafe(errorBodyForWire({ error, detail, requestId }), {
|
|
20
|
+
status,
|
|
21
|
+
headers: { "cache-control": "no-store" },
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* One page of the deployed commit's files from backend-next, which admits the deployment by its
|
|
26
|
+
* Vercel OIDC token and takes the member's id for its log only.
|
|
27
|
+
*/
|
|
28
|
+
function fetchPage(input) {
|
|
29
|
+
const { environment, token, member, cursor, requestId } = input;
|
|
30
|
+
const url = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
|
|
31
|
+
`${encodeURIComponent(environment.workspaceId)}/ontology/source` +
|
|
32
|
+
(cursor === null ? "" : `?cursor=${encodeURIComponent(cursor)}`);
|
|
33
|
+
return Effect.tryPromise({
|
|
34
|
+
try: async (signal) => {
|
|
35
|
+
const response = await input.fetch(url, {
|
|
36
|
+
method: "GET",
|
|
37
|
+
redirect: "error",
|
|
38
|
+
headers: {
|
|
39
|
+
"x-segmentstream-runtime-identity": token,
|
|
40
|
+
"x-segmentstream-organization-id": environment.organizationId,
|
|
41
|
+
"x-segmentstream-ontology-principal": member.id,
|
|
42
|
+
"x-segmentstream-request-id": requestId,
|
|
43
|
+
},
|
|
44
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(PAGE_TIMEOUT_MS)]),
|
|
45
|
+
});
|
|
46
|
+
const headers = {};
|
|
47
|
+
response.headers.forEach((value, name) => {
|
|
48
|
+
if (name === "content-type" || name.startsWith(SOURCE_HEADER_PREFIX)) {
|
|
49
|
+
headers[name] = value;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
status: response.status,
|
|
54
|
+
headers,
|
|
55
|
+
body: new Uint8Array(await response.arrayBuffer()),
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
catch: (cause) => cause,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `GET /api/ontology/agent/source[?cursor=…]` (runtime): the app's agent, acting for a member,
|
|
63
|
+
* reads the workspace's deployed code a page at a time to copy it into its sandbox. Only the
|
|
64
|
+
* deployment's runtime token authenticates, never an API key or a task's secret; the member named
|
|
65
|
+
* by `X-SegmentStream-Act-As` must be active, paired with the agent and hold
|
|
66
|
+
* `workspace_source:read`, which no wildcard grants, before backend-next is called. The route
|
|
67
|
+
* forwards the cursor with the request's Vercel OIDC token and answers with backend-next's status,
|
|
68
|
+
* body and `x-segmentstream-source-*` headers as they are. It is no MCP tool, and it is not served
|
|
69
|
+
* without runtime authentication or the agent's tables.
|
|
70
|
+
*/
|
|
71
|
+
export function workspaceSourceLayer(options) {
|
|
72
|
+
return Layer.effectDiscard(Effect.gen(function* () {
|
|
73
|
+
const router = yield* HttpRouter.HttpRouter;
|
|
74
|
+
const { agents } = yield* OntologyBackend;
|
|
75
|
+
const verify = options.verifyRuntime;
|
|
76
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
77
|
+
if (agents === undefined || verify === undefined) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const page = (request) => Effect.gen(function* () {
|
|
81
|
+
const requestId = yield* RequestId;
|
|
82
|
+
const authenticated = yield* authenticateAgentRuntimeMember({ request, agents, verify });
|
|
83
|
+
if (!authenticated.ok) {
|
|
84
|
+
return authenticated.response;
|
|
85
|
+
}
|
|
86
|
+
const { member } = authenticated;
|
|
87
|
+
if (member === undefined) {
|
|
88
|
+
return refusal(403, "permission_denied", "The member is inactive or has not paired with the agent.", requestId);
|
|
89
|
+
}
|
|
90
|
+
if (!isAllowed(WORKSPACE_SOURCE_PERMISSION, member)) {
|
|
91
|
+
return refusal(403, "permission_denied", `${WORKSPACE_SOURCE_PERMISSION} is required.`, requestId);
|
|
92
|
+
}
|
|
93
|
+
const token = identityToken(request);
|
|
94
|
+
if (token === undefined || token === "") {
|
|
95
|
+
return refusal(503, UNAVAILABLE, "The request carries no Vercel OIDC token. The workspace's code is available to " +
|
|
96
|
+
"production deployments.", requestId);
|
|
97
|
+
}
|
|
98
|
+
const cursor = new URL(request.url, "https://ontology.invalid").searchParams.get("cursor");
|
|
99
|
+
const answered = yield* Effect.result(fetchPage({
|
|
100
|
+
environment: options.environment,
|
|
101
|
+
fetch: fetchImpl,
|
|
102
|
+
token,
|
|
103
|
+
member,
|
|
104
|
+
cursor,
|
|
105
|
+
requestId,
|
|
106
|
+
}));
|
|
107
|
+
if (Result.isFailure(answered)) {
|
|
108
|
+
yield* Effect.logWarning("ontology.workspace_source.unavailable").pipe(Effect.annotateLogs({
|
|
109
|
+
requestId,
|
|
110
|
+
error: describeError(answered.failure, (text) => text.split(token).join("[redacted]")),
|
|
111
|
+
}));
|
|
112
|
+
return refusal(503, UNAVAILABLE, "The workspace's code could not be read.", requestId);
|
|
113
|
+
}
|
|
114
|
+
const { status, headers, body } = answered.success;
|
|
115
|
+
// The member and the commit only: never a path, a cursor or a file.
|
|
116
|
+
yield* Effect.logInfo("ontology.workspace_source.page").pipe(Effect.annotateLogs({
|
|
117
|
+
requestId,
|
|
118
|
+
memberId: member.id,
|
|
119
|
+
commit: headers[COMMIT_HEADER] ?? null,
|
|
120
|
+
}));
|
|
121
|
+
return HttpServerResponse.uint8Array(body, {
|
|
122
|
+
status,
|
|
123
|
+
headers: { ...headers, "cache-control": "no-store" },
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
yield* router.add("GET", WORKSPACE_SOURCE_PATH, page);
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
|
3
|
+
import type { Principal } from "../../runtime.js";
|
|
4
|
+
import { RequestId } from "../errors.js";
|
|
5
|
+
import type { RateLimit, RateLimiter } from "../rate-limit.js";
|
|
6
|
+
import type { AgentStore, AgentWebStore, OAuthStore } from "../runtime-contract.js";
|
|
7
|
+
/**
|
|
8
|
+
* A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
|
|
9
|
+
* server (`sso_…`): the token of the member's grant to the first-party client `agent-web`, for the
|
|
10
|
+
* agent's resource on the app's origin. Like every access token, it works only for the resource of
|
|
11
|
+
* its grant, so it is no app session and no MCP token. The agent asks the ontology who a token
|
|
12
|
+
* stands for, and names the token's grant whenever it then acts for the member.
|
|
13
|
+
*/
|
|
14
|
+
export declare const AGENT_WEB_CLIENT_ID = "agent-web";
|
|
15
|
+
/** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
|
|
16
|
+
export declare function agentResource(origin: string): string;
|
|
17
|
+
/** Tokens one member may request per minute; the browser keeps one until it is about to expire. */
|
|
18
|
+
export declare const AGENT_TOKEN_LIMIT: RateLimit;
|
|
19
|
+
/** The member's own chat with the agent, the only chat a token opens so far. */
|
|
20
|
+
export declare function personalChat(userId: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* `POST /api/ontology/agent/tokens`, for the signed-in member: `{ token, expires_at, chat }`, an
|
|
23
|
+
* access token of their grant to the agent, for their own chat.
|
|
24
|
+
*/
|
|
25
|
+
export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, limiter: RateLimiter): (request: HttpServerRequest.HttpServerRequest, member: Principal) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
|
|
26
|
+
/**
|
|
27
|
+
* `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
|
|
28
|
+
* agent token a browser showed stands for. `{ active: false }` for any token that is not a live
|
|
29
|
+
* `agent-web` token for the origin, or whose member may no longer sign in.
|
|
30
|
+
*/
|
|
31
|
+
export declare function introspectAgentToken(store: AgentStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { Effect, Result, Schema } from "effect";
|
|
2
|
+
import { HttpServerResponse } from "effect/unstable/http";
|
|
3
|
+
import { schemaIssues } from "../../runtime/validation.js";
|
|
4
|
+
import { BASE_PATH } from "../api.js";
|
|
5
|
+
import { RequestId, errorBodyForWire, forbidden, rateLimited, toServerResponse, } from "../errors.js";
|
|
6
|
+
import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, callerOfAccessToken, publicOrigin, } from "../oauth/protocol.js";
|
|
7
|
+
/**
|
|
8
|
+
* A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
|
|
9
|
+
* server (`sso_…`): the token of the member's grant to the first-party client `agent-web`, for the
|
|
10
|
+
* agent's resource on the app's origin. Like every access token, it works only for the resource of
|
|
11
|
+
* its grant, so it is no app session and no MCP token. The agent asks the ontology who a token
|
|
12
|
+
* stands for, and names the token's grant whenever it then acts for the member.
|
|
13
|
+
*/
|
|
14
|
+
export const AGENT_WEB_CLIENT_ID = "agent-web";
|
|
15
|
+
/** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
|
|
16
|
+
export function agentResource(origin) {
|
|
17
|
+
return new URL(`${BASE_PATH}/agent`, origin).href;
|
|
18
|
+
}
|
|
19
|
+
/** Tokens one member may request per minute; the browser keeps one until it is about to expire. */
|
|
20
|
+
export const AGENT_TOKEN_LIMIT = { limit: 60, windowMs: 60_000, maxKeys: 10_000 };
|
|
21
|
+
/** The member's own chat with the agent, the only chat a token opens so far. */
|
|
22
|
+
export function personalChat(userId) {
|
|
23
|
+
return `member:${userId}`;
|
|
24
|
+
}
|
|
25
|
+
const NO_STORE = { "cache-control": "no-store" };
|
|
26
|
+
function json(body, status = 200) {
|
|
27
|
+
return HttpServerResponse.jsonUnsafe(body, { status, headers: NO_STORE });
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `POST /api/ontology/agent/tokens`, for the signed-in member: `{ token, expires_at, chat }`, an
|
|
31
|
+
* access token of their grant to the agent, for their own chat.
|
|
32
|
+
*/
|
|
33
|
+
export function issueAgentToken(store, web, limiter) {
|
|
34
|
+
return (request, member) => Effect.gen(function* () {
|
|
35
|
+
const requestId = yield* RequestId;
|
|
36
|
+
const retryAfter = limiter.take(member.id);
|
|
37
|
+
if (retryAfter !== undefined) {
|
|
38
|
+
return toServerResponse(rateLimited(requestId, "Too many agent tokens; try again in a minute.", retryAfter));
|
|
39
|
+
}
|
|
40
|
+
const expiresAt = new Date(Date.now() + ACCESS_TOKEN_TTL_MS);
|
|
41
|
+
const token = (yield* store.member(member.id)) === undefined
|
|
42
|
+
? undefined
|
|
43
|
+
: yield* web.issue({
|
|
44
|
+
userId: member.id,
|
|
45
|
+
resource: agentResource(publicOrigin(request)),
|
|
46
|
+
expiresAt,
|
|
47
|
+
});
|
|
48
|
+
if (token === undefined) {
|
|
49
|
+
return toServerResponse(forbidden(requestId, "The member is inactive."));
|
|
50
|
+
}
|
|
51
|
+
return json({
|
|
52
|
+
token,
|
|
53
|
+
expires_at: expiresAt.toISOString(),
|
|
54
|
+
chat: personalChat(member.id),
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const IntrospectionRequest = Schema.Struct({
|
|
59
|
+
token: Schema.String.check(Schema.isMaxLength(512)),
|
|
60
|
+
/** The origin the member reached the agent on; by default the one the agent calls this on. */
|
|
61
|
+
origin: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2048))),
|
|
62
|
+
});
|
|
63
|
+
function originOf(value, request) {
|
|
64
|
+
if (value === undefined) {
|
|
65
|
+
return publicOrigin(request);
|
|
66
|
+
}
|
|
67
|
+
const url = URL.canParse(value) ? new URL(value) : undefined;
|
|
68
|
+
return url !== undefined && (url.protocol === "https:" || url.protocol === "http:")
|
|
69
|
+
? url.origin
|
|
70
|
+
: undefined;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
|
|
74
|
+
* agent token a browser showed stands for. `{ active: false }` for any token that is not a live
|
|
75
|
+
* `agent-web` token for the origin, or whose member may no longer sign in.
|
|
76
|
+
*/
|
|
77
|
+
export function introspectAgentToken(store, oauth) {
|
|
78
|
+
return (request) => Effect.gen(function* () {
|
|
79
|
+
const requestId = yield* RequestId;
|
|
80
|
+
const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
|
|
81
|
+
try {
|
|
82
|
+
return JSON.parse(text);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
const decoded = Schema.decodeUnknownResult(IntrospectionRequest)(body, {
|
|
89
|
+
errors: "all",
|
|
90
|
+
onExcessProperty: "error",
|
|
91
|
+
});
|
|
92
|
+
if (Result.isFailure(decoded)) {
|
|
93
|
+
return HttpServerResponse.jsonUnsafe(errorBodyForWire({
|
|
94
|
+
error: "invalid_request",
|
|
95
|
+
detail: "The request body is invalid.",
|
|
96
|
+
requestId,
|
|
97
|
+
issues: schemaIssues(decoded.failure),
|
|
98
|
+
}), { status: 400 });
|
|
99
|
+
}
|
|
100
|
+
const { token } = decoded.success;
|
|
101
|
+
const origin = originOf(decoded.success.origin, request);
|
|
102
|
+
const authenticated = origin === undefined || !token.startsWith(ACCESS_TOKEN_PREFIX)
|
|
103
|
+
? undefined
|
|
104
|
+
: yield* callerOfAccessToken(oauth, token, agentResource(origin));
|
|
105
|
+
const member = authenticated?.caller.kind === "oauth" &&
|
|
106
|
+
authenticated.caller.client.id === AGENT_WEB_CLIENT_ID
|
|
107
|
+
? yield* store.member(authenticated.principal.id)
|
|
108
|
+
: undefined;
|
|
109
|
+
if (authenticated === undefined || member === undefined) {
|
|
110
|
+
return json({ active: false });
|
|
111
|
+
}
|
|
112
|
+
return json({
|
|
113
|
+
active: true,
|
|
114
|
+
member_id: member.principal.id,
|
|
115
|
+
name: member.name,
|
|
116
|
+
roles: member.principal.roles,
|
|
117
|
+
grant_id: authenticated.grantId,
|
|
118
|
+
chat: personalChat(member.principal.id),
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
|
@@ -11,8 +11,8 @@ import { RequestId, crossOriginSession, forbidden, internalError, notInvited, to
|
|
|
11
11
|
import { ACCESS_TOKEN_PREFIX, appSessionResource, publicOrigin, callerOfAccessToken, rejectedAccessToken, } from "./oauth/protocol.js";
|
|
12
12
|
import { CurrentCaller } from "./caller-context.js";
|
|
13
13
|
import { OntologyBackend } from "./runtime-contract.js";
|
|
14
|
-
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_TASK_HEADER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
|
|
15
|
-
import { delegatedAccount } from "./agent/authentication.js";
|
|
14
|
+
import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, logRuntimeRejection, runtimeCredential, } from "./runtime-identity.js";
|
|
15
|
+
import { delegatedAccount, webMember } from "./agent/authentication.js";
|
|
16
16
|
import { agentTaskCaller } from "./agent/task-caller.js";
|
|
17
17
|
import { ErrorSchemas } from "./schemas.js";
|
|
18
18
|
const CLOCK_TOLERANCE_SECONDS = 5;
|
|
@@ -455,7 +455,7 @@ export function sessionMayAuthenticate(request) {
|
|
|
455
455
|
* roles they hold now, while they are active and paired with the agent. Without the header, the
|
|
456
456
|
* runtime may call only the agent's own routes, which authenticate it themselves.
|
|
457
457
|
*/
|
|
458
|
-
function actingMember(actAs, provider) {
|
|
458
|
+
function actingMember(actAs, provider, grant) {
|
|
459
459
|
return Effect.gen(function* () {
|
|
460
460
|
const backend = yield* OntologyBackend;
|
|
461
461
|
if (actAs === undefined) {
|
|
@@ -464,9 +464,17 @@ function actingMember(actAs, provider) {
|
|
|
464
464
|
detail: `The app's agent names the member it acts for in ${ACT_AS_HEADER}.`,
|
|
465
465
|
};
|
|
466
466
|
}
|
|
467
|
+
if (provider === WEB_PROVIDER && grant === undefined) {
|
|
468
|
+
return {
|
|
469
|
+
status: "forbidden",
|
|
470
|
+
detail: `The app's agent names a web member's grant in ${AGENT_GRANT_HEADER}.`,
|
|
471
|
+
};
|
|
472
|
+
}
|
|
467
473
|
const member = backend.agents === undefined
|
|
468
474
|
? undefined
|
|
469
|
-
:
|
|
475
|
+
: provider === WEB_PROVIDER
|
|
476
|
+
? yield* webMember(backend.agents, actAs, grant)
|
|
477
|
+
: yield* backend.agents.actingMember(actAs, provider);
|
|
470
478
|
return member === undefined || member.kind !== "member"
|
|
471
479
|
? {
|
|
472
480
|
status: "forbidden",
|
|
@@ -611,7 +619,7 @@ export function authenticate(credential, verifyToken, options = {}) {
|
|
|
611
619
|
? { status: "rejected" }
|
|
612
620
|
: {
|
|
613
621
|
status: "authenticated",
|
|
614
|
-
|
|
622
|
+
caller: authenticated.caller,
|
|
615
623
|
principal: {
|
|
616
624
|
...authenticated.principal,
|
|
617
625
|
authenticatedVia: authenticated.principal.authenticatedVia ?? "oauth",
|
|
@@ -645,7 +653,7 @@ export function authenticate(credential, verifyToken, options = {}) {
|
|
|
645
653
|
switch (runtime.status) {
|
|
646
654
|
case "valid":
|
|
647
655
|
return agentTask === undefined
|
|
648
|
-
? yield* actingMember(actAs, provider)
|
|
656
|
+
? yield* actingMember(actAs, provider, options.runtime.grant)
|
|
649
657
|
: yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
|
|
650
658
|
case "invalid":
|
|
651
659
|
yield* logRuntimeRejection(runtime.reason);
|
|
@@ -60,6 +60,7 @@ export declare function publicOrigin(request: HttpServerRequest.HttpServerReques
|
|
|
60
60
|
export declare function callerOfAccessToken(store: OAuthStore, token: string, resource: string): Effect.Effect<{
|
|
61
61
|
readonly principal: Principal;
|
|
62
62
|
readonly caller: VerifiedCaller;
|
|
63
|
+
readonly grantId: string;
|
|
63
64
|
} | undefined>;
|
|
64
65
|
export declare const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
65
66
|
export declare const DEVICE_TTL_MS: number;
|
|
@@ -129,6 +129,7 @@ export function callerOfAccessToken(store, token, resource) {
|
|
|
129
129
|
return yield* rejectedAccessToken("client_unavailable", grant.id);
|
|
130
130
|
}
|
|
131
131
|
return {
|
|
132
|
+
grantId: grant.id,
|
|
132
133
|
principal: {
|
|
133
134
|
...scopedPrincipal(member, grant.scope),
|
|
134
135
|
...(grant.identityProvider ? { authenticatedVia: grant.identityProvider } : {}),
|
|
@@ -232,6 +232,29 @@ export interface AgentIdentity {
|
|
|
232
232
|
readonly noticeSha256: string | null;
|
|
233
233
|
readonly noticeVersion: string | null;
|
|
234
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* The grants through which members reach the app's agent from a browser: ordinary OAuth grants of
|
|
237
|
+
* the first-party client `agent-web`, with ordinary access tokens.
|
|
238
|
+
*/
|
|
239
|
+
export interface AgentWebStore {
|
|
240
|
+
/**
|
|
241
|
+
* A new access token of the member's standing grant to the agent at `resource`, granting one
|
|
242
|
+
* first; `undefined` for a member who may not sign in.
|
|
243
|
+
*/
|
|
244
|
+
readonly issue: (input: {
|
|
245
|
+
readonly userId: string;
|
|
246
|
+
readonly resource: string;
|
|
247
|
+
readonly expiresAt: Date;
|
|
248
|
+
}) => Effect.Effect<string | undefined>;
|
|
249
|
+
/**
|
|
250
|
+
* The member an `agent-web` grant acts for, with the roles they hold now: `undefined` when the
|
|
251
|
+
* grant was revoked, is another client's or user's, or the member may no longer sign in.
|
|
252
|
+
*/
|
|
253
|
+
readonly grantMember: (input: {
|
|
254
|
+
readonly grantId: string;
|
|
255
|
+
readonly userId: string;
|
|
256
|
+
}) => Effect.Effect<Principal | undefined>;
|
|
257
|
+
}
|
|
235
258
|
/** A member as the agent names them: their user's name and the roles they hold now. */
|
|
236
259
|
export interface AgentMember {
|
|
237
260
|
readonly name: string;
|
|
@@ -386,6 +409,8 @@ export interface AgentStore {
|
|
|
386
409
|
* not an active member of the app. Absent on stores that predate reviews.
|
|
387
410
|
*/
|
|
388
411
|
readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
|
|
412
|
+
/** The grants behind agent tokens for the web. Absent on stores that predate them. */
|
|
413
|
+
readonly web?: AgentWebStore;
|
|
389
414
|
}
|
|
390
415
|
/** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
|
|
391
416
|
export interface HeldReplyInput {
|
|
@@ -57,6 +57,14 @@ export declare function runtimeTokenVerifier(config: RuntimeIdentityConfig): Run
|
|
|
57
57
|
export declare function logRuntimeRejection(reason: string): Effect.Effect<void>;
|
|
58
58
|
/** How a request may authenticate as the runtime: the verifier and the member it names, if any. */
|
|
59
59
|
export declare const ACT_AS_PROVIDER_HEADER = "x-segmentstream-identity-provider";
|
|
60
|
+
/**
|
|
61
|
+
* The OAuth grant behind the agent token a member's browser showed the agent, when the agent acts
|
|
62
|
+
* for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`) instead of a paired
|
|
63
|
+
* account.
|
|
64
|
+
*/
|
|
65
|
+
export declare const AGENT_GRANT_HEADER = "x-segmentstream-agent-grant";
|
|
66
|
+
/** The identity provider the agent names for a member who reached it with an agent token. */
|
|
67
|
+
export declare const WEB_PROVIDER = "web";
|
|
60
68
|
export interface RuntimeCredential {
|
|
61
69
|
readonly verify: RuntimeTokenVerifier;
|
|
62
70
|
/** The user id in `X-SegmentStream-Act-As`; `undefined` without the header. */
|
|
@@ -64,6 +72,8 @@ export interface RuntimeCredential {
|
|
|
64
72
|
readonly provider?: string;
|
|
65
73
|
/** The task secret in `X-SegmentStream-Agent-Task`; `undefined` without the header. */
|
|
66
74
|
readonly agentTask?: Redacted.Redacted<string>;
|
|
75
|
+
/** The grant in `X-SegmentStream-Agent-Grant`; `undefined` without the header. */
|
|
76
|
+
readonly grant?: string;
|
|
67
77
|
}
|
|
68
78
|
/** The task secret a request presents; `undefined` without the header. */
|
|
69
79
|
export declare function agentTaskSecret(request: HttpServerRequest.HttpServerRequest): Redacted.Redacted<string> | undefined;
|
|
@@ -100,6 +100,14 @@ export function logRuntimeRejection(reason) {
|
|
|
100
100
|
}
|
|
101
101
|
/** How a request may authenticate as the runtime: the verifier and the member it names, if any. */
|
|
102
102
|
export const ACT_AS_PROVIDER_HEADER = "x-segmentstream-identity-provider";
|
|
103
|
+
/**
|
|
104
|
+
* The OAuth grant behind the agent token a member's browser showed the agent, when the agent acts
|
|
105
|
+
* for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`) instead of a paired
|
|
106
|
+
* account.
|
|
107
|
+
*/
|
|
108
|
+
export const AGENT_GRANT_HEADER = "x-segmentstream-agent-grant";
|
|
109
|
+
/** The identity provider the agent names for a member who reached it with an agent token. */
|
|
110
|
+
export const WEB_PROVIDER = "web";
|
|
103
111
|
/** The task secret a request presents; `undefined` without the header. */
|
|
104
112
|
export function agentTaskSecret(request) {
|
|
105
113
|
const secret = request.headers[AGENT_TASK_HEADER]?.trim();
|
|
@@ -113,10 +121,12 @@ export function runtimeCredential(verify, request) {
|
|
|
113
121
|
const actAs = request.headers[ACT_AS_HEADER]?.trim();
|
|
114
122
|
const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim();
|
|
115
123
|
const agentTask = agentTaskSecret(request);
|
|
124
|
+
const grant = request.headers[AGENT_GRANT_HEADER]?.trim();
|
|
116
125
|
return {
|
|
117
126
|
verify,
|
|
118
127
|
actAs: actAs === undefined || actAs === "" ? undefined : actAs,
|
|
119
128
|
...(provider ? { provider } : {}),
|
|
120
129
|
...(agentTask === undefined ? {} : { agentTask }),
|
|
130
|
+
...(grant ? { grant } : {}),
|
|
121
131
|
};
|
|
122
132
|
}
|
package/dist/service/service.js
CHANGED
|
@@ -15,6 +15,7 @@ import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-li
|
|
|
15
15
|
import { memberFileRoutes } from "./member-file-routes.js";
|
|
16
16
|
import { attachmentsLayer } from "./agent/attachments.js";
|
|
17
17
|
import { filesLayer } from "./agent/files.js";
|
|
18
|
+
import { workspaceSourceLayer } from "./agent/source.js";
|
|
18
19
|
import { platformChatArchive } from "./agent/chat-archive.js";
|
|
19
20
|
import { archiveRoutes } from "./agent/archive-routes.js";
|
|
20
21
|
import { makeChatDelivery } from "./chat/delivery.js";
|
|
@@ -409,7 +410,7 @@ export function createOntologyService(ontology, config) {
|
|
|
409
410
|
chatDelivery,
|
|
410
411
|
verifyToken,
|
|
411
412
|
exchangeSession,
|
|
412
|
-
}), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), chatHistory === undefined
|
|
413
|
+
}), preview ? Layer.empty : filesLayer({ plan: built.plan, verifyRuntime }), preview ? Layer.empty : workspaceSourceLayer({ environment: config, verifyRuntime }), chatHistory === undefined
|
|
413
414
|
? Layer.empty
|
|
414
415
|
: archiveRoutes({
|
|
415
416
|
transport: chatHistory,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.101.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",
|