@segmentstream/ontology 0.102.0 → 0.105.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.
@@ -2,9 +2,12 @@ import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
3
  import { CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, USER_TABLE, } from "../migrate/storage.js";
4
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";
5
+ import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
6
6
  import { completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, } from "./agent-counters.js";
7
7
  import { channelUsersAvailable } from "./member-tables.js";
8
+ import { runNewUserHook } from "./new-user-hook.js";
9
+ import { CHANNEL_IDENTITIES_FROM, LIVE_CHANNEL_IDENTITY } from "./user-identity-sql.js";
10
+ import { WEB_PROVIDER } from "../service/runtime-identity.js";
8
11
  import { sqlOAuthStore } from "./oauth.js";
9
12
  import { isMemberBlocked } from "./principals.js";
10
13
  import { isRecordId } from "./records.js";
@@ -14,7 +17,9 @@ const GRANTS = `"${OAUTH_GRANTS_TABLE}"`;
14
17
  * member and resource for the first-party client `agent-web`, and a new access token on each
15
18
  * request. Blocking or deactivating the member revokes the grant with every other one of theirs.
16
19
  */
17
- export function sqlAgentWebStore(ontology, sql) {
20
+ /** How many new website visitors one network address may start an hour. */
21
+ export const VISITORS_PER_CLIENT_PER_HOUR = 10;
22
+ export function sqlAgentWebStore(ontology, sql, admission) {
18
23
  const oauth = sqlOAuthStore(ontology, sql);
19
24
  return {
20
25
  issue: ({ userId, resource, expiresAt }) => sql
@@ -64,7 +69,8 @@ export function sqlAgentWebStore(ontology, sql) {
64
69
  if (!isRecordId(userId) || !(yield* channelUsersAvailable(sql))) {
65
70
  return undefined;
66
71
  }
67
- const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
72
+ const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up",
73
+ "c"."on_new_user_completed_at" IS NULL AND "c"."blocked_at" IS NULL AS "pending"
68
74
  FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [userId]);
69
75
  if (lifecycle?.signed_up !== true) {
70
76
  return undefined;
@@ -94,7 +100,80 @@ export function sqlAgentWebStore(ontology, sql) {
94
100
  return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
95
101
  }
96
102
  }
103
+ // Onboarding that failed at sign-up runs again before an admitted turn, as a messenger's
104
+ // does; a refused turn never runs it.
105
+ if (lifecycle.pending && ontology.signIn.onSignUp !== undefined) {
106
+ const principal = yield* oauth.memberPrincipal(userId);
107
+ if (principal !== undefined) {
108
+ yield* runNewUserHook(ontology, sql, principal);
109
+ }
110
+ }
97
111
  return undefined;
98
112
  }).pipe(Effect.orDie),
113
+ visitor: ({ visitorId, resource, client }) => Effect.gen(function* () {
114
+ const crowded = yield* countAgentAttempt(sql, {
115
+ scope: "newUsersPerHour",
116
+ subject: `web:${client}`,
117
+ window: "hour",
118
+ limit: VISITORS_PER_CLIENT_PER_HOUR,
119
+ });
120
+ if (crowded !== undefined) {
121
+ return { status: "limited", retryAfterSeconds: crowded.retryAfterSeconds };
122
+ }
123
+ // Admission commits the user, their identity and onboarding before the grant, as a channel
124
+ // session's does; never inside the issuer transaction.
125
+ const admitted = yield* admission.signUp(visitorId);
126
+ if (admitted.status === "limited") {
127
+ return { status: "limited", retryAfterSeconds: admitted.retryAfterSeconds };
128
+ }
129
+ if (admitted.status !== "created" && admitted.status !== "existing") {
130
+ return { status: "refused" };
131
+ }
132
+ const userId = admitted.member.principal.id;
133
+ return yield* sql.withTransaction(Effect.gen(function* () {
134
+ // Same lock as the member's lifecycle operations, so a blocked visitor gets nothing.
135
+ const [member] = yield* sql.unsafe(`SELECT "kind"::text AS "kind", "active" FROM "${USER_TABLE}"
136
+ WHERE "id" = $1::uuid FOR SHARE`, [userId]);
137
+ if (member?.kind !== "member" ||
138
+ !member.active ||
139
+ (yield* isMemberBlocked(sql, userId))) {
140
+ return { status: "refused" };
141
+ }
142
+ // The grant lives as long as the visitor's `web` account: revoking the account revokes
143
+ // it, as it revokes a channel's sessions, and a revoked account gets none.
144
+ const [identity] = yield* sql.unsafe(`SELECT "i"."id"::text AS "id", "i"."user_id"::text AS "user_id"
145
+ FROM ${CHANNEL_IDENTITIES_FROM}
146
+ WHERE "i"."provider" = $1 AND "i"."subject" = $2 AND ${LIVE_CHANNEL_IDENTITY}
147
+ FOR UPDATE OF "i"`, [WEB_PROVIDER, visitorId]);
148
+ if (identity === undefined || identity.user_id !== userId) {
149
+ return { status: "refused" };
150
+ }
151
+ yield* sql.unsafe(`INSERT INTO "${OAUTH_CLIENTS_TABLE}" ("id", "name", "redirect_uris", "auth_method")
152
+ VALUES ($1, $1, '[]'::jsonb, 'none') ON CONFLICT ("id") DO NOTHING`, [AGENT_WEB_CLIENT_ID]);
153
+ const grantId = randomUUID();
154
+ const token = newSecret(ACCESS_TOKEN_PREFIX);
155
+ const refreshToken = newSecret(REFRESH_TOKEN_PREFIX);
156
+ const now = Date.now();
157
+ const expiresAt = new Date(now + ACCESS_TOKEN_TTL_MS);
158
+ yield* oauth.saveGrant({
159
+ id: grantId,
160
+ clientId: AGENT_WEB_CLIENT_ID,
161
+ userId,
162
+ scope: FULL_SCOPE,
163
+ resource,
164
+ });
165
+ yield* sql.unsafe(`UPDATE "${OAUTH_GRANTS_TABLE}" SET "identity_id" = $2::uuid WHERE "id" = $1::uuid`, [grantId, identity.id]);
166
+ yield* oauth.saveTokens([
167
+ { hash: secretHash(token), grantId, kind: "access", expiresAt },
168
+ {
169
+ hash: secretHash(refreshToken),
170
+ grantId,
171
+ kind: "refresh",
172
+ expiresAt: new Date(now + REFRESH_TOKEN_TTL_MS),
173
+ },
174
+ ]);
175
+ return { status: "signed_up", userId, token, refreshToken, expiresAt };
176
+ }));
177
+ }).pipe(Effect.orDie),
99
178
  };
