@segmentstream/ontology 0.197.1 → 0.199.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/analyze.d.ts +2 -0
  3. package/dist/analyze.js +17 -0
  4. package/dist/bin/check.js +12 -0
  5. package/dist/bin/migrate.js +1 -1
  6. package/dist/connection.d.ts +109 -6
  7. package/dist/connection.js +132 -17
  8. package/dist/diagnostics.d.ts +3 -3
  9. package/dist/diagnostics.js +2 -0
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/manifest.d.ts +28 -0
  13. package/dist/manifest.js +6 -0
  14. package/dist/migrate/apply.d.ts +7 -1
  15. package/dist/migrate/apply.js +12 -3
  16. package/dist/migrate/model.d.ts +8 -0
  17. package/dist/migrate/plan.js +14 -1
  18. package/dist/owned-workflows.d.ts +10 -0
  19. package/dist/owned-workflows.js +16 -0
  20. package/dist/runtime/agents.js +2 -0
  21. package/dist/runtime/owner-departures.d.ts +35 -0
  22. package/dist/runtime/owner-departures.js +64 -0
  23. package/dist/runtime/pipeline.d.ts +15 -1
  24. package/dist/runtime/pipeline.js +67 -1
  25. package/dist/runtime/principals.d.ts +17 -2
  26. package/dist/runtime/principals.js +33 -2
  27. package/dist/runtime/service-binding.js +17 -3
  28. package/dist/runtime/workflow-starts.d.ts +108 -8
  29. package/dist/runtime/workflow-starts.js +276 -49
  30. package/dist/service/agent/attachments.js +27 -6
  31. package/dist/service/agent/authentication.d.ts +5 -0
  32. package/dist/service/agent/authentication.js +1 -1
  33. package/dist/service/agent/protocol.d.ts +4 -0
  34. package/dist/service/agent/protocol.js +4 -0
  35. package/dist/service/agent/server.js +7 -4
  36. package/dist/service/agent/task-caller.d.ts +4 -2
  37. package/dist/service/agent/task-caller.js +4 -2
  38. package/dist/service/authentication.d.ts +7 -0
  39. package/dist/service/authentication.js +12 -0
  40. package/dist/service/channel/telegram-pairing.d.ts +9 -0
  41. package/dist/service/channel/telegram-pairing.js +114 -0
  42. package/dist/service/chat/envelope.d.ts +7 -0
  43. package/dist/service/chat/envelope.js +15 -0
  44. package/dist/service/chat/providers/telegram.d.ts +2 -0
  45. package/dist/service/chat/providers/telegram.js +1 -1
  46. package/dist/service/config.d.ts +6 -0
  47. package/dist/service/connections.d.ts +17 -2
  48. package/dist/service/connections.js +21 -1
  49. package/dist/service/errors.js +27 -1
  50. package/dist/service/member-files.js +6 -0
  51. package/dist/service/operations.d.ts +8 -0
  52. package/dist/service/operations.js +11 -4
  53. package/dist/service/owned-connections.d.ts +80 -0
  54. package/dist/service/owned-connections.js +488 -0
  55. package/dist/service/runtime-contract.d.ts +34 -0
  56. package/dist/service/schemas.d.ts +2 -0
  57. package/dist/service/service.js +26 -2
  58. package/dist/service/workflow-errors.d.ts +12 -1
  59. package/dist/service/workflow-errors.js +15 -2
  60. package/dist/service/workflows.d.ts +22 -0
  61. package/dist/service/workflows.js +358 -48
  62. package/dist/start-recovery-contract.d.ts +17 -1
  63. package/dist/start-recovery-contract.js +11 -1
  64. package/dist/start-recovery.js +4 -1
  65. package/dist/storage/tables.d.ts +15 -0
  66. package/dist/storage/tables.js +21 -0
  67. package/dist/workflow.d.ts +20 -2
  68. package/package.json +1 -1
@@ -4,8 +4,10 @@ import { taskSecretSha256 } from "./task-start.js";
4
4
  /** How a principal that a task's secret authenticated says it authenticated. */
5
5
  export const AGENT_TASK_AUTHENTICATION = "agent_task";
