@segmentstream/ontology 0.198.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.199.0
4
+
5
+ Support sender-verified Telegram Mini App pairing in groups and personal chats. Workspace admission can check the delivery chat and require a Cloud sign-in before the agent starts a turn.
6
+
3
7
  ## 0.198.0
4
8
 
5
9
  A user who leaves keeps no credential of an owned connection (`owner="user"`). Once an action that
@@ -414,6 +414,8 @@ export function sqlAgentStore(ontology, sql) {
414
414
  return inserted.length > 0;
415
415
  }))
416
416
  .pipe(Effect.orDie),
417
+ telegramLaunchPairing: (id, sender) => rows(`SELECT "code_hash" FROM ${PAIRINGS} WHERE "id" = $1::uuid AND "provider" = 'telegram'
418
+ AND "external_id" = $2 AND "expires_at" > now()`, [id, sender]).pipe(Effect.map(([row]) => (row ? { codeHash: String(row.code_hash) } : undefined))),
417
419
  findPairing: (codeHash) => rows([
418
420
  `SELECT ${PAIRING_COLUMNS}`,
419
421
  `FROM ${PAIRINGS}`,
@@ -98,6 +98,10 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
98
98
  readonly provider: Schema.String;
99
99
  readonly external_id: Schema.String;
100
100
  readonly display: Schema.optionalKey<Schema.NullOr<Schema.String>>;
101
+ readonly delivery: Schema.optionalKey<Schema.Struct<{
102
+ readonly channel: Schema.String;
103
+ readonly chat_id: Schema.String;
104
+ }>>;
101
105
  }>;
102
106
  export declare const IdentityNoticeRequest: Schema.Struct<{
103
107
  readonly provider: Schema.String;
@@ -107,6 +107,10 @@ export const GuestSignUpRequest = Schema.Union([
107
107
  }),
108
108
  ]);
109
109
  export const ResolveIdentityRequest = Schema.Struct({
110
+ delivery: Schema.optionalKey(Schema.Struct({
111
+ channel: ChatChannelName,
112
+ chat_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
113
+ })),
110
114
  ...PairingRequest.fields,
111
115
  chat: Schema.Literals(["private", "group"]),
112
116
  turn: Schema.Boolean,
@@ -109,8 +109,9 @@ function createPairing(store, limiter) {
109
109
  for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++) {
110
110
  const code = newPairingCode();
111
111
  const expiresAt = new Date(Date.now() + PAIRING_TTL_MS);
112
+ const id = randomUUID();
112
113
  const saved = yield* store.savePairing({
113
- id: randomUUID(),
114
+ id,
114
115
  codeHash: secretHash(code),
115
116
  provider,
116
117
  externalId,
@@ -118,7 +119,7 @@ function createPairing(store, limiter) {
118
119
  expiresAt,
119
120
  });
120
121
  if (saved) {
121
- return json({ code, expires_at: expiresAt.toISOString() }, 201);
122
+ return json({ id, code, expires_at: expiresAt.toISOString() }, 201);
122
123
  }
123
124
  }
124
125
  return yield* Effect.die(new Error("No free pairing code after several attempts."));
@@ -207,8 +208,10 @@ function resolveChannelIdentity(store, agentTools, guest) {
207
208
  if (Result.isFailure(decoded)) {
208
209
  return invalidBody(requestId, schemaIssues(decoded.failure));
209
210
  }
210
- const { external_id: externalId, notice_version, notice_sha256, address_verified, ...input } = decoded.success;
211
- const resolution = yield* store.resolveIdentity({
211
+ const { external_id: externalId, notice_version, notice_sha256, address_verified, delivery, ...input } = decoded.success;
212
+ const resolve = store.inboundIdentity?.get(input.provider) ?? store.resolveIdentity;
213
+ const resolution = yield* resolve({
214
+ ...(delivery && { delivery: { channel: delivery.channel, chatId: delivery.chat_id } }),
212
215
  ...input,
213
216
  externalId,
214
217
  ...(notice_version === undefined ? {} : { noticeVersion: notice_version }),
@@ -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
+ }
@@ -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);
@@ -514,6 +514,11 @@ export interface ResolveIdentityInput {
514
514
  readonly provider: string;
515
515
  readonly externalId: string;
516
516
  readonly chat: "private" | "group";
517
+ /** Trusted delivery address from the verified channel update. */
518
+ readonly delivery?: {
519
+ readonly channel: string;
520
+ readonly chatId: string;
521
+ };
517
522
  readonly turn: boolean;
518
523
  readonly display?: string | null;
519
524
  readonly username?: string;
@@ -566,6 +571,7 @@ export type AgentResolution = {
566
571
  readonly takeover?: true;
567
572
  } | {
568
573
  readonly status: "pairing_required";
574
+ readonly telegramMiniApp?: true;
569
575
  } | {
570
576
  readonly status: "refused";
571
577
  readonly reason: "blocked" | "inactive";
@@ -622,6 +628,10 @@ export interface AgentStore {
622
628
  readonly codeHash: string;
623
629
  }) => Effect.Effect<boolean>;
624
630
  /** A pairing that has neither expired nor been approved. */
631
+ /** The hash stays inside the service. A public launch id alone cannot approve a pairing. */
632
+ readonly telegramLaunchPairing?: (id: string, sender: string) => Effect.Effect<{
633
+ readonly codeHash: string;
634
+ } | undefined>;
625
635
  readonly findPairing: (codeHash: string) => Effect.Effect<AgentPairing | undefined>;
626
636
  /**
627
637
  * Consumes a live pairing once. The same account on the same member is idempotent; another
@@ -635,6 +645,8 @@ export interface AgentStore {
635
645
  }) => Effect.Effect<AgentIdentity | undefined, IdentityInUse>;
636
646
  /** Finds an active identity, or provisions a private sender when the channel admits strangers. */
637
647
  readonly resolveIdentity: (input: ResolveIdentityInput) => Effect.Effect<AgentResolution>;
648
+ /** Optional inbound admission handlers keyed by messenger provider. Each may delegate to resolveIdentity. */
649
+ readonly inboundIdentity?: ReadonlyMap<string, AgentStore["resolveIdentity"]>;
638
650
  /** Complete the leased limit-reply claim only after delivery, or release it after failure. */
639
651
  readonly completeLimitNotice: (input: {
640
652
  readonly notificationId: string;
@@ -1,3 +1,4 @@
1
+ import { telegramPairingLayer } from "./channel/telegram-pairing.js";
1
2
  import { Cause, Context, Effect, Layer, Redacted } from "effect";
2
3
  import { HttpRouter, HttpServer, HttpServerError, HttpServerRequest } from "effect/unstable/http";
3
4
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
@@ -529,6 +530,8 @@ export function createOntologyService(ontology, config) {
529
530
  });
530
531
  const application = Layer.mergeAll(channelApps.length > 0
531
532
  ? Layer.merge(channelSessionLayer(config), channelSignInLayer(channelApps, config, connections))
533
+ : Layer.empty, !preview && telegram?.miniApp && telegramConnection && federationConfig
534
+ ? telegramPairingLayer(config, connections, telegramAppProvider(telegramConnection, testKey), telegramConnection, verifyToken)
532
535
  : Layer.empty, federationLayer(federationConfig, verifyToken, { ontology, browserRevision }), routes, withoutAgent
533
536
  ? Layer.empty
534
537
  : chatRoutes({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.198.0",
3
+ "version": "0.199.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",