100
179
  }
@@ -13,6 +13,7 @@ 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
15
  import { sqlAgentWebStore } from "./agent-web.js";
16
+ import { WEB_PROVIDER } from "../service/runtime-identity.js";
16
17
  import { isRecordId } from "./records.js";
17
18
  import { makeOntologyRuntime } from "./sql-runtime.js";
18
19
  import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
@@ -489,7 +490,9 @@ export function sqlAgentStore(ontology, sql) {
489
490
  return { id: String(review.id), status: "pending", created: true };
490
491
  }))
491
492
  .pipe(Effect.orDie),
492
- web: sqlAgentWebStore(ontology, sql),
493
+ web: sqlAgentWebStore(ontology, sql, {
494
+ signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
495
+ }),
493
496
  };
494
497
  return store;
495
498
  }
package/dist/server.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type PlatformWorkflows } from "./workflow-runtime.js";
2
+ import type { WorkflowStructures } from "./workflow-structure.js";
2
3
  /**
3
4
  * Prepares the process for serving the ontology's runs; the starter's `server/plugin.ts` calls it
4
5
  * at startup. Until the flow handler loads, which sets the Workflow SDK's base path itself from the
@@ -21,3 +22,9 @@ export declare function installWorkflowRuntime(): void;
21
22
  * since the service could not arm the recovery run that guarantees its starts.
22
23
  */
23
24
  export declare function registerPlatformWorkflows(workflows: PlatformWorkflows): void;
25
+ /**
26
+ * Registers what the build read of each workflow's code, by workflow id: the plugin
27
+ * `ontologyWorkflows()` generates calls it at startup, and the service serves each declared
28
+ * workflow's structure beside its runs. Without it, the service answers that it has none.
29
+ */
30
+ export declare function registerWorkflowStructures(structures: WorkflowStructures): void;
package/dist/server.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { setWorkflowBasePath } from "@workflow/utils";
7
7
  import { deploymentFromEnv, requireDeploymentCapability } from "./deployment.js";
8
- import { setPlatformWorkflows, setWorkflowSdk, } from "./workflow-runtime.js";
8
+ import { setPlatformWorkflows, setWorkflowSdk, setWorkflowStructures, } from "./workflow-runtime.js";
9
9
  import { ONTOLOGY_QUEUE_NAMESPACE, WORKFLOW_BASE_PATH } from "./workflow-topics.js";