6
6
  /**
7
- * The live task a secret names and the user it acts as: its workflow's user, resolved as the
8
- * workflow's steps resolve it, with the roles it holds now. Refused when the secret matches no live
7
+ * The live task a secret names and the user it acts as: its workflow's user, resolved as the steps
8
+ * of a run with no owner resolve it, with the roles it holds now. A task a step of an owned run
9
+ * starts acts as the workflow's user too, never as the run's owner, so its owned connection calls
10
+ * fail with `owner_required` (docs/agent-tasks-spec.md, decision 2). Refused when the secret matches no live
9
11
  * task (an unknown secret, a terminal task or one past its deadline) or the workflow user is
10
12
  * missing or inactive. The ontology resolves the identity from the task; the caller never names it.
11
13
  */
@@ -163,6 +163,13 @@ export declare function neonAuthSessionExchange(config: {
163
163
  * with same-origin `POST`s, so a change without one is refused too.
164
164
  */
165
165
  export declare function sessionMayAuthenticate(request: HttpServerRequest.HttpServerRequest): boolean;
166
+ /**
167
+ * Whether a browser sent this request from another site: it names an origin other than the app's
168
+ * own, or Fetch Metadata says it is not same-origin. A server-side caller sends neither header.
169
+ * Routes that change something without a credential refuse such a request, as the session cookie
170
+ * is refused on one ({@link sessionMayAuthenticate}).
171
+ */
172
+ export declare function crossSiteRequest(request: HttpServerRequest.HttpServerRequest): boolean;
166
173
  type Authenticated = {
167
174
  readonly status: "authenticated";
168
175
  readonly principal: Principal;
@@ -452,6 +452,18 @@ export function sessionMayAuthenticate(request) {
452
452
  const origin = request.headers.origin;
453
453
  return origin !== undefined && origin === requestOrigin(request);
454
454
  }
455
+ /**
456
+ * Whether a browser sent this request from another site: it names an origin other than the app's
457
+ * own, or Fetch Metadata says it is not same-origin. A server-side caller sends neither header.
458
+ * Routes that change something without a credential refuse such a request, as the session cookie
459
+ * is refused on one ({@link sessionMayAuthenticate}).
460
+ */
461
+ export function crossSiteRequest(request) {
462
+ const site = request.headers["sec-fetch-site"];
463
+ const origin = request.headers.origin;
464
+ return ((site !== undefined && site !== "same-origin" && site !== "none") ||
465
+ (origin !== undefined && origin !== requestOrigin(request)));
466
+ }
455
467
  /**
456
468
  * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
457
469
  * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,
@@ -0,0 +1,9 @@
1
+ import { type TokenVerifier } from "../authentication.js";
2
+ import type { OntologyServiceConfig } from "../config.js";
3
+ import type { ConnectionTransportFactory } from "../connections.js";
4
+ import { RequestId } from "../errors.js";
5
+ import { OntologyBackend } from "../runtime-contract.js";
6
+ import type { ChannelAppProvider } from "./provider.js";
7
+ /** A public button names the request. Telegram proves its original sender, then signs
8
+ * a fresh challenge in the browser that completed Cloud login. Neither link is a credential. */
9
+ export declare function telegramPairingLayer(config: OntologyServiceConfig, connections: ConnectionTransportFactory, telegram: ChannelAppProvider, connection: string, verifyToken: TokenVerifier): import("effect/Layer").Layer<never, never, OntologyBackend | import("effect/unstable/http/HttpRouter").HttpRouter | import("effect/unstable/http/HttpRouter").Request<"Requires", RequestId> | import("effect/unstable/http/HttpRouter").Request<"Error", import("effect/unstable/http/HttpServerError").HttpServerError>>;
@@ -0,0 +1,114 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { Effect, Redacted } from "effect";
3
+ import { HttpServerResponse } from "effect/unstable/http";
4
+ import { use as routes } from "effect/unstable/http/HttpRouter";
5
+ import { CurrentPrincipal, sessionMayAuthenticate, withPrincipal, } from "../authentication.js";
6
+ import { FEDERATION_TOKEN_PREFIX } from "../../runtime/federation.js";
7
+ import { botUsername } from "../chat/providers/telegram.js";
8
+ import { identityToken } from "../operations.js";
9
+ import { RequestId } from "../errors.js";
10
+ import { clientAddress, fixedWindowLimiter } from "../rate-limit.js";
11
+ import { OntologyBackend } from "../runtime-contract.js";
12
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
13
+ const launch = new RegExp("^sslink_(" + UUID + ")$");
14
+ const finish = new RegExp("^ssverify_(" + UUID + ")_([A-Za-z0-9_-]{32})$");
15
+ const json = (status, body, cookie) => HttpServerResponse.jsonUnsafe(body, {
16
+ status,
17
+ headers: {
18
+ "cache-control": "no-store",
19
+ ...(cookie && { "set-cookie": cookie }),
20
+ },
21
+ });
22
+ /** A public button names the request. Telegram proves its original sender, then signs
23
+ * a fresh challenge in the browser that completed Cloud login. Neither link is a credential. */
24
+ export function telegramPairingLayer(config, connections, telegram, connection, verifyToken) {
25
+ const suffix = config.workspaceId.replace(/[^A-Za-z0-9_-]/g, "_");
26
+ const cookieName = (id) => "__Host-ss_telegram_link." + suffix + "." + id;
27
+ const cookie = (id, value, age) => cookieName(id) + "=" + value + "; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=" + age;
28
+ const limiter = fixedWindowLimiter({ limit: 30, windowMs: 60000, maxKeys: 10000 });
29
+ return routes((router) => Effect.gen(function* () {
30
+ const backend = yield* OntologyBackend;
31
+ const store = backend.agents;
32
+ if (!store?.telegramLaunchPairing) {
33
+ return;
34
+ }
35
+ const read = store.telegramLaunchPairing;
36
+ yield* router.add("POST", "/api/ontology/agent/telegram-link", (request) => Effect.gen(function* () {
37
+ if (!sessionMayAuthenticate(request)) {
38
+ return json(403, { error: "cross_origin_session" });
39
+ }
40
+ if (limiter.take(clientAddress(request)) !== undefined) {
41
+ return json(429, { error: "rate_limited" });
42
+ }
43
+ const assertion = yield* request.text;
44
+ if (assertion.length > 16384) {
45
+ return json(400, { error: "invalid_assertion" });
46
+ }
47
+ const transport = connections({
48
+ identityToken: identityToken(request),
49
+ audit: {
50
+ action: "agent.telegram_link",
51
+ principalId: "anonymous",
52
+ requestId: yield* RequestId,
53
+ },
54
+ });
55
+ const identity = yield* telegram.verify(assertion, { connections: transport });
56
+ if (!identity) {
57
+ return json(403, { error: "invalid_assertion" });
58
+ }
59
+ const start = new URLSearchParams(assertion).get("start_param") ?? "";
60
+ const initial = launch.exec(start);
61
+ const completed = finish.exec(start);
62
+ const id = initial?.[1] ?? completed?.[1];
63
+ if (!id) {
64
+ return json(400, { error: "invalid_launch" });
65
+ }
66
+ const pairing = yield* read(id, identity.externalId);
67
+ if (!pairing) {
68
+ return json(403, { error: "pairing_unavailable" });
69
+ }
70
+ if (initial) {
71
+ const username = yield* botUsername(transport, connection);
72
+ if (!username) {
73
+ return json(503, { error: "bot_unavailable" });
74
+ }
75
+ const nonce = randomBytes(24).toString("base64url");
76
+ const continuation = "ssverify_" + id + "_" + nonce;
77
+ return json(200, { reopen: "https://t.me/" + username + "?startapp=" + continuation }, cookie(id, continuation, 600));
78
+ }
79
+ if (request.cookies[cookieName(id)] !== start) {
80
+ return json(403, { error: "browser_mismatch" });
81
+ }
82
+ const token = request.cookies["__Host-ss_oidc_session." + suffix];
83
+ if (!token?.startsWith(FEDERATION_TOKEN_PREFIX)) {
84
+ return json(401, { error: "cloud_login_required" });
85
+ }
86
+ return yield* withPrincipal(Redacted.make(token), verifyToken, backend, Effect.gen(function* () {
87
+ const member = yield* CurrentPrincipal;
88
+ if (member.kind !== "member" || member.authenticatedVia !== "oidc") {
89
+ return json(403, { error: "cloud_login_required" });
90
+ }
91
+ const linked = yield* store
92
+ .approvePairing({
93
+ codeHash: pairing.codeHash,
94
+ userId: member.id,
95
+ identityId: randomUUID(),
96
+ })
97
+ .pipe(Effect.catchTag("IdentityInUse", () => Effect.succeed("conflict")));
98
+ if (linked === "conflict") {
99
+ return json(409, { error: "identity_in_use" });
100
+ }
101
+ if (!linked) {
102
+ const owner = yield* store.findIdentity({
103
+ provider: "telegram",
104
+ externalId: identity.externalId,
105
+ });
106
+ if (!owner || owner.revokedAt !== null || owner.userId !== member.id) {
107
+ return json(410, { error: "pairing_expired" });
108
+ }
109
+ }
110
+ return json(200, { linked: true }, cookie(id, "", 0));
111
+ }));
112
+ }));
113
+ }));
114
+ }
@@ -1,5 +1,6 @@
1
1
  import { Context, Effect, Schema } from "effect";
2
2
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
+ import type { ValidationIssue } from "../../runtime/errors.js";
3
4
  import type { CallerContext } from "../caller-context.js";
4
5
  declare const RuntimeEnvelope: Schema.Struct<{
5
6
  readonly version: Schema.Literal<1>;
@@ -141,4 +142,10 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
141
142
  readonly operation_id?: string | undefined;
142
143
  };
143
144
  }, ActionRejected | PermissionDenied, never>;
145
+ /**
146
+ * The issue of a promotion whose action input carries runtime call metadata, which is refused: a
147
+ * promotion's provenance comes only from where its route takes it, never from the action input a
148
+ * model or client supplies. Empty when the input carries none.
149
+ */
150
+ export declare function nestedEnvelopeIssues(input: Readonly<Record<string, unknown>> | undefined): ReadonlyArray<ValidationIssue>;
144
151
  export {};
@@ -47,3 +47,18 @@ export function consumeChatEnvelope(args, caller) {
47
47
  return { input, envelope: parsed };
48
48
  });
49
49
  }
