@segmentstream/ontology 0.100.0 → 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 +18 -0
- 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 +61 -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 +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/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
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
|
+
|
|
3
21
|
## 0.100.0
|
|
4
22
|
|
|
5
23
|
The built-in permission `workspace_source:read` lets a role read the workspace's deployed code
|
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, 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,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
|
}
|
|
@@ -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, backend.oauth)));
|
|
438
|
+
}
|
|
431
439
|
}));
|
|
432
440
|
}
|
|
@@ -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/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",
|