10
10
  import { installWorkflowArgumentCodecs } from "./service/workflow-argument-serialization.js";
11
11
  import { installWorkflowLogging } from "./service/workflow-logging.js";
@@ -105,3 +105,11 @@ export function installWorkflowRuntime() {
105
105
  export function registerPlatformWorkflows(workflows) {
106
106
  setPlatformWorkflows(workflows);
107
107
  }
108
+ /**
109
+ * Registers what the build read of each workflow's code, by workflow id: the plugin
110
+ * `ontologyWorkflows()` generates calls it at startup, and the service serves each declared
111
+ * workflow's structure beside its runs. Without it, the service answers that it has none.
112
+ */
113
+ export function registerWorkflowStructures(structures) {
114
+ setWorkflowStructures(structures);
115
+ }
@@ -10,6 +10,8 @@ export declare const AGENT_PATH = "/api/ontology/agent";
10
10
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
11
11
  export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
12
12
  export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
13
+ /** Where a browser on a declared website signs its visitor up on `web`. */
14
+ export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
13
15
  /**
14
16
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
15
17
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -17,6 +19,8 @@ export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/token
17
19
  export declare const PAIRING_LIMIT: RateLimit;
18
20
  export interface AgentServerOptions {
19
21
  readonly verifyToken: TokenVerifier;
22
+ /** The websites whose visitors may sign up on `web`, by origin; none while `web` is closed. */
23
+ readonly visitorOrigins?: ReadonlyArray<string>;
20
24
  /** The deployment's runtime tokens; `undefined` while runtime authentication is disabled. */
21
25
  readonly verifyRuntime: RuntimeTokenVerifier | undefined;
22
26
  readonly exchangeSession: SessionExchange | undefined;
@@ -13,7 +13,7 @@ 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
+ import { AGENT_TOKEN_LIMIT, introspectAgentToken, issueAgentToken, signUpVisitor, visitorPreflight, } from "./web-tokens.js";
17
17
  /** The agent's endpoints, under the ontology service's path. */
18
18
  export const AGENT_PATH = `${BASE_PATH}/agent`;
19
19
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
@@ -23,6 +23,8 @@ const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
23
23
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
24
24
  export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
25
25
  export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
26
+ /** Where a browser on a declared website signs its visitor up on `web`. */
27
+ export const AGENT_VISITORS_PATH = `${AGENT_PATH}/visitors`;
26
28
  /**
27
29
  * Pairings one client address may start per minute; each one is a row in the database. The agent's
28
30
  * functions share a few egress addresses, so the limit leaves room for a busy channel.
@@ -435,6 +437,11 @@ export function agentLayer(options) {
435
437
  if (store.web !== undefined && backend.oauth !== undefined) {
436
438
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
437
439
  yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth)));
440
+ const origins = options.visitorOrigins ?? [];
441
+ if (origins.length > 0) {
442
+ yield* router.add("OPTIONS", AGENT_VISITORS_PATH, visitorPreflight(origins));
443
+ yield* router.add("POST", AGENT_VISITORS_PATH, signUpVisitor(store.web, origins));
444
+ }
438
445
  }
439
446
  }));
440
447
  }
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
3
  import type { Principal } from "../../runtime.js";
4
4
  import { RequestId } from "../errors.js";
5
- import type { RateLimit, RateLimiter } from "../rate-limit.js";
5
+ import { type RateLimit, type RateLimiter } from "../rate-limit.js";
6
6
  import type { AgentStore, AgentWebStore, OAuthStore } from "../runtime-contract.js";
7
7
  /**
8
8
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
@@ -31,3 +31,17 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
31
31
  * and the answer names the limit it exceeds as `limited`.
32
32
  */
33
33
  export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
34
+ /**
35
+ * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of `signUp.origins` sign its visitor
36
+ * up; any other origin gets no permission.
37
+ */
38
+ export declare function visitorPreflight(origins: ReadonlyArray<string>): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, never>;
39
+ /**
40
+ * `POST /api/ontology/agent/visitors`, for a browser on one of the websites `signUp.origins` names:
41
+ * signs a new visitor up on `web` with the roles `signUp` gives it, and answers
42
+ * `{ token, expires_at, refresh_token, chat }`. The token is an agent token like a member's; the
43
+ * refresh token renews it at the ontology's OAuth token endpoint, as client `agent-web`. Any other
44
+ * origin is refused. A browser's Origin proves no sender, so the limits on new visitors per network
45
+ * address and per workspace, and on each one's turns, are what bound it.
46
+ */
47
+ export declare function signUpVisitor(web: AgentWebStore, origins: ReadonlyArray<string>): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
@@ -1,9 +1,11 @@
1
+ import { createHash, randomUUID } from "node:crypto";
1
2
  import { Effect, Result, Schema } from "effect";
2
3
  import { HttpServerResponse } from "effect/unstable/http";
3
4
  import { schemaIssues } from "../../runtime/validation.js";
4
5
  import { BASE_PATH } from "../api.js";
5
6
  import { RequestId, errorBodyForWire, forbidden, rateLimited, toServerResponse, } from "../errors.js";
6
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, callerOfAccessToken, publicOrigin, } from "../oauth/protocol.js";
8
+ import { clientAddress } from "../rate-limit.js";
7
9
  /**
8
10
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
9
11
  * server (`sso_…`): the token of the member's grant to the first-party client `agent-web`, for the
@@ -129,3 +131,83 @@ export function introspectAgentToken(store, web, oauth) {
129
131
  });
130
132
  });
131
133
  }
134
+ /** The headers that let a website on `origin` read an answer to its visitor's browser. */
135
+ function websiteHeaders(origin) {
136
+ return { "access-control-allow-origin": origin, vary: "Origin" };
137
+ }
138
+ /** The declared website a browser's request comes from, when it comes from one. */
139
+ function websiteOf(request, origins) {
140
+ const origin = request.headers.origin;
141
+ return origin !== undefined && origins.includes(origin) ? origin : undefined;
142
+ }
143
+ /**
144
+ * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of `signUp.origins` sign its visitor
145
+ * up; any other origin gets no permission.
146
+ */
147
+ export function visitorPreflight(origins) {
148
+ return (request) => Effect.sync(() => {
149
+ const origin = websiteOf(request, origins);
150
+ return origin === undefined
151
+ ? HttpServerResponse.empty({ status: 403, headers: { vary: "Origin" } })
152
+ : HttpServerResponse.empty({
153
+ status: 204,
154
+ headers: {
155
+ ...websiteHeaders(origin),
156
+ "access-control-allow-methods": "POST",
157
+ "access-control-allow-headers": "content-type",
158
+ "access-control-max-age": "600",
159
+ },
160
+ });
161
+ });
162
+ }
163
+ /**
164
+ * `POST /api/ontology/agent/visitors`, for a browser on one of the websites `signUp.origins` names:
165
+ * signs a new visitor up on `web` with the roles `signUp` gives it, and answers
166
+ * `{ token, expires_at, refresh_token, chat }`. The token is an agent token like a member's; the
167
+ * refresh token renews it at the ontology's OAuth token endpoint, as client `agent-web`. Any other
168
+ * origin is refused. A browser's Origin proves no sender, so the limits on new visitors per network
169
+ * address and per workspace, and on each one's turns, are what bound it.
170
+ */
171
+ export function signUpVisitor(web, origins) {
172
+ return (request) => Effect.gen(function* () {
173
+ const requestId = yield* RequestId;
174
+ const origin = websiteOf(request, origins);
175
+ if (origin === undefined) {
176
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({
177
+ error: "origin_not_allowed",
178
+ detail: "This origin is not one of signUp.origins.",
179
+ requestId,
180
+ }), { status: 403, headers: { ...NO_STORE, vary: "Origin" } });
181
+ }
182
+ const headers = { ...NO_STORE, ...websiteHeaders(origin) };
183
+ const signedUp = yield* web.visitor({
184
+ visitorId: randomUUID(),
185
+ resource: agentResource(publicOrigin(request)),
186
+ client: createHash("sha256").update(clientAddress(request)).digest("hex"),
187
+ });
188
+ switch (signedUp.status) {
189
+ case "signed_up":
190
+ return HttpServerResponse.jsonUnsafe({
191
+ token: signedUp.token,
192
+ expires_at: signedUp.expiresAt.toISOString(),
193
+ refresh_token: signedUp.refreshToken,
194
+ chat: personalChat(signedUp.userId),
195
+ }, { status: 200, headers });
196
+ case "limited":
197
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({
198
+ error: "rate_limited",
199
+ detail: "Too many new visitors; try again later.",
200
+ requestId,
201
+ }), {
202
+ status: 429,
203
+ headers: { ...headers, "retry-after": String(signedUp.retryAfterSeconds) },
204
+ });
205
+ case "refused":
206
+ return HttpServerResponse.jsonUnsafe(errorBodyForWire({
207
+ error: "forbidden",
208
+ detail: "The visitor could not be signed up.",
209
+ requestId,
210
+ }), { status: 403, headers });
211
+ }
212
+ });
213
+ }
@@ -257,10 +257,34 @@ export interface AgentWebStore {
257
257
  /**
258
258
  * Counts one turn a member starts on the web against the agent's limits when `signUp` created
259
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.
260
+ * members are never counted. Their `onSignUp`, if it is still pending, runs again first. The
261
+ * limit the turn exceeds, or `undefined` when it may run.
261
262
  */
262
263
  readonly countTurn: (userId: string) => Effect.Effect<WebTurnLimit | undefined>;
264
+ /**
265
+ * Signs up a new visitor of a website on `web`: the user `signUp` creates for them, and the access
266
+ * and refresh tokens of their grant to the agent at `resource`. `client` keys how many visitors one
267
+ * network address may start an hour; the workspace's own cap on new users applies too.
268
+ */
269
+ readonly visitor: (input: {
270
+ readonly visitorId: string;
271
+ readonly resource: string;
272
+ readonly client: string;
273
+ }) => Effect.Effect<VisitorSignUp>;
263
274
  }