50
+ /**
51
+ * The issue of a promotion whose action input carries runtime call metadata, which is refused: a
52
+ * promotion's provenance comes only from where its route takes it, never from the action input a
53
+ * model or client supplies. Empty when the input carries none.
54
+ */
55
+ export function nestedEnvelopeIssues(input) {
56
+ return input !== undefined && Object.hasOwn(input, "_segmentstream")
57
+ ? [
58
+ {
59
+ path: ["input", "_segmentstream"],
60
+ message: "A promotion's action input cannot carry runtime call metadata.",
61
+ },
62
+ ]
63
+ : [];
64
+ }
@@ -18,6 +18,8 @@ export declare function renderTelegram(markdown: string, attribution: string, se
18
18
  * closes, would take the attribution in.
19
19
  */
20
20
  export declare function telegramRichMarkdown(markdown: string, attribution: string, separator?: string, links?: ReadonlyMap<string, string>): string | undefined;
21
+ /** The bot's username from Telegram's `getMe`; undefined, and nothing cached, when it fails. */
22
+ export declare function botUsername(transport: ConnectionTransport["Service"], connection: string): Effect.Effect<string | undefined>;
21
23
  /** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
22
24
  export declare function telegramKeyboard(rows: ChatButtonRows, links?: ReadonlyMap<string, string>): Readonly<Record<string, unknown>>;
23
25
  /** Where a text goes: the chat, its forum topic and the message it answers. */
@@ -128,7 +128,7 @@ export function telegramRichMarkdown(markdown, attribution, separator = "\n\n",
128
128
  const botUsernames = new Map();
129
129
  const BOT_USERNAME_TTL_MS = 60 * 60_000;
130
130
  /** The bot's username from Telegram's `getMe`; undefined, and nothing cached, when it fails. */
131
- function botUsername(transport, connection) {
131
+ export function botUsername(transport, connection) {
132
132
  const known = botUsernames.get(connection);
133
133
  if (known !== undefined && known.until > Date.now()) {
134
134
  return Effect.succeed(known.username);
@@ -185,6 +185,12 @@ export interface OntologyServiceConfig extends OntologyEnvironment {
185
185
  * set, else SegmentStream's proxy with the request's Vercel OIDC token.
186
186
  */
187
187
  readonly connections?: ConnectionTransportFactory;
188
+ /**
189
+ * Sends the requests of the caller's own connection routes (`/api/ontology/me/connections`), and
190
+ * a cron's read of the users eligible for an owned workflow's runs, to backend-next; tests
191
+ * replace it. Defaults to `fetch`.
192
+ */
193
+ readonly ownedConnectionsFetch?: typeof fetch;
188
194
  /**
189
195
  * Serve the MCP server at `/mcp`. On by default: its tools reach exactly what the HTTP routes
190
196
  * reach, with the same credentials.
@@ -1,6 +1,14 @@
1
+ import type { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
1
2
  import { type ConnectionTransport } from "../connection.js";
2
3
  /** The header Vercel sets on each function request: the deployment's OIDC token. */
3
4
  export declare const OIDC_TOKEN_HEADER = "x-vercel-oidc-token";
5
+ /**
6
+ * The owner of an owned connection's call: the acting user's id (docs/private-connections-spec.md).
7
+ * Internal: the package does not export it, so no API names an owner.
8
+ */
9
+ export declare const CONNECTION_OWNER_HEADER = "x-segmentstream-connection-owner";
10
+ /** An owned connection's call kind, `interactive` or `background`. Internal, as the owner. */
11
+ export declare const CONNECTION_CALL_HEADER = "x-segmentstream-connection-call";
4
12
  /** Where `segmentstream exec` passes the local runtime context: a pipe's file descriptor. */
5
13
  export declare const RUNTIME_CONTEXT_FD = "SEGMENTSTREAM_RUNTIME_CONTEXT_FD";
6
14
  /** Who a connection call is made for. SegmentStream logs these; it never trusts them. */
@@ -11,11 +19,18 @@ export interface ConnectionAudit {
11
19
  readonly requestId: string;
12
20
  }
13
21
  /** Builds the transport of one action request. */
14
- export type ConnectionTransportFactory = (input: {
22
+ export type ConnectionTransportFactory = ((input: {
15
23
  /** The deployment's OIDC token, from the request or the environment. */
16
24
  readonly identityToken: string | undefined;
17
25
  readonly audit: ConnectionAudit;
18
- }) => ConnectionTransport["Service"];
26
+ }) => ConnectionTransport["Service"]) & {
27
+ /**
28
+ * The platform's retirement of a departed user's owned connection credentials, with the
29
+ * request's deployment identity; absent where there is no platform to call, as in a preview, a
30
+ * local run or a test.
31
+ */
32
+ readonly retirement?: (identityToken: string | undefined) => OwnedConnectionRetirement["Service"];
33
+ };
19
34
  /** A connection the local grant covers, as the CLI describes it. */
20
35
  export interface LocalConnection {
21
36
  readonly key: string;
@@ -1,9 +1,21 @@
1
1
  import { closeSync, readFileSync } from "node:fs";
2
2
  import { Effect, Stream } from "effect";
3
- import { CONNECTION_KEY, ConnectionError, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "../connection.js";
3
+ import { callOwner, CONNECTION_KEY, ConnectionError, MAXIMUM_CONNECTION_BODY_BYTES, MAXIMUM_CONNECTION_RESPONSE_BYTES, } from "../connection.js";
4
4
  import { CONNECTION_STREAM_MEDIA_TYPE, openConnectionStream } from "./connection-stream.js";
5
5
  /** The header Vercel sets on each function request: the deployment's OIDC token. */
6
6
  export const OIDC_TOKEN_HEADER = "x-vercel-oidc-token";
7
+ /**
8
+ * The owner of an owned connection's call: the acting user's id (docs/private-connections-spec.md).
9
+ * Internal: the package does not export it, so no API names an owner.
10
+ */
11
+ export const CONNECTION_OWNER_HEADER = "x-segmentstream-connection-owner";
12
+ /** An owned connection's call kind, `interactive` or `background`. Internal, as the owner. */
13
+ export const CONNECTION_CALL_HEADER = "x-segmentstream-connection-call";
14
+ function ownerHeaders(owner) {
15
+ return owner === undefined
16
+ ? {}
17
+ : { [CONNECTION_OWNER_HEADER]: owner.id, [CONNECTION_CALL_HEADER]: owner.call };
18
+ }
7
19
  /** Where `segmentstream exec` passes the local runtime context: a pipe's file descriptor. */
8
20
  export const RUNTIME_CONTEXT_FD = "SEGMENTSTREAM_RUNTIME_CONTEXT_FD";
9
21
  const MAXIMUM_CONTEXT_BYTES = 4 * 1_048_576;
@@ -24,6 +36,8 @@ function failure(connection, reason, message, requestId, cause) {
24
36
  }
25
37
  const REASONS = {
26
38
  connection_authorization_required: "authorization_required",
39
+ connection_owner_required: "owner_required",
40
+ connection_background_consent_required: "background_consent_required",
27
41
  connections_not_deployed: "not_deployed",
28
42
  connections_redeployment_required: "not_deployed",
29
43
  connection_not_found: "not_deployed",
@@ -50,6 +64,9 @@ const MESSAGES = {
50
64
  timeout: "The connection call exceeded its deadline.",
51
65
  invalid_request: "The connection proxy refused the request.",
52
66
  invalid_response: "The connection proxy answered with an invalid response.",
67
+ owner_required: "The connection is owned by each user; only code running as a signed-in user, or in a " +
68
+ "workflow run of one that lists it, may call it.",
69
+ background_consent_required: "The connection's owner has not allowed it to be used while nobody is asking for the work.",
53
70
  };
54
71
  function isRecord(value) {
55
72
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -206,6 +223,9 @@ export function deployedConnections(environment, fetchImpl = fetch) {
206
223
  "x-segmentstream-ontology-action": audit.action,
207
224
  "x-segmentstream-ontology-principal": audit.principalId,
208
225
  "x-segmentstream-request-id": audit.requestId,
226
+ // Only an owned connection's call names whose credential it uses: the runtime sets it
227
+ // beside the call, never a field a builder's call could carry.
228
+ ...ownerHeaders(callOwner(call)),
209
229
  },
210
230
  call: { ...call, api: call.api },
211
231
  });
@@ -280,13 +280,39 @@ function connectionFailure(error, requestId) {
280
280
  const connection = error.connection;
281
281
  switch (error.reason) {
282
282
  case "authorization_required":
283
+ // An owned connection is connected by the acting user in the app, at `connect`.
283
284
  return {
284
285
  status: 409,
285
286
  body: {
286
287
  error: "connection_authorization_required",
287
- detail: `Configure or authorize the ${connection} connection in SegmentStream.`,
288
+ detail: error.connect === undefined
289
+ ? `Configure or authorize the ${connection} connection in SegmentStream.`
290
+ : `The acting user has not connected the ${connection} connection.`,
288
291
  requestId,
289
292
  connection,
293
+ ...(error.connect === undefined ? {} : { connect: error.connect }),
294
+ },
295
+ };
296
+ case "owner_required":
297
+ return {
298
+ status: 409,
299
+ body: {
300
+ error: "connection_owner_required",
301
+ detail: `Each user connects the ${connection} connection; only a signed-in user's code may call it.`,
302
+ requestId,
303
+ connection,
304
+ retryable: false,
305
+ },
306
+ };
307
+ case "background_consent_required":
308
+ return {
309
+ status: 409,
310
+ body: {
311
+ error: "connection_background_consent_required",
312
+ detail: `The owner has not allowed the ${connection} connection to be used in the background.`,
313
+ requestId,
314
+ connection,
315
+ retryable: false,
290
316
  },
291
317
  };
292
318
  case "not_deployed":
@@ -6,6 +6,7 @@ import { schemaIssues } from "../runtime/validation.js";
6
6
  import { uploadFields } from "../storage/attachments.js";
7
7
  import { OpenUploads } from "../storage/sessions.js";
8
8
  import { CurrentPrincipal } from "./authentication.js";
9
+ import { nestedEnvelopeIssues } from "./chat/envelope.js";
9
10
  import { InvalidRequestBody, RequestId } from "./errors.js";
10
11
  const Id = Schema.String.check(Schema.isUUID());
11
12
  const DateTime = Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/));
@@ -211,6 +212,11 @@ export function memberFileOperations(backend, plan, operations) {
211
212
  }
212
213
  if (kind === "attachments-promote") {
213
214
  const input = yield* decode(Promotion, args);
215
+ // Runtime call metadata comes only from where the request's route takes it.
216
+ const nested = nestedEnvelopeIssues(input.input);
217
+ if (nested.length > 0) {
218
+ return yield* new InvalidRequestBody({ reason: "invalid_request", issues: nested });
219
+ }
214
220
  const promoted = yield* attachments.promoteForMember(input.id, {
215
221
  entity: input.entity,
216
222
  action: input.action,
@@ -1,6 +1,7 @@
1
1
  import type { ActionRuntime } from "../runtime-source.js";
2
2
  import { Effect, Schema } from "effect";
3
3
  import type { HttpServerRequest } from "effect/unstable/http";
4
+ import { type RunConnectionOwner } from "../connection.js";
4
5
  import { ActionRejected, PermissionDenied } from "../errors.js";
5
6
  import { type ScopedPermission } from "../permissions.js";
6
7
  import { type Query, type QueryResult } from "../query.js";
@@ -50,6 +51,13 @@ export interface ActionCall {
50
51
  };
51
52
  /** The deployment's OIDC token, which authorizes the action's connection calls. */
52
53
  readonly identityToken: string | undefined;
54
+ /**
55
+ * The owner of the workflow run whose step runs the action, as the platform recorded it when the
56
+ * run started, and the owned keys the run's workflow lists. Only the workflow service sets it.
57
+ * It is bound to this action's transport alone: a hook or another action the action leads to
58
+ * gets none.
59
+ */
60
+ readonly runOwner?: RunConnectionOwner | undefined;
53
61
  }
54
62
  /** What an action answers: `{ result, validation, edits }`. */
55
63
  export interface ActionAnswer {
@@ -2,10 +2,12 @@ import { Effect, Option, Schema } from "effect";
2
2
  import { editsFromWire, generatedResultFromWire, recordFromWire } from "../authoring-records.js";
3
3
  import { nameToWire } from "../authoring-names.js";
4
4
  import { principalFromWire } from "../authoring.js";
5
+ import { withRunOwner } from "../connection.js";
5
6
  import { ActionRejected, PermissionDenied } from "../errors.js";
6
7
  import { toCamelCase } from "../names.js";
7
8
  import { missingPermission, permissionOf, READ_VERB, } from "../permissions.js";
8
9
  import { includedRelationships } from "../query.js";
10
+ import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
9
11
  import { InvalidQuery } from "../runtime/errors.js";
10
12
  import { CurrentPrincipal } from "./authentication.js";
11
13
  import { currentCaller, CurrentCaller } from "./caller-context.js";
@@ -300,10 +302,10 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
300
302
  ...(call.confirm === undefined ? {} : { confirm: call.confirm }),
301
303
  },
302
304
  requestId,
303
- connections: connections({
305
+ connections: withRunOwner(connections({
304
306
  identityToken: call.identityToken,
305
307
  audit: { action: `${planned.name}.${name}`, principalId: principal.id, requestId },
306
- }),
308
+ }), call.runOwner),
307
309
  ...(hook || backend.replicationEnabled
308
310
  ? {
309
311
  afterCommit: (committed) => Effect.gen(function* () {
@@ -343,9 +345,14 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
343
345
  }
344
346
  : {}),
345
347
  });
346
- const outcome = yield* delivery === undefined
348
+ // A user the action makes leave has their owned connection credentials retired.
349
+ const retirement = connections.retirement?.(call.identityToken);
350
+ const retiring = retirement === undefined
347
351
  ? run
348
- : run.pipe(Effect.provideService(ChatDelivery, delivery));
352
+ : run.pipe(Effect.provideService(OwnedConnectionRetirement, retirement));
353
+ const outcome = yield* delivery === undefined
354
+ ? retiring
355
+ : retiring.pipe(Effect.provideService(ChatDelivery, delivery));
349
356
  // Validating a message checks its destination, sender and exact text, sending nothing.
350
357
  if (call.validateOnly &&
351
358
  outcome.validation.ok &&
@@ -0,0 +1,80 @@
1
+ import { Layer } from "effect";
2
+ import { HttpRouter } from "effect/unstable/http";
3
+ import { type SessionExchange, type TokenVerifier } from "./authentication.js";
4
+ import { RequestId } from "./errors.js";
5
+ import { OwnedConnectionRetirement } from "../runtime/owner-departures.js";
6
+ import { OntologyBackend } from "./runtime-contract.js";
7
+ /**
8
+ * The routes a workspace user manages their own credentials of owned connections with
9
+ * (docs/private-connections-spec.md, "In the ontology SDK"), under the caller's own `me`, which no
10
+ * entity, toolset or metric may be named. Every route but the discard acts as the signed-in member
11
+ * and on that member's own credential: the owner is always the request's principal, and no route
12
+ * takes a user id. The discard names no owner at all.
13
+ */
14
+ export declare const OWNED_CONNECTIONS_PATH = "/api/ontology/me/connections";
15
+ interface OwnedConnectionsOptions {
16
+ readonly environment: {
17
+ readonly segmentstreamUrl: string;
18
+ readonly workspaceId: string;
19
+ readonly organizationId: string;
20
+ };
21
+ /**
22
+ * The keys of the deployed ontology's owned handles. The discard asks backend-next only for one
23
+ * of these; any other key is answered as a discarded code, without a request.
24
+ */
25
+ readonly ownedKeys: ReadonlySet<string>;
26
+ readonly verifyToken: TokenVerifier;
27
+ readonly exchangeSession?: SessionExchange | undefined;
28
+ readonly fetch?: typeof fetch | undefined;
29
+ }
30
+ /**
31
+ * The platform's retirement of a departed user's owned connection credentials, called with the
32
+ * request's deployment identity (`DELETE …/owners/:ownerId`) after the action that made them leave
33
+ * committed. A failure, or a request with no deployment identity, is logged and changes nothing
34
+ * else; the next deployment retires what was missed.
35
+ */
36
+ export declare function ownedConnectionRetirement(options: {
37
+ readonly environment: OwnedConnectionsOptions["environment"];
38
+ readonly fetch?: typeof fetch | undefined;
39
+ }, identityToken: string | undefined): OwnedConnectionRetirement["Service"];
40
+ /**
41
+ * Whether a departed user's owned connection credentials are retired from this service: only in
42
+ * the platform's production deployment (it names its deployment, `workloadTarget`) of an ontology
43
+ * that declares an owned handle. Anywhere else a deactivation, a deletion or an identity
44
+ * revocation calls nothing and reads nothing for it.
45
+ */
46
+ export declare function retiresOwnedConnections(input: {
47
+ readonly ownedKeys: ReadonlySet<string>;
48
+ readonly preview: boolean;
49
+ readonly workloadTarget: {
50
+ readonly deploymentId: string;
51
+ } | undefined;
52
+ }): boolean;
53
+ /** One page of the owners eligible for a scheduled run, as backend-next answers it. */
54
+ export interface EligibleOwnersPage {
55
+ readonly owners: ReadonlyArray<string>;
56
+ /** The owner id to continue after; `null` on the last page. */
57
+ readonly next: string | null;
58
+ /** Users who hold a credential on some listed key but are not eligible, on every page. */
59
+ readonly ineligible: number;
60
+ }
61
+ /** Why backend-next did not answer a page of eligible owners. */
62
+ export declare class EligibleOwnersUnavailable extends Error {
63
+ constructor(message: string, options?: {
64
+ readonly cause?: unknown;
65
+ });
66
+ }
67
+ /**
68
+ * Reads the owners eligible for a scheduled run of a workflow listing these owned keys, a page of
69
+ * 500 at a time (`listEligibleConnectionOwners`), with the deployment's OIDC token: users with an
70
+ * active credential and background consent on every key.
71
+ */
72
+ export type EligibleOwners = (input: {
73
+ readonly identityToken: string;
74
+ readonly keys: ReadonlyArray<string>;
75
+ readonly after: string | null;
76
+ readonly requestId: string;
77
+ }) => Promise<EligibleOwnersPage>;
78
+ export declare function eligibleOwners(environment: OwnedConnectionsOptions["environment"], fetchImpl?: typeof fetch): EligibleOwners;
79
+ export declare function ownedConnectionsLayer(options: OwnedConnectionsOptions): Layer.Layer<never, never, OntologyBackend | HttpRouter.HttpRouter | HttpRouter.Request<"Requires", RequestId>>;
80
+ export {};