@segmentstream/ontology 0.100.0 → 0.102.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 +35 -0
- package/README.md +14 -12
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -2
- package/dist/runtime/agent-web.d.ts +9 -0
- package/dist/runtime/agent-web.js +100 -0
- package/dist/runtime/agents.js +2 -0
- package/dist/service/agent/authentication.d.ts +7 -1
- package/dist/service/agent/authentication.js +37 -7
- package/dist/service/agent/server.d.ts +3 -0
- package/dist/service/agent/server.js +8 -0
- package/dist/service/agent/web-tokens.d.ts +33 -0
- package/dist/service/agent/web-tokens.js +131 -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 +36 -0
- package/dist/service/runtime-identity.d.ts +10 -0
- package/dist/service/runtime-identity.js +10 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.102.0
|
|
4
|
+
|
|
5
|
+
The agent's limits for people who signed up now apply to the web. Each message a member sends from
|
|
6
|
+
the browser starts a turn that the ontology counts against `limits` when `signUp` created them, by
|
|
7
|
+
email too, on the same counters as their turns on a messenger. Invited and paired members are never
|
|
8
|
+
counted. A turn beyond the limits is refused before it reaches the model with `429 rate_limited` and
|
|
9
|
+
`Retry-After`, and `useAgent()` reports it, like every refusal of the agent's routes, as a
|
|
10
|
+
`SegmentStreamApiError` with its code. The counts use the `limits` the agent last sent with a
|
|
11
|
+
messenger's turn, or the platform's defaults.
|
|
12
|
+
|
|
13
|
+
The agent token introspection (`POST /api/ontology/agent/tokens/introspect`) accepts `turn: true`
|
|
14
|
+
and then answers `limited: { scope, retry_after_seconds }` for a turn beyond the limits.
|
|
15
|
+
|
|
16
|
+
Action required: upgrade the ontology SDK together with the agent SDK. With an ontology SDK released
|
|
17
|
+
before this one, the agent asks again without the turn and web turns stay uncounted until
|
|
18
|
+
2027-02-15; after that date they fail.
|
|
19
|
+
|
|
20
|
+
## 0.101.0
|
|
21
|
+
|
|
22
|
+
A member signed in to the app can reach the app's agent from the browser with an agent token: an
|
|
23
|
+
ordinary OAuth access token (`sso_…`) of the member's grant to the first-party client `agent-web`,
|
|
24
|
+
for the resource `<app origin>/api/ontology/agent`. It works only there, so it is neither an app
|
|
25
|
+
session nor an MCP token.
|
|
26
|
+
|
|
27
|
+
- `POST /api/ontology/agent/tokens`, with the member's app sign-in, answers
|
|
28
|
+
`{ token, expires_at, chat }`: a new hour-long token of the member's one standing grant, for their
|
|
29
|
+
own chat `member:<id>`. API keys and the agent get none.
|
|
30
|
+
- `POST /api/ontology/agent/tokens/introspect`, for the agent only, answers whom a token stands for:
|
|
31
|
+
`{ active, member_id, name, roles, grant_id, chat }`, or `{ active: false }`.
|
|
32
|
+
- Acting for a member who wrote on the web (`X-SegmentStream-Identity-Provider: web`), the agent
|
|
33
|
+
names the grant in `X-SegmentStream-Agent-Grant`; the request runs as the member while the grant
|
|
34
|
+
stands and they are active. Deactivating or blocking the member revokes it.
|
|
35
|
+
|
|
36
|
+
The grants and tokens live in the existing OAuth tables; nothing is migrated.
|
|
37
|
+
|
|
3
38
|
## 0.100.0
|
|
4
39
|
|
|
5
40
|
The built-in permission `workspace_source:read` lets a role read the workspace's deployed code
|
package/README.md
CHANGED
|
@@ -11,6 +11,9 @@ database and the HTTP service under `/api/ontology`. Every read and every action
|
|
|
11
11
|
a permission that the caller's roles grant, and every change to a record goes through an
|
|
12
12
|
action and is kept in history.
|
|
13
13
|
|
|
14
|
+
Guides named by path below, such as `docs/ontology.md`, are in every workspace project;
|
|
15
|
+
`segmentstream sync` keeps them current.
|
|
16
|
+
|
|
14
17
|
TypeScript definitions, handler records and SDK calls use camelCase: `jobTitle`,
|
|
15
18
|
`assignedOwnerId`, `createdAt`, and `changeStatus`. The SDK converts ontology names,
|
|
16
19
|
select identifiers and declared action input fields to snake_case for the generated
|
|
@@ -118,7 +121,7 @@ every aggregate, so that a metric reads only the rows its conditions accept (`m.
|
|
|
118
121
|
it or filter it to one day. Aggregate requests
|
|
119
122
|
take the `notEquals`, `notIn`, `gt`, `gte`, `lt`, `lte`, `contains`, `startsWith`, `endsWith` and
|
|
120
123
|
`inPeriod` operators, the `hour`, `quarter` and `year` granularities and a `timezone`. See
|
|
121
|
-
|
|
124
|
+
ontology metrics (`docs/ontology-metrics.md`).
|
|
122
125
|
|
|
123
126
|
SDK 0.14.0 lets the app's own agent call the service as a paired member (see
|
|
124
127
|
[Agents](#agents)). Its migration adds the agent's runtime tables.
|
|
@@ -132,7 +135,7 @@ fields and business relationships. Existing history captures immutable snapshots
|
|
|
132
135
|
service wakes the publisher after commits. Upgrade and redeploy to activate it; workspace
|
|
133
136
|
configuration can intentionally exclude exported data. Automatic repairs build a private replacement
|
|
134
137
|
while the serving analytical projection keeps receiving changes and answering queries. See
|
|
135
|
-
|
|
138
|
+
replication lifecycle (`docs/ontology-replication.md`).
|
|
136
139
|
The next release supports schema changes during active copies: property renames adapt views over retained
|
|
137
140
|
JSON, and restored or newly included data is exported through scoped resumable scans. No manual pause
|
|
138
141
|
is required for deployment or recovery. Explicit opt-outs and supported-writer fences remain in force.
|
|
@@ -141,7 +144,7 @@ SDK 0.13.0 writes manifest version 6. Relationships may target warehouse-backed
|
|
|
141
144
|
stored or warehouse-backed entities, matched by value through `on`, and `unique` is allowed on
|
|
142
145
|
warehouse-backed properties as an unenforced assertion. Upgrading: 0.12 accepted an explicit `onDelete`, or `optional: true`, on a
|
|
143
146
|
warehouse → stored relationship; 0.13.0 `check` refuses both, so remove them. See
|
|
144
|
-
|
|
147
|
+
ontology metrics (`docs/ontology-metrics.md#relationships`).
|
|
145
148
|
|
|
146
149
|
SDK 0.13.0 also serves aggregates. Upgrade notes:
|
|
147
150
|
|
|
@@ -161,8 +164,7 @@ SDK 0.13.0 also serves aggregates. Upgrade notes:
|
|
|
161
164
|
warehouse-backed entities through aggregates. Grant those to `member` by name
|
|
162
165
|
(`acme_sales:read`), or keep the `invited` policy.
|
|
163
166
|
|
|
164
|
-
See
|
|
165
|
-
and [ontology analytics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-aggregates-spec.md).
|
|
167
|
+
See `docs/ontology-metrics.md`.
|
|
166
168
|
|
|
167
169
|
## File storage
|
|
168
170
|
|
|
@@ -227,7 +229,7 @@ allow more types, then check, migrate and redeploy the ontology. The app SDK sto
|
|
|
227
229
|
0.13.1 or later uses `application/octet-stream` when the browser supplies no MIME type.
|
|
228
230
|
REST callers should supply that type themselves for unknown formats.
|
|
229
231
|
|
|
230
|
-
See
|
|
232
|
+
See `docs/ontology.md#file-transfers`
|
|
231
233
|
for upload tickets, transfer grants and retained revisions.
|
|
232
234
|
|
|
233
235
|
SDK 0.56.0 adds server-side file transfers through `Files`. In an action, declare
|
|
@@ -238,7 +240,7 @@ authorized retained revision for sending to another provider. Use `files: []` wh
|
|
|
238
240
|
preparation only reads files and has no connections. Callers of staging actions provide
|
|
239
241
|
an idempotency key; workflow action calls derive a stable key from the run, step and input
|
|
240
242
|
when omitted. Streams stay within the step; carry tickets and references between steps.
|
|
241
|
-
See
|
|
243
|
+
See `docs/ontology.md#file-transfers`
|
|
242
244
|
for the API and recovery rules.
|
|
243
245
|
|
|
244
246
|
Buffered `get`/`post`/`request` calls receive the provider's response through a streamed
|
|
@@ -263,7 +265,7 @@ commit. They are never replayed. This declaration is independent of
|
|
|
263
265
|
timeouts, cancellation, permission failures, cleanup failures or uncertain commits.
|
|
264
266
|
Custom service runtime implementations own their retry policy; wrappers around
|
|
265
267
|
the default backend are not replayed. See
|
|
266
|
-
|
|
268
|
+
action deadlines and load (`docs/ontology.md#action-deadlines-and-load`)
|
|
267
269
|
for the full replay contract.
|
|
268
270
|
|
|
269
271
|
An action with `hints: { connectionsReadOnly: true, destructive: false }` may read
|
|
@@ -905,7 +907,7 @@ selects. Metric queries lock nothing: lock the record the decision depends on wi
|
|
|
905
907
|
`forUpdate`. Balance
|
|
906
908
|
metrics, model metrics and workflow steps stay with the warehouse's `query_metrics`.
|
|
907
909
|
`aggregate`, the earlier name of `queryMetrics`, remains as a deprecated alias.
|
|
908
|
-
See
|
|
910
|
+
See fresh metric queries inside an action (`docs/ontology.md#fresh-metric-queries-inside-an-action`).
|
|
909
911
|
|
|
910
912
|
## Permissions
|
|
911
913
|
|
|
@@ -1258,7 +1260,7 @@ API from the ontology's MCP server: each tool in the lock, written by
|
|
|
1258
1260
|
confirmed. Fixed values the connection declares are removed from the tool's input and added to each
|
|
1259
1261
|
call, and backend-next admits only the declared tools and values. A toolset has no records. It is
|
|
1260
1262
|
served over MCP only: not by the REST API, to workflows or under the OAuth `ontology:read` scope.
|
|
1261
|
-
See
|
|
1263
|
+
See `docs/ontology.md#provider-mcp-tools-toolsets` and `docs/connections.md#declare-an-mcp-server`.
|
|
1262
1264
|
|
|
1263
1265
|
## Agents
|
|
1264
1266
|
|
|
@@ -1728,9 +1730,9 @@ Apache-2.0
|
|
|
1728
1730
|
|
|
1729
1731
|
## Entity sources and metric queries
|
|
1730
1732
|
|
|
1731
|
-
Entities with a warehouse source declare mapped properties, metrics and relationships without ontology storage tables or actions. `find`, `query` and `get` read observations through the workspace's warehouse API, with opaque source-key record IDs and bounded, permission-checked relationship reads. See
|
|
1733
|
+
Entities with a warehouse source declare mapped properties, metrics and relationships without ontology storage tables or actions. `find`, `query` and `get` read observations through the workspace's warehouse API, with opaque source-key record IDs and bounded, permission-checked relationship reads. See warehouse record reads (`docs/ontology-record-reads.md`). Stored entities may declare metrics too; they are computed over the entity's replication view, whose columns are the properties' snake_case names. See ontology metrics (`docs/ontology-metrics.md`) for declaration rules, metric query paths, source verification and workspace authorization.
|
|
1732
1734
|
|
|
1733
|
-
See
|
|
1735
|
+
See release order and rollback (`docs/agent-chat-delivery-migration.md`).
|
|
1734
1736
|
|
|
1735
1737
|
### Telegram link previews
|
|
1736
1738
|
|
package/dist/index.d.ts
CHANGED
|
@@ -86,12 +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, WebTurnLimit, 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
93
|
export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
|
|
94
|
-
export {
|
|
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";
|
|
95
96
|
export type { RuntimeIdentityConfig } from "./service/runtime-identity.js";
|
|
96
97
|
export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
|
|
97
98
|
export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.js";
|
package/dist/index.js
CHANGED
|
@@ -54,10 +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
59
|
export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
|
|
60
|
-
|
|
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";
|
|
61
63
|
// The MCP server the service serves beside the HTTP API.
|
|
62
64
|
export { MCP_PATH, MCP_PROTOCOL_VERSIONS } from "./service/mcp/server.js";
|
|
63
65
|
export { MCP_TOOL_NAME_MAX_LENGTH, mcpToolName } from "./names.js";
|
|
@@ -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,100 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { CHANNEL_USERS_TABLE, 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 { completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, } from "./agent-counters.js";
|
|
7
|
+
import { channelUsersAvailable } from "./member-tables.js";
|
|
8
|
+
import { sqlOAuthStore } from "./oauth.js";
|
|
9
|
+
import { isMemberBlocked } from "./principals.js";
|
|
10
|
+
import { isRecordId } from "./records.js";
|
|
11
|
+
const GRANTS = `"${OAUTH_GRANTS_TABLE}"`;
|
|
12
|
+
/**
|
|
13
|
+
* Agent tokens in the ontology's OAuth tables, as channel sessions are: one standing grant per
|
|
14
|
+
* member and resource for the first-party client `agent-web`, and a new access token on each
|
|
15
|
+
* request. Blocking or deactivating the member revokes the grant with every other one of theirs.
|
|
16
|
+
*/
|
|
17
|
+
export function sqlAgentWebStore(ontology, sql) {
|
|
18
|
+
const oauth = sqlOAuthStore(ontology, sql);
|
|
19
|
+
return {
|
|
20
|
+
issue: ({ userId, resource, expiresAt }) => sql
|
|
21
|
+
.withTransaction(Effect.gen(function* () {
|
|
22
|
+
// Same lock as the member's lifecycle operations, so a blocked member never gets one.
|
|
23
|
+
const [member] = yield* sql.unsafe(`SELECT "kind"::text AS "kind", "active" FROM "${USER_TABLE}"
|
|
24
|
+
WHERE "id" = $1::uuid FOR SHARE`, [userId]);
|
|
25
|
+
if (member?.kind !== "member" ||
|
|
26
|
+
!member.active ||
|
|
27
|
+
(yield* isMemberBlocked(sql, userId))) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
yield* sql.unsafe(`INSERT INTO "${OAUTH_CLIENTS_TABLE}" ("id", "name", "redirect_uris", "auth_method")
|
|
31
|
+
VALUES ($1, $1, '[]'::jsonb, 'none') ON CONFLICT ("id") DO NOTHING`, [AGENT_WEB_CLIENT_ID]);
|
|
32
|
+
const [standing] = yield* sql.unsafe(`SELECT "id"::text AS "id" FROM ${GRANTS}
|
|
33
|
+
WHERE "user_id" = $1::uuid AND "client_id" = $2 AND "resource" = $3
|
|
34
|
+
AND "revoked_at" IS NULL ORDER BY "created_at" LIMIT 1`, [userId, AGENT_WEB_CLIENT_ID, resource]);
|
|
35
|
+
const grantId = standing?.id ?? randomUUID();
|
|
36
|
+
if (standing === undefined) {
|
|
37
|
+
yield* oauth.saveGrant({
|
|
38
|
+
id: grantId,
|
|
39
|
+
clientId: AGENT_WEB_CLIENT_ID,
|
|
40
|
+
userId,
|
|
41
|
+
scope: FULL_SCOPE,
|
|
42
|
+
resource,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const token = newSecret(ACCESS_TOKEN_PREFIX);
|
|
46
|
+
yield* oauth.saveTokens([
|
|
47
|
+
{ hash: secretHash(token), grantId, kind: "access", expiresAt },
|
|
48
|
+
]);
|
|
49
|
+
return token;
|
|
50
|
+
}))
|
|
51
|
+
.pipe(Effect.orDie),
|
|
52
|
+
grantMember: ({ grantId, userId }) => Effect.gen(function* () {
|
|
53
|
+
if (!isRecordId(grantId) || !isRecordId(userId)) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const [standing] = yield* sql
|
|
57
|
+
.unsafe(`SELECT 1 FROM ${GRANTS} WHERE "id" = $1::uuid AND "user_id" = $2::uuid
|
|
58
|
+
AND "client_id" = $3 AND "revoked_at" IS NULL`, [grantId, userId, AGENT_WEB_CLIENT_ID])
|
|
59
|
+
.pipe(Effect.orDie);
|
|
60
|
+
return standing === undefined ? undefined : yield* oauth.memberPrincipal(userId);
|
|
61
|
+
}),
|
|
62
|
+
countTurn: (userId) => Effect.gen(function* () {
|
|
63
|
+
// @legacy ontology.pre-upgrade-database-tolerance
|
|
64
|
+
if (!isRecordId(userId) || !(yield* channelUsersAvailable(sql))) {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
|
|
68
|
+
FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [userId]);
|
|
69
|
+
if (lifecycle?.signed_up !== true) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
const limits = yield* effectiveChannelLimits(sql);
|
|
73
|
+
for (const [scope, subject, window] of [
|
|
74
|
+
["turnsPerMinute", userId, "minute"],
|
|
75
|
+
["turnsPerDay", userId, "day"],
|
|
76
|
+
["workspaceTurnsPerDay", "workspace", "day"],
|
|
77
|
+
]) {
|
|
78
|
+
const limited = yield* countAgentAttempt(sql, {
|
|
79
|
+
scope,
|
|
80
|
+
subject,
|
|
81
|
+
window,
|
|
82
|
+
limit: scope === "workspaceTurnsPerDay"
|
|
83
|
+
? limits.workspaceTurnsPerDay
|
|
84
|
+
: limits.perSender[scope],
|
|
85
|
+
});
|
|
86
|
+
if (limited !== undefined) {
|
|
87
|
+
// The refusal the browser gets is this window's notice, on every channel.
|
|
88
|
+
if (limited.notificationId !== undefined) {
|
|
89
|
+
yield* completeAgentLimitNotice(sql, {
|
|
90
|
+
notificationId: limited.notificationId,
|
|
91
|
+
delivered: true,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
}).pipe(Effect.orDie),
|
|
99
|
+
};
|
|
100
|
+
}
|
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
|
}
|
|
@@ -27,11 +27,17 @@ export declare function authenticateAgentCaller(input: {
|
|
|
27
27
|
readonly caller: AttachmentCaller;
|
|
28
28
|
readonly response?: undefined;
|
|
29
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>;
|
|
30
35
|
/**
|
|
31
36
|
* Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
|
|
32
37
|
* on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
|
|
33
38
|
* refused. `member` is the member with the roles they hold now, or `undefined` when the header names
|
|
34
|
-
* nobody who is active and paired with the agent
|
|
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.
|
|
35
41
|
*/
|
|
36
42
|
export declare function authenticateAgentRuntimeMember(input: {
|
|
37
43
|
readonly request: HttpServerRequest.HttpServerRequest;
|
|
@@ -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. */
|
|
@@ -34,11 +34,16 @@ export function authenticateAgentCaller(input) {
|
|
|
34
34
|
return { ok: false, response: refused };
|
|
35
35
|
}
|
|
36
36
|
const actAs = request.headers[ACT_AS_HEADER]?.trim() ?? "";
|
|
37
|
+
const grant = request.headers[AGENT_GRANT_HEADER]?.trim() ?? "";
|
|
37
38
|
const member = actAs === ""
|
|
38
39
|
? undefined
|
|
39
|
-
:
|
|
40
|
-
?
|
|
41
|
-
|
|
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);
|
|
42
47
|
if (member === undefined) {
|
|
43
48
|
return denied(input.allowUnpairedMember
|
|
44
49
|
? notFound(requestId, "Attachment not found.")
|
|
@@ -47,6 +52,31 @@ export function authenticateAgentCaller(input) {
|
|
|
47
52
|
return agentCaller(request, requestId, member);
|
|
48
53
|
});
|
|
49
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
|
+
}
|
|
50
80
|
/**
|
|
51
81
|
* The answer refusing an agent route's bearer token unless it is the deployment's own runtime token
|
|
52
82
|
* and the request presents no task's secret; `undefined` when it is admitted.
|
|
@@ -77,7 +107,8 @@ function refuseUnlessRuntime(request, token, verify) {
|
|
|
77
107
|
* Authenticate the deployment's own runtime acting for the member `X-SegmentStream-Act-As` names,
|
|
78
108
|
* on a route only that runtime calls: an API key, with delegation or not, and a task's secret are
|
|
79
109
|
* refused. `member` is the member with the roles they hold now, or `undefined` when the header names
|
|
80
|
-
* nobody who is active and paired with the agent
|
|
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.
|
|
81
112
|
*/
|
|
82
113
|
export function authenticateAgentRuntimeMember(input) {
|
|
83
114
|
return Effect.gen(function* () {
|
|
@@ -88,8 +119,7 @@ export function authenticateAgentRuntimeMember(input) {
|
|
|
88
119
|
if (refused !== undefined) {
|
|
89
120
|
return { ok: false, response: refused };
|
|
90
121
|
}
|
|
91
|
-
const
|
|
92
|
-
const member = actAs === "" ? undefined : yield* agents.actingMember(actAs);
|
|
122
|
+
const member = yield* runtimeActingMember(request, agents);
|
|
93
123
|
return { ok: true, member: member?.kind === "member" ? member : undefined };
|
|
94
124
|
});
|
|
95
125
|
}
|
|
@@ -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, store.web, backend.oauth)));
|
|
438
|
+
}
|
|
431
439
|
}));
|
|
432
440
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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. With `turn: true` the
|
|
30
|
+
* member is starting a turn: someone `signUp` created has it counted against the agent's limits,
|
|
31
|
+
* and the answer names the limit it exceeds as `limited`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
|
|
@@ -0,0 +1,131 @@
|
|
|
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
|
+
/** The token starts a turn: count it against the agent's limits for people who signed up. */
|
|
63
|
+
turn: Schema.optionalKey(Schema.Boolean),
|
|
64
|
+
});
|
|
65
|
+
function originOf(value, request) {
|
|
66
|
+
if (value === undefined) {
|
|
67
|
+
return publicOrigin(request);
|
|
68
|
+
}
|
|
69
|
+
const url = URL.canParse(value) ? new URL(value) : undefined;
|
|
70
|
+
return url !== undefined && (url.protocol === "https:" || url.protocol === "http:")
|
|
71
|
+
? url.origin
|
|
72
|
+
: undefined;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
|
|
76
|
+
* agent token a browser showed stands for. `{ active: false }` for any token that is not a live
|
|
77
|
+
* `agent-web` token for the origin, or whose member may no longer sign in. With `turn: true` the
|
|
78
|
+
* member is starting a turn: someone `signUp` created has it counted against the agent's limits,
|
|
79
|
+
* and the answer names the limit it exceeds as `limited`.
|
|
80
|
+
*/
|
|
81
|
+
export function introspectAgentToken(store, web, oauth) {
|
|
82
|
+
return (request) => Effect.gen(function* () {
|
|
83
|
+
const requestId = yield* RequestId;
|
|
84
|
+
const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
|
|
85
|
+
try {
|
|
86
|
+
return JSON.parse(text);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
const decoded = Schema.decodeUnknownResult(IntrospectionRequest)(body, {
|
|
93
|
+
errors: "all",
|
|
94
|
+
onExcessProperty: "error",
|
|
95
|
+
});
|
|
96
|
+
if (Result.isFailure(decoded)) {
|
|
97
|
+
return HttpServerResponse.jsonUnsafe(errorBodyForWire({
|
|
98
|
+
error: "invalid_request",
|
|
99
|
+
detail: "The request body is invalid.",
|
|
100
|
+
requestId,
|
|
101
|
+
issues: schemaIssues(decoded.failure),
|
|
102
|
+
}), { status: 400 });
|
|
103
|
+
}
|
|
104
|
+
const { token } = decoded.success;
|
|
105
|
+
const origin = originOf(decoded.success.origin, request);
|
|
106
|
+
const authenticated = origin === undefined || !token.startsWith(ACCESS_TOKEN_PREFIX)
|
|
107
|
+
? undefined
|
|
108
|
+
: yield* callerOfAccessToken(oauth, token, agentResource(origin));
|
|
109
|
+
const member = authenticated?.caller.kind === "oauth" &&
|
|
110
|
+
authenticated.caller.client.id === AGENT_WEB_CLIENT_ID
|
|
111
|
+
? yield* store.member(authenticated.principal.id)
|
|
112
|
+
: undefined;
|
|
113
|
+
if (authenticated === undefined || member === undefined) {
|
|
114
|
+
return json({ active: false });
|
|
115
|
+
}
|
|
116
|
+
const limited = decoded.success.turn === true ? yield* web.countTurn(member.principal.id) : undefined;
|
|
117
|
+
return json({
|
|
118
|
+
active: true,
|
|
119
|
+
member_id: member.principal.id,
|
|
120
|
+
name: member.name,
|
|
121
|
+
roles: member.principal.roles,
|
|
122
|
+
grant_id: authenticated.grantId,
|
|
123
|
+
chat: personalChat(member.principal.id),
|
|
124
|
+
...(limited === undefined
|
|
125
|
+
? {}
|
|
126
|
+
: {
|
|
127
|
+
limited: { scope: limited.scope, retry_after_seconds: limited.retryAfterSeconds },
|
|
128
|
+
}),
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
}
|
|
@@ -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,40 @@ 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
|
+
/**
|
|
258
|
+
* Counts one turn a member starts on the web against the agent's limits when `signUp` created
|
|
259
|
+
* them, as their turns on a messenger are counted, on the same counters; invited and paired
|
|
260
|
+
* members are never counted. The limit the turn exceeds, or `undefined` when it may run.
|
|
261
|
+
*/
|
|
262
|
+
readonly countTurn: (userId: string) => Effect.Effect<WebTurnLimit | undefined>;
|
|
263
|
+
}
|
|
264
|
+
/** The limit a member's turn on the web exceeds, and when the next one may run. */
|
|
265
|
+
export interface WebTurnLimit {
|
|
266
|
+
readonly scope: AgentLimitScope;
|
|
267
|
+
readonly retryAfterSeconds: number;
|
|
268
|
+
}
|
|
235
269
|
/** A member as the agent names them: their user's name and the roles they hold now. */
|
|
236
270
|
export interface AgentMember {
|
|
237
271
|
readonly name: string;
|
|
@@ -386,6 +420,8 @@ export interface AgentStore {
|
|
|
386
420
|
* not an active member of the app. Absent on stores that predate reviews.
|
|
387
421
|
*/
|
|
388
422
|
readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
|
|
423
|
+
/** The grants behind agent tokens for the web. Absent on stores that predate them. */
|
|
424
|
+
readonly web?: AgentWebStore;
|
|
389
425
|
}
|
|
390
426
|
/** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
|
|
391
427
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.102.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",
|