275
+ /** A website visitor's sign-up on `web`, as {@link AgentWebStore.visitor} answers it. */
276
+ export type VisitorSignUp = {
277
+ readonly status: "signed_up";
278
+ readonly userId: string;
279
+ readonly token: string;
280
+ readonly refreshToken: string;
281
+ readonly expiresAt: Date;
282
+ } | {
283
+ readonly status: "limited";
284
+ readonly retryAfterSeconds: number;
285
+ } | {
286
+ readonly status: "refused";
287
+ };
264
288
  /** The limit a member's turn on the web exceeds, and when the next one may run. */
265
289
  export interface WebTurnLimit {
266
290
  readonly scope: AgentLimitScope;
@@ -425,6 +425,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
425
425
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
426
426
  readonly signUp: Schema.optionalKey<Schema.Struct<{
427
427
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
428
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
428
429
  }>>;
429
430
  readonly onSignUp: Schema.optionalKey<Schema.String>;
430
431
  }>, {
@@ -697,6 +698,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
697
698
  readonly codeLink: Schema.optionalKey<Schema.Boolean>;
698
699
  readonly signUp: Schema.optionalKey<Schema.Struct<{
699
700
  readonly channels: Schema.$Record<Schema.String, Schema.Unknown>;
701
+ readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
700
702
  }>>;
701
703
  readonly onSignUp: Schema.optionalKey<Schema.String>;
702
704
  }>, {
@@ -9,6 +9,7 @@ import { RuntimeDeployment } from "../runtime/deployment.js";
9
9
  import { nameToWire } from "../authoring-names.js";
10
10
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
11
  import { parsePageCatalog } from "../navigation-catalog.js";
12
+ import { signUpOriginsOf } from "../manifest.js";
12
13
  import { isAllowed } from "../permissions.js";
13
14
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
14
15
  import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
@@ -349,8 +350,15 @@ export function createOntologyService(ontology, config) {
349
350
  ErrorResponsesLive,
350
351
  storageMaintenanceAuthenticationLayer(config.storageMaintenanceKey),
351
352
  ]));
352
- const mcp = config.mcp === false
353
+ const visitorOrigins = signUpOriginsOf(ontology.manifest);
354
+ const oauth = preview
353
355
  ? Layer.empty
356
+ : oauthLayer({ verifyToken, refreshReuseGraceMs: config.oauthRefreshReuseGraceMs });
357
+ const mcp = config.mcp === false
358
+ ? // A website's visitors renew their agent tokens at the OAuth token endpoint.
359
+ visitorOrigins.length > 0
360
+ ? oauth
361
+ : Layer.empty
354
362
  : Layer.mergeAll(mcpLayer({
355
363
  built,
356
364
  hooks,
@@ -366,10 +374,15 @@ export function createOntologyService(ontology, config) {
366
374
  streamMaxDurationMs: config.mcpStreamMaxDurationMs,
367
375
  workspaceId: config.workspaceId,
368
376
  decide: config.decisions,
369
- }), preview
370
- ? Layer.empty
371
- : oauthLayer({ verifyToken, refreshReuseGraceMs: config.oauthRefreshReuseGraceMs }));
372
- const agent = preview ? Layer.empty : agentLayer({ verifyToken, verifyRuntime, exchangeSession });
377
+ }), oauth);
378
+ const agent = preview
379
+ ? Layer.empty
380
+ : agentLayer({
381
+ verifyToken,
382
+ verifyRuntime,
383
+ exchangeSession,
384
+ visitorOrigins,
385
+ });
373
386
  const agentTasks = preview
374
387
  ? Layer.empty
375
388
  : agentTasksLayer({
@@ -189,6 +189,8 @@ export declare const SWEEP_PATH = "/api/ontology/workflows/sweep";
189
189
  * `workflow:<workflow>:start`, or for the platform;
190
190
  * - `GET /api/ontology/workflows`, `…/:workflow/runs` and `…/runs/:runId` read the declarations
191
191
  * and the SDK's run records for callers holding `workflow:<workflow>:read` and the platform;
192
+ * - `GET /api/ontology/workflows/:workflow/structure`, for the same callers, serves what the build
193
+ * read of the workflow's code (`../workflow-structure.ts`), `null` when it has none;
192
194
  * - `GET /api/ontology/workflows/:workflow/starts` lists the starts its action triggers decided,
193
195
  * pending and started, for the same callers;
194
196
  * - `GET` and `POST /api/ontology/workflows/sweep`, verified with the cron secret, start the
@@ -25,7 +25,7 @@ import { validate } from "../runtime/validation.js";
25
25
  import { triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
26
26
  import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, } from "../start-recovery-contract.js";
27
27
  import { nextCronTime, } from "../workflow.js";
28
- import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, } from "../workflow-runtime.js";
28
+ import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
29
29
  import { callbackIdentityToken } from "./workflow-callback.js";
30
30
  import { expireAgentTask, startAgentTask, } from "./agent/task-start.js";
31
31
  import { CurrentPrincipal, WORKLOAD_TOKEN_TYPE, withPrincipal, workloadKind, } from "./authentication.js";
@@ -565,6 +565,8 @@ function expected(effect, tags) {
565
565
  * `workflow:<workflow>:start`, or for the platform;
566
566
  * - `GET /api/ontology/workflows`, `…/:workflow/runs` and `…/runs/:runId` read the declarations
567
567
  * and the SDK's run records for callers holding `workflow:<workflow>:read` and the platform;
568
+ * - `GET /api/ontology/workflows/:workflow/structure`, for the same callers, serves what the build
569
+ * read of the workflow's code (`../workflow-structure.ts`), `null` when it has none;
568
570
  * - `GET /api/ontology/workflows/:workflow/starts` lists the starts its action triggers decided,
569
571
  * pending and started, for the same callers;
570
572
  * - `GET` and `POST /api/ontology/workflows/sweep`, verified with the cron secret, start the
@@ -1486,6 +1488,17 @@ export function workflowsLayer(options) {
1486
1488
  nextCursor: page.value.hasMore ? page.value.cursor : null,
1487
1489
  });
1488
1490
  })));
1491
+ // What the build read of the workflow's code: its steps, waits, branches and loops.
1492
+ yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows/:workflow/structure`, authorized((caller) => Effect.gen(function* () {
1493
+ const params = yield* HttpRouter.params;
1494
+ const found = yield* readable(caller, params.workflow);
1495
+ if (!found.ok) {
1496
+ return found.refused;
1497
+ }
1498
+ const workflowId = compiledWorkflowId(found.workflow.declaration.run);
1499
+ const structure = workflowId === undefined ? undefined : workflowStructures()?.[workflowId];
1500
+ return json({ structure: structure ?? null });
1501
+ })));
1489
1502
  yield* router.add("GET", `${WORKFLOW_BASE_PATH}/workflows/:workflow/runs/:runId`, authorized((caller, request) => Effect.gen(function* () {
1490
1503
  const requestId = yield* RequestId;
1491
1504
  const params = yield* HttpRouter.params;
package/dist/sign-in.d.ts CHANGED
@@ -11,10 +11,11 @@ export declare const DEFAULT_SIGN_IN_POLICY: SignInPolicy;
11
11
  export declare const CHANNEL_PROVIDERS: readonly ["telegram"];
12
12
  export type ChannelProvider = (typeof CHANNEL_PROVIDERS)[number];
13
13
  /**
14
- * The channels a stranger may sign up through. `email` is sign-in by email code in the app; the
15
- * others are a first private message to the agent, or opening the Telegram Mini App.
14
+ * The channels a stranger may sign up through. `email` is sign-in by email code in the app; `web`
15
+ * is a visitor who writes to the agent from one of the websites `signUp.origins` names; the others
16
+ * are a first private message to the agent, or opening the Telegram Mini App.
16
17
  */
17
- export declare const SIGN_UP_CHANNELS: readonly ["email", "telegram", "whatsapp"];
18
+ export declare const SIGN_UP_CHANNELS: readonly ["email", "telegram", "whatsapp", "web"];
18
19
  export type SignUpChannel = (typeof SIGN_UP_CHANNELS)[number];
19
20
  /** The sign-up channels a person reaches through a chat, which need a matching `chat` adapter. */
20
21
  export declare const SIGN_UP_CHAT_CHANNELS: ReadonlyArray<SignUpChannel>;
@@ -30,11 +31,25 @@ export interface SignUpOptions<R = unknown> {
30
31
  readonly roles: ReadonlyArray<R>;
31
32
  /** Roles for a listed channel that differs from `roles`. */
32
33
  readonly byChannel?: Readonly<Partial<Record<SignUpChannel, ReadonlyArray<R>>>>;
34
+ /**
35
+ * The websites whose visitors may sign up on `web`, by origin, such as
36
+ * `https://www.example.com`: the agent's sign-up answers a browser on one of them. Required with
37
+ * `web`; `http` only for `localhost` and `127.0.0.1`.
38
+ */
39
+ readonly origins?: ReadonlyArray<string>;
33
40
  }
34
41
  /** Sign-up as the manifest carries it: the wire names of the roles each open channel grants. */
35
42
  export interface ResolvedSignUp {
36
43
  readonly channels: Readonly<Partial<Record<SignUpChannel, ReadonlyArray<string>>>>;
44
+ /** The websites whose visitors may sign up on `web`, by origin. */
45
+ readonly origins?: ReadonlyArray<string>;
37
46
  }
47
+ /**
48
+ * The origin a website's address declares, when it is one `signUp.origins` accepts: the exact
49
+ * origin of an `https` address, or of an `http` address on `localhost` or `127.0.0.1`, written as
50
+ * the origin alone, without a path.
51
+ */
52
+ export declare function signUpOrigin(value: unknown): string | undefined;
38
53
  /** How people become members of the app. Email and channel admission are independent. */
39
54
  export interface SignInOptions {
40
55
  readonly policy: SignInPolicy;
package/dist/sign-in.js CHANGED
@@ -10,15 +10,35 @@ export const DEFAULT_SIGN_IN_POLICY = "invited";
10
10
  /** Channels `signIn.channels` can open; `signUp` replaces it. */
11
11
  export const CHANNEL_PROVIDERS = ["telegram"];
12
12
  /**
13
- * The channels a stranger may sign up through. `email` is sign-in by email code in the app; the
14
- * others are a first private message to the agent, or opening the Telegram Mini App.
13
+ * The channels a stranger may sign up through. `email` is sign-in by email code in the app; `web`
14
+ * is a visitor who writes to the agent from one of the websites `signUp.origins` names; the others
15
+ * are a first private message to the agent, or opening the Telegram Mini App.
15
16
  */
16
- export const SIGN_UP_CHANNELS = ["email", "telegram", "whatsapp"];
17
+ export const SIGN_UP_CHANNELS = ["email", "telegram", "whatsapp", "web"];
17
18
  /** The sign-up channels a person reaches through a chat, which need a matching `chat` adapter. */
18
19
  export const SIGN_UP_CHAT_CHANNELS = ["telegram", "whatsapp"];
19
20
  export function isSignUpChannel(value) {
20
21
  return SIGN_UP_CHANNELS.includes(value);
21
22
  }
23
+ /**
24
+ * The origin a website's address declares, when it is one `signUp.origins` accepts: the exact
25
+ * origin of an `https` address, or of an `http` address on `localhost` or `127.0.0.1`, written as
26
+ * the origin alone, without a path.
27
+ */
28
+ export function signUpOrigin(value) {
29
+ if (typeof value !== "string" || !URL.canParse(value)) {
30
+ return undefined;
31
+ }
32
+ const url = new URL(value);
33
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
34
+ // The service compares a browser's origin exactly, so a pattern such as `*.example.com` would
35
+ // match nothing.
36
+ return (url.protocol === "https:" || (url.protocol === "http:" && local)) &&
37
+ !url.hostname.includes("*") &&
38
+ url.origin === value
39
+ ? url.origin
40
+ : undefined;
41
+ }
22
42
  /**
23
43
  * How a person signs in with an address. `code`: a six-digit code, for a member who has signed in
24
44
  * with Neon Auth before, so their Neon Auth account exists. `link`: an emailed sign-in link, for
@@ -6,7 +6,7 @@ export declare const ATTACHMENTS_TABLE = "_agent_attachments";
6
6
  * Where an attachment comes from: a chat message on a channel, or a file the agent produced in its
7
7
  * sandbox and stores so that an action can keep it.
8
8
  */
9
- export declare const ATTACHMENT_SOURCES: readonly ["telegram", "slack", "sandbox"];
9
+ export declare const ATTACHMENT_SOURCES: readonly ["telegram", "slack", "whatsapp", "sandbox"];
10
10
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
11
11
  export declare const ATTACHMENT_SOURCE_CHECK = "_agent_attachments_source_check";
12
12
  /**
@@ -59,7 +59,7 @@ export const ATTACHMENTS_TABLE = "_agent_attachments";
59
59
  * Where an attachment comes from: a chat message on a channel, or a file the agent produced in its
60
60
  * sandbox and stores so that an action can keep it.
61
61
  */
62
- export const ATTACHMENT_SOURCES = ["telegram", "slack", "sandbox"];
62
+ export const ATTACHMENT_SOURCES = ["telegram", "slack", "whatsapp", "sandbox"];
63
63
  /** The check that limits `source` to {@link ATTACHMENT_SOURCES}; its name is PostgreSQL's default. */
64
64
  export const ATTACHMENT_SOURCE_CHECK = `${ATTACHMENTS_TABLE}_source_check`;
65
65
  const SOURCE_CHECK = `CHECK ("source" IN (${ATTACHMENT_SOURCES.map((source) => `'${source}'`).join(", ")}))`;
@@ -5,6 +5,7 @@ import type { Files } from "./files.js";
5
5
  import type { OntologyActions, OntologyReads, OntologyWrites } from "./runtime.js";
6
6
  import type { StartRecoveryInput, StartRecoveryOutcome } from "./start-recovery-contract.js";
7
7
  import type { WorkflowReservation } from "./runtime/workflow-admission.js";
8
+ import type { WorkflowStructures } from "./workflow-structure.js";
8
9
  /**
9
10
  * The ontology service's workflow runtime, shared through `globalThis` so that every copy of this
10
11
  * module a bundler makes sees the same one. This module imports none of the Workflow SDK: the
@@ -87,6 +88,10 @@ export declare function workflowBinding(): WorkflowBinding | undefined;
87
88
  export declare function setPlatformWorkflows(workflows: PlatformWorkflows | undefined): void;
88
89
  /** The platform's workflow functions as the generated plugin registered them; `undefined` before. */
89
90
  export declare function platformWorkflows(): PlatformWorkflows | undefined;
91
+ /** Registers what the build read of each workflow's code; the latest registration wins. */
92
+ export declare function setWorkflowStructures(structures: WorkflowStructures | undefined): void;
93
+ /** The build's workflow structures by workflow id, as the generated plugin registered them. */
94
+ export declare function workflowStructures(): WorkflowStructures | undefined;
90
95
  /** The Workflow SDK as `installWorkflowRuntime()` registered it; `undefined` before. */
91
96
  export declare function workflowSdk(): WorkflowSdk | undefined;
92
97
  /** `run` was called where no step runs: in a `"use workflow"` body or outside any workflow. */
@@ -17,6 +17,7 @@ export const WORKFLOW_ROUTE_BASE = "/.well-known/workflow/v1";
17
17
  const BINDING = Symbol.for("@segmentstream/ontology/workflow-binding");
18
18
  const SDK = Symbol.for("@segmentstream/ontology/workflow-sdk");
19
19
  const PLATFORM = Symbol.for("@segmentstream/ontology/platform-workflows");
20
+ const STRUCTURES = Symbol.for("@segmentstream/ontology/workflow-structures");
20
21
  const globals = globalThis;
21
22
  /** Registers the Workflow SDK for the service's workflow routes; the first registration stays. */
22
23
  export function setWorkflowSdk(sdk) {
@@ -37,6 +38,14 @@ export function setPlatformWorkflows(workflows) {
37
38
  export function platformWorkflows() {
38
39
  return globals[PLATFORM];
39
40
  }
41
+ /** Registers what the build read of each workflow's code; the latest registration wins. */
42
+ export function setWorkflowStructures(structures) {
43
+ globals[STRUCTURES] = structures;
44
+ }
45
+ /** The build's workflow structures by workflow id, as the generated plugin registered them. */
46
+ export function workflowStructures() {
47
+ return globals[STRUCTURES];
48
+ }
40
49
  /** The Workflow SDK as `installWorkflowRuntime()` registered it; `undefined` before. */
41
50
  export function workflowSdk() {
42
51
  return globals[SDK];