@fungi.computer/oyster 0.10.0 → 0.12.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 (107) hide show
  1. package/README.md +103 -12
  2. package/dist/agents.d.ts +66 -22
  3. package/dist/agents.js +128 -38
  4. package/dist/app-builds.d.ts +2 -0
  5. package/dist/app-builds.js +17 -6
  6. package/dist/authorization.d.ts +25 -3
  7. package/dist/authorization.js +47 -14
  8. package/dist/browser/capability-source.d.ts +23 -5
  9. package/dist/browser/capability-source.js +19 -22
  10. package/dist/browser/index.d.ts +2 -1
  11. package/dist/browser/index.js +1 -0
  12. package/dist/browser/live-view.d.ts +38 -0
  13. package/dist/browser/live-view.js +179 -0
  14. package/dist/build/artifact-writer.d.ts +11 -2
  15. package/dist/build/artifact-writer.js +42 -24
  16. package/dist/build/candidate-cli.mjs +26 -18
  17. package/dist/build/content-objects.d.ts +29 -14
  18. package/dist/build/content-objects.js +57 -19
  19. package/dist/build/local-build.js +3 -0
  20. package/dist/build/submission-contract.d.ts +1 -1
  21. package/dist/build/submission-contract.js +5 -5
  22. package/dist/build-egress.d.ts +8 -7
  23. package/dist/build-egress.js +4 -3
  24. package/dist/build.d.ts +1 -1
  25. package/dist/channels/binding.d.ts +2 -0
  26. package/dist/channels/run-decision.d.ts +33 -0
  27. package/dist/channels/run-decision.js +25 -0
  28. package/dist/channels/visitor-channel.d.ts +84 -14
  29. package/dist/channels/visitor-channel.js +55 -32
  30. package/dist/channels/visitor-edge.d.ts +18 -2
  31. package/dist/channels/visitor-edge.js +67 -5
  32. package/dist/channels/visitors.d.ts +4 -0
  33. package/dist/channels/visitors.js +22 -1
  34. package/dist/channels/web-binding.d.ts +117 -0
  35. package/dist/channels/web-binding.js +227 -0
  36. package/dist/embed-metafiles.d.ts +8 -0
  37. package/dist/embed-metafiles.js +2 -0
  38. package/dist/embed-scripts.d.ts +8 -0
  39. package/dist/embed-scripts.js +3 -0
  40. package/dist/host.d.ts +3 -1
  41. package/dist/host.js +6 -1
  42. package/dist/install-release-cli.d.ts +2 -1
  43. package/dist/install-release-cli.js +18 -10
  44. package/dist/installation-client.d.ts +1 -0
  45. package/dist/installation-operations.d.ts +2 -0
  46. package/dist/installation-operations.js +1 -0
  47. package/dist/pack.d.ts +5 -2
  48. package/dist/pack.js +3 -1
  49. package/dist/page/embed-challenge.d.ts +19 -0
  50. package/dist/page/embed-challenge.js +45 -0
  51. package/dist/page/embed-error.d.ts +2 -0
  52. package/dist/page/embed-error.js +16 -0
  53. package/dist/page/embed-loader-protocol.d.ts +12 -0
  54. package/dist/page/embed-loader-protocol.js +29 -0
  55. package/dist/standalone/agent-connections.d.ts +22 -19
  56. package/dist/standalone/agent-connections.js +150 -106
  57. package/dist/standalone/agents.d.ts +174 -16
  58. package/dist/standalone/agents.js +331 -21
  59. package/dist/standalone/browser.d.ts +14 -2
  60. package/dist/standalone/browser.js +52 -4
  61. package/dist/standalone/channel-session-door.d.ts +4 -0
  62. package/dist/standalone/channel-session-door.js +72 -0
  63. package/dist/standalone/computer-egress.d.ts +5 -3
  64. package/dist/standalone/computer-egress.js +1 -1
  65. package/dist/standalone/hello-app.d.ts +9 -0
  66. package/dist/standalone/hello-app.js +78 -0
  67. package/dist/standalone/install-apps-cli.d.ts +2 -1
  68. package/dist/standalone/install-apps-cli.js +36 -14
  69. package/dist/standalone/instance.js +2 -2
  70. package/dist/standalone/local-desktop.d.ts +11 -0
  71. package/dist/standalone/local-desktop.js +75 -0
  72. package/dist/standalone/owner-routes.d.ts +4 -3
  73. package/dist/standalone/owner-routes.js +7 -1
  74. package/dist/standalone/registry.d.ts +2 -0
  75. package/dist/standalone/sign-in-link.d.ts +9 -0
  76. package/dist/standalone/sign-in-link.js +49 -0
  77. package/dist/standalone/try-cli.d.ts +52 -0
  78. package/dist/standalone/try-cli.js +404 -0
  79. package/dist/standalone/visitor-edge.d.ts +36 -0
  80. package/dist/standalone/visitor-edge.js +67 -0
  81. package/dist/standalone/visitor-proof.d.ts +23 -0
  82. package/dist/standalone/visitor-proof.js +67 -0
  83. package/dist/standalone/website-channels.d.ts +134 -0
  84. package/dist/standalone/website-channels.js +262 -0
  85. package/dist/standalone/worker-routes.d.ts +4 -1
  86. package/dist/standalone/worker-routes.js +3 -0
  87. package/dist/standalone/worker.d.ts +2 -1
  88. package/dist/standalone/worker.js +5 -1
  89. package/dist/testing/capabilities.d.ts +3 -0
  90. package/dist/testing/capabilities.js +1 -0
  91. package/dist/testing/installation.d.ts +4 -2
  92. package/dist/testing/installation.js +7 -2
  93. package/dist/webhook-abuse.d.ts +7 -1
  94. package/dist/webhook-abuse.js +8 -2
  95. package/dist/workers-git.js +2 -2
  96. package/dist/workers.d.ts +7 -2
  97. package/dist/workers.js +1 -1
  98. package/docs/api/agents.md +103 -36
  99. package/docs/api/authorization.md +56 -11
  100. package/docs/api/browser.md +115 -8
  101. package/docs/api/build-contract.md +52 -10
  102. package/docs/api/build.md +16 -2
  103. package/docs/api/host.md +1 -0
  104. package/docs/api/pack.md +179 -3
  105. package/docs/api/workers-git.md +6 -6
  106. package/docs/site/agent-quickstart.mdx +8 -0
  107. package/package.json +34 -8
@@ -1,37 +1,103 @@
1
1
  import { type ConversationBinding } from "./binding.js";
2
2
  import { type ChannelConversations, type ChannelWithdrawResult, type InboundEvent, type IntakeResult, type SessionDoor, type VisitorPendingPrompt, type VisitorReadOptions } from "./conversations.js";
3
3
  import type { ChannelVisitors, VisitorGrant } from "./visitors.js";
4
+ export type AuthenticatedChannelVisitor = NonNullable<Awaited<ReturnType<ChannelVisitors["authenticate"]>>>;
4
5
  /**
5
- * Web visitor sequencing only. The host owns authorization, its admission
6
- * receipt and the Session implementation; identity and conversations can live
7
- * in different stores (and, in standalone, different Agents).
6
+ * Conversation work on an already authenticated visitor. Only the trusted
7
+ * edge/host can choose this path; no client-supplied visitor id is decoded here.
8
+ * The Hub's token-bearing door composes this same owner below.
8
9
  */
9
- export declare function createVisitorChannel(options: Readonly<{
10
+ export declare function createAuthenticatedVisitorChannel(options: Readonly<{
10
11
  binding: (bindingId: string) => ConversationBinding | null;
11
- visitors: () => ChannelVisitors;
12
12
  conversations: () => ChannelConversations;
13
13
  sessionDoor: () => SessionDoor;
14
14
  intake: (event: InboundEvent) => Promise<IntakeResult>;
15
15
  acquireStream: (bindingId: string, visitorId: string, addressHash: string) => (() => void) | null;
16
16
  now: () => number;
17
17
  }>): {
18
- mint: (bindingId: string, siteKey: string, addressHash: string) => Promise<VisitorGrant>;
19
- refresh: (bindingId: string, secret: string) => Promise<VisitorGrant>;
20
- rotate: (bindingId: string, siteKey: string, token: string, addressHash: string) => Promise<VisitorGrant | Readonly<{
18
+ send: (bindingId: string, visitor: AuthenticatedChannelVisitor, requestId: string, text: string) => Promise<IntakeResult>;
19
+ withdraw: (bindingId: string, visitor: AuthenticatedChannelVisitor, rawRequestId: string) => Promise<ChannelWithdrawResult | Readonly<{
21
20
  kind: "unauthorized";
21
+ }> | Readonly<{
22
+ kind: "denied";
23
+ reason: "event_conflict" | "new_party_limit" | "banned";
22
24
  }>>;
23
- send: (bindingId: string, token: string, requestId: string, text: string) => Promise<IntakeResult | Readonly<{
25
+ latestPending: (bindingId: string, visitor: AuthenticatedChannelVisitor) => Promise<VisitorPendingPrompt | null | Readonly<{
24
26
  kind: "unauthorized";
25
27
  }>>;
26
- withdraw: (bindingId: string, token: string, rawRequestId: string) => Promise<ChannelWithdrawResult | Readonly<{
28
+ open: (bindingId: string, visitor: AuthenticatedChannelVisitor, read: VisitorReadOptions) => Promise<Readonly<{
29
+ kind: "session";
30
+ snapshot: string;
31
+ }> | Readonly<{
27
32
  kind: "unauthorized";
28
33
  }> | Readonly<{
29
34
  kind: "denied";
30
- reason: "event_conflict" | "new_party_limit" | "banned";
35
+ reason: "new_party_limit" | "banned";
36
+ }>>;
37
+ watch: (bindingId: string, visitor: AuthenticatedChannelVisitor, canRead: (visitorId: string) => Promise<boolean>) => Promise<Readonly<{
38
+ kind: "stream";
39
+ body: ReadableStream<Uint8Array>;
40
+ }> | Readonly<{
41
+ kind: "empty" | "unauthorized";
42
+ }> | Readonly<{
43
+ kind: "denied";
44
+ reason: "suspended" | "stream_limit";
31
45
  }>>;
32
- latestPending: (bindingId: string, token: string) => Promise<VisitorPendingPrompt | null | Readonly<{
46
+ };
47
+ /** Hub's token-bearing channel uses the same conversation decisions as a
48
+ * standalone Agent whose edge already authenticated the central visitor. */
49
+ export declare function createVisitorChannel(options: Parameters<typeof createAuthenticatedVisitorChannel>[0] & Readonly<{
50
+ visitors: () => ChannelVisitors;
51
+ }>): {
52
+ mint: (bindingId: string, siteKey: string, addressHash: string) => Promise<VisitorGrant>;
53
+ refresh: (bindingId: string, secret: string) => Promise<VisitorGrant>;
54
+ rotate: (bindingId: string, siteKey: string, token: string, addressHash: string) => Promise<VisitorGrant | Readonly<{
33
55
  kind: "unauthorized";
34
56
  }>>;
57
+ send: (bindingId: string, token: string, requestId: string, text: string) => Promise<Readonly<{
58
+ kind: "accepted";
59
+ sessionId: string;
60
+ commandId: string;
61
+ delivery: "new" | "replay";
62
+ }> | Readonly<{
63
+ kind: "held";
64
+ sessionId: string;
65
+ delivery: "new" | "replay";
66
+ }> | Readonly<{
67
+ kind: "denied";
68
+ reason: "unmapped" | "suspended" | "banned" | "too_long" | "party_daily_limit" | "new_party_limit" | "rate_limited" | "event_conflict";
69
+ }> | {
70
+ readonly kind: "unauthorized";
71
+ }>;
72
+ withdraw: (bindingId: string, token: string, requestId: string) => Promise<Readonly<{
73
+ status: "unknown";
74
+ }> | Readonly<{
75
+ status: "accepted";
76
+ commandId: string;
77
+ sessionId?: string;
78
+ }> | Readonly<{
79
+ kind: "unauthorized";
80
+ }> | Readonly<{
81
+ kind: "denied";
82
+ reason: "event_conflict" | "new_party_limit" | "banned";
83
+ }> | {
84
+ readonly kind: "unauthorized";
85
+ }>;
86
+ latestPending: (bindingId: string, token: string) => Promise<Readonly<{
87
+ requestId: string;
88
+ commandId: string;
89
+ text: string;
90
+ delivery: "steer" | "followUp";
91
+ images?: readonly Readonly<{
92
+ type: "image";
93
+ data: string;
94
+ mimeType: string;
95
+ }>[] | undefined;
96
+ }> | Readonly<{
97
+ kind: "unauthorized";
98
+ }> | {
99
+ readonly kind: "unauthorized";
100
+ } | null>;
35
101
  open: (bindingId: string, token: string, read: VisitorReadOptions) => Promise<Readonly<{
36
102
  kind: "session";
37
103
  snapshot: string;
@@ -40,7 +106,9 @@ export declare function createVisitorChannel(options: Readonly<{
40
106
  }> | Readonly<{
41
107
  kind: "denied";
42
108
  reason: "new_party_limit" | "banned";
43
- }>>;
109
+ }> | {
110
+ readonly kind: "unauthorized";
111
+ }>;
44
112
  watch: (bindingId: string, token: string, canRead: (visitorId: string) => Promise<boolean>) => Promise<Readonly<{
45
113
  kind: "stream";
46
114
  body: ReadableStream<Uint8Array>;
@@ -49,5 +117,7 @@ export declare function createVisitorChannel(options: Readonly<{
49
117
  }> | Readonly<{
50
118
  kind: "denied";
51
119
  reason: "suspended" | "stream_limit";
52
- }>>;
120
+ }> | {
121
+ readonly kind: "unauthorized";
122
+ }>;
53
123
  };
@@ -2,11 +2,11 @@ import { partyLabel } from "./binding.js";
2
2
  import { channelRequestId, } from "./conversations.js";
3
3
  import { visitorMessageId, visitorRequestSchema } from "./visitor-request.js";
4
4
  /**
5
- * Web visitor sequencing only. The host owns authorization, its admission
6
- * receipt and the Session implementation; identity and conversations can live
7
- * in different stores (and, in standalone, different Agents).
5
+ * Conversation work on an already authenticated visitor. Only the trusted
6
+ * edge/host can choose this path; no client-supplied visitor id is decoded here.
7
+ * The Hub's token-bearing door composes this same owner below.
8
8
  */
9
- export function createVisitorChannel(options) {
9
+ export function createAuthenticatedVisitorChannel(options) {
10
10
  const active = (bindingId) => {
11
11
  const binding = options.binding(bindingId);
12
12
  return binding?.lifecycle === "active" &&
@@ -14,22 +14,8 @@ export function createVisitorChannel(options) {
14
14
  ? binding
15
15
  : null;
16
16
  };
17
- const authenticate = (bindingId, token) => options.visitors().authenticate(bindingId, token);
18
17
  return {
19
- mint: (bindingId, siteKey, addressHash) => options.visitors().mint(options.binding(bindingId), siteKey, addressHash),
20
- refresh: (bindingId, secret) => options.visitors().refresh(options.binding(bindingId), secret),
21
- rotate: async (bindingId, siteKey, token, addressHash) => {
22
- const visitors = options.visitors();
23
- const visitor = await visitors.authenticate(bindingId, token);
24
- if (visitor === null)
25
- return { kind: "unauthorized" };
26
- visitors.forget(visitor.visitorId);
27
- return await visitors.mint(options.binding(bindingId), siteKey, addressHash);
28
- },
29
- send: async (bindingId, token, requestId, text) => {
30
- const visitor = await authenticate(bindingId, token);
31
- if (visitor === null)
32
- return { kind: "unauthorized" };
18
+ send: async (bindingId, visitor, requestId, text) => {
33
19
  const { visitorId } = visitor;
34
20
  return options.intake({
35
21
  bindingId,
@@ -40,10 +26,9 @@ export function createVisitorChannel(options) {
40
26
  sourceRequestId: requestId,
41
27
  });
42
28
  },
43
- withdraw: async (bindingId, token, rawRequestId) => {
29
+ withdraw: async (bindingId, visitor, rawRequestId) => {
44
30
  const binding = active(bindingId);
45
- const visitor = await authenticate(bindingId, token);
46
- if (visitor === null || binding === null)
31
+ if (binding === null)
47
32
  return { kind: "unauthorized" };
48
33
  const { requestId } = visitorRequestSchema.parse({
49
34
  requestId: rawRequestId,
@@ -62,10 +47,9 @@ export function createVisitorChannel(options) {
62
47
  .sessionDoor()
63
48
  .withdraw(opened.conversation.sessionId, channelRequestId(binding.bindingId, eventId));
64
49
  },
65
- latestPending: async (bindingId, token) => {
50
+ latestPending: async (bindingId, visitor) => {
66
51
  const binding = active(bindingId);
67
- const visitor = await authenticate(bindingId, token);
68
- if (visitor === null || binding === null)
52
+ if (binding === null)
69
53
  return { kind: "unauthorized" };
70
54
  const { visitorId } = visitor;
71
55
  const conversation = options.conversations().find(bindingId, visitorId);
@@ -76,10 +60,9 @@ export function createVisitorChannel(options) {
76
60
  name: partyLabel({ kind: "visitor", visitorId }),
77
61
  });
78
62
  },
79
- open: async (bindingId, token, read) => {
63
+ open: async (bindingId, visitor, read) => {
80
64
  const binding = active(bindingId);
81
- const visitor = await authenticate(bindingId, token);
82
- if (visitor === null || binding === null)
65
+ if (binding === null)
83
66
  return { kind: "unauthorized" };
84
67
  const { visitorId } = visitor;
85
68
  const opened = await options.conversations().open(binding, visitorId, {
@@ -95,10 +78,7 @@ export function createVisitorChannel(options) {
95
78
  .participantDocument(opened.conversation.sessionId, visitorId, read),
96
79
  };
97
80
  },
98
- watch: async (bindingId, token, canRead) => {
99
- const visitor = await authenticate(bindingId, token);
100
- if (visitor === null)
101
- return { kind: "unauthorized" };
81
+ watch: async (bindingId, visitor, canRead) => {
102
82
  if (options.binding(bindingId)?.lifecycle !== "active")
103
83
  return { kind: "denied", reason: "suspended" };
104
84
  const { visitorId } = visitor;
@@ -122,3 +102,46 @@ export function createVisitorChannel(options) {
122
102
  },
123
103
  };
124
104
  }
105
+ /** Hub's token-bearing channel uses the same conversation decisions as a
106
+ * standalone Agent whose edge already authenticated the central visitor. */
107
+ export function createVisitorChannel(options) {
108
+ const channel = createAuthenticatedVisitorChannel(options);
109
+ const authenticate = (bindingId, token) => options.visitors().authenticate(bindingId, token);
110
+ return {
111
+ mint: (bindingId, siteKey, addressHash) => options.visitors().mint(options.binding(bindingId), siteKey, addressHash),
112
+ refresh: (bindingId, secret) => options.visitors().refresh(options.binding(bindingId), secret),
113
+ rotate: async (bindingId, siteKey, token, addressHash) => options
114
+ .visitors()
115
+ .rotate(options.binding(bindingId), siteKey, token, addressHash),
116
+ send: async (bindingId, token, requestId, text) => {
117
+ const visitor = await authenticate(bindingId, token);
118
+ return visitor === null
119
+ ? { kind: "unauthorized" }
120
+ : channel.send(bindingId, visitor, requestId, text);
121
+ },
122
+ withdraw: async (bindingId, token, requestId) => {
123
+ const visitor = await authenticate(bindingId, token);
124
+ return visitor === null
125
+ ? { kind: "unauthorized" }
126
+ : channel.withdraw(bindingId, visitor, requestId);
127
+ },
128
+ latestPending: async (bindingId, token) => {
129
+ const visitor = await authenticate(bindingId, token);
130
+ return visitor === null
131
+ ? { kind: "unauthorized" }
132
+ : channel.latestPending(bindingId, visitor);
133
+ },
134
+ open: async (bindingId, token, read) => {
135
+ const visitor = await authenticate(bindingId, token);
136
+ return visitor === null
137
+ ? { kind: "unauthorized" }
138
+ : channel.open(bindingId, visitor, read);
139
+ },
140
+ watch: async (bindingId, token, canRead) => {
141
+ const visitor = await authenticate(bindingId, token);
142
+ return visitor === null
143
+ ? { kind: "unauthorized" }
144
+ : channel.watch(bindingId, visitor, canRead);
145
+ },
146
+ };
147
+ }
@@ -2,16 +2,29 @@ import { Hono, type Context, type Env as HonoEnv } from "hono";
2
2
  import type { ChannelWithdrawResult, IntakeResult, VisitorPendingPrompt, VisitorReadOptions } from "./conversations.js";
3
3
  import { type VisitorGrant } from "./visitors.js";
4
4
  import type { Avatar } from "@fungi.computer/sprite/avatar";
5
+ import { type TurnstileConfiguration } from "../turnstile.js";
5
6
  /** Public address facts the host supplies after looking up an embed site. */
6
7
  export type VisitorSiteAddress = Readonly<{
7
8
  bindingId: string;
8
9
  }>;
9
10
  /** Embed-safe site chrome returned by the host after binding admission. */
10
- export type VisitorSiteFacts = Readonly<{
11
+ export type VisitorSiteFacts = {
11
12
  accent?: string;
12
13
  name: string;
13
14
  avatar: Avatar;
14
15
  origins: readonly string[];
16
+ /** The owner requires a Turnstile check before this site mints a visitor. */
17
+ turnstile?: boolean;
18
+ };
19
+ /** How a host checks a site's Turnstile requirement; read per request. */
20
+ export type VisitorTurnstile = Readonly<{
21
+ configuration: TurnstileConfiguration;
22
+ timeoutMs: number;
23
+ onError: (cause: unknown) => void;
24
+ }>;
25
+ declare const verifiedByVisitorEdge: unique symbol;
26
+ export type EdgeVerifiedVisitor<V extends object> = V & Readonly<{
27
+ [verifiedByVisitorEdge]: true;
15
28
  }>;
16
29
  /** An opened host door, disposed after the edge has returned a response. */
17
30
  export type VisitorEdgeChannel = Readonly<{
@@ -107,9 +120,12 @@ export type VisitorEdgeHost<E extends HonoEnv, Site extends VisitorSiteAddress,
107
120
  resolveSite: (context: Context<E>, siteKey: string) => Promise<Site | null>;
108
121
  openSite: (context: Context<E>, site: Site) => Promise<VisitorEdgeChannel>;
109
122
  authenticateVisitor: (context: Context<E>, site: Site, token: string) => Promise<Visitor | null>;
110
- openChannel: (context: Context<E>, site: Site, visitor: Visitor) => Promise<VisitorEdgeChannel>;
123
+ openChannel: (context: Context<E>, site: Site, visitor: EdgeVerifiedVisitor<Visitor>) => Promise<VisitorEdgeChannel>;
111
124
  addressHash: (context: Context<E>) => Promise<string>;
125
+ /** Host-owned Turnstile configuration, applied to sites that require it. */
126
+ turnstile: (context: Context<E>) => VisitorTurnstile;
112
127
  assetPath: (kind: "widget" | "styles") => string;
113
128
  onError: (error: Error, context: Context<E>) => Response | Promise<Response>;
114
129
  }>;
115
130
  export declare function createVisitorEdge<E extends HonoEnv, Site extends VisitorSiteAddress, Visitor extends object>(host: VisitorEdgeHost<E, Site, Visitor>): Hono<E>;
131
+ export {};
@@ -60,6 +60,7 @@ import { channelIds } from "./ids.js";
60
60
  import { originAllowed } from "./binding.js";
61
61
  import { visitorBearerSchema } from "./visitors.js";
62
62
  import { visitorRequestSchema } from "./visitor-request.js";
63
+ import { verifyTurnstileToken, } from "../turnstile.js";
63
64
  /**
64
65
  * The public web-channel edge. The host owns address lookup, visitor identity
65
66
  * and Agent selection. Current conversation operations authenticate their
@@ -73,6 +74,9 @@ const messageSchema = visitorRequestSchema.extend({
73
74
  text: z.string().trim().min(1).max(16_000),
74
75
  });
75
76
  const refreshSchema = z.strictObject({ refreshSecret: visitorBearerSchema });
77
+ const mintSchema = z.strictObject({
78
+ turnstileToken: z.string().min(1).max(2048).optional(),
79
+ });
76
80
  const sessionReadSchema = z
77
81
  .strictObject({
78
82
  limit: z.number().int().min(1).max(200).optional(),
@@ -86,6 +90,9 @@ const sessionReadSchema = z
86
90
  return { limit: value.limit, before: value.before };
87
91
  });
88
92
  const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
93
+ // An edge-local type marker, not a wire credential. Only authentication here
94
+ // constructs it; the Agent verifies a separate HMAC after DO RPC cloning.
95
+ const verifiedByVisitorEdge = Symbol("oyster.edge-authenticated");
89
96
  const DENIAL_STATUS = {
90
97
  unmapped: 404,
91
98
  suspended: 403,
@@ -99,6 +106,9 @@ const DENIAL_STATUS = {
99
106
  event_conflict: 409,
100
107
  refresh_invalid: 401,
101
108
  refresh_reused: 401,
109
+ turnstile_required: 400,
110
+ turnstile_failed: 403,
111
+ turnstile_unavailable: 503,
102
112
  };
103
113
  function denied(reason) {
104
114
  return Response.json({ error: reason }, { status: DENIAL_STATUS[reason], headers: { "cache-control": "no-store" } });
@@ -130,7 +140,7 @@ function frameAncestors(origins) {
130
140
  .join(" ");
131
141
  }
132
142
  /** Both values are already parsed: a site key and an optional `#rrggbb`. */
133
- async function embedDocument(siteKey, facts, assets) {
143
+ async function embedDocument(siteKey, facts, assets, turnstileSiteKey) {
134
144
  return (await html `<!doctype html>
135
145
  <html lang="en">
136
146
  <head>
@@ -147,11 +157,28 @@ async function embedDocument(siteKey, facts, assets) {
147
157
  data-accent="${facts.accent ?? ""}"
148
158
  data-name="${facts.name}"
149
159
  data-avatar="${JSON.stringify(facts.avatar)}"
160
+ data-turnstile-site="${turnstileSiteKey ?? ""}"
150
161
  ></div>
151
162
  <script type="module" src="${assets("widget")}"></script>
152
163
  </body>
153
164
  </html>`).toString();
154
165
  }
166
+ /** The reason a Turnstile-protected mint is refused, or null when it may go on. */
167
+ async function refuseWithoutTurnstile(turnstile, token, remoteIp) {
168
+ const { configuration } = turnstile;
169
+ if (configuration.kind === "disabled")
170
+ return null;
171
+ if (configuration.kind === "misconfigured")
172
+ return "turnstile_unavailable";
173
+ if (token === undefined)
174
+ return "turnstile_required";
175
+ const verdict = await verifyTurnstileToken(remoteIp === undefined
176
+ ? { secretKey: configuration.secretKey, token }
177
+ : { secretKey: configuration.secretKey, token, remoteIp }, { timeoutMs: turnstile.timeoutMs, onError: turnstile.onError });
178
+ if (verdict === "passed")
179
+ return null;
180
+ return verdict === "failed" ? "turnstile_failed" : "turnstile_unavailable";
181
+ }
155
182
  export function createVisitorEdge(host) {
156
183
  async function route(context) {
157
184
  const siteKey = siteKeySchema.safeParse(context.req.param("siteKey"));
@@ -163,7 +190,11 @@ export function createVisitorEdge(host) {
163
190
  const visitor = await host.authenticateVisitor(context, site, token);
164
191
  if (visitor === null)
165
192
  return null;
166
- return host.openChannel(context, site, visitor);
193
+ const verified = {
194
+ ...visitor,
195
+ [verifiedByVisitorEdge]: true,
196
+ };
197
+ return host.openChannel(context, site, verified);
167
198
  }
168
199
  return new Hono()
169
200
  .onError(host.onError)
@@ -181,7 +212,12 @@ export function createVisitorEdge(host) {
181
212
  });
182
213
  if (facts === null)
183
214
  return context.text("Not found", 404);
184
- return new Response(await embedDocument(siteKey, facts, host.assetPath), {
215
+ const challenge = host.turnstile(context).configuration;
216
+ const turnstileSiteKey = facts.turnstile === true && challenge.kind === "enabled"
217
+ ? challenge.siteKey
218
+ : null;
219
+ const challengeOrigin = "https://challenges.cloudflare.com";
220
+ return new Response(await embedDocument(siteKey, facts, host.assetPath, turnstileSiteKey), {
185
221
  headers: {
186
222
  "content-type": "text/html; charset=utf-8",
187
223
  "cache-control": "no-store",
@@ -189,11 +225,18 @@ export function createVisitorEdge(host) {
189
225
  "x-content-type-options": "nosniff",
190
226
  "content-security-policy": [
191
227
  "default-src 'none'",
192
- "script-src 'self'",
228
+ turnstileSiteKey === null
229
+ ? "script-src 'self'"
230
+ : `script-src 'self' ${challengeOrigin}`,
193
231
  "style-src 'self'",
194
232
  "font-src 'self'",
195
233
  "img-src 'self' data:",
196
- "connect-src 'self'",
234
+ turnstileSiteKey === null
235
+ ? "connect-src 'self'"
236
+ : `connect-src 'self' ${challengeOrigin}`,
237
+ ...(turnstileSiteKey === null
238
+ ? []
239
+ : [`frame-src ${challengeOrigin}`]),
197
240
  "base-uri 'none'",
198
241
  "form-action 'none'",
199
242
  `frame-ancestors ${frameAncestors(facts.origins) || "'none'"}`,
@@ -251,7 +294,26 @@ export function createVisitorEdge(host) {
251
294
  const site = await route(context);
252
295
  if (site === null)
253
296
  return denied("unmapped");
297
+ const raw = await context.req.text();
298
+ if (raw.length > 4_096)
299
+ return denied("too_long");
300
+ const json = raw === "" ? Option.some({}) : decodeJson(raw);
301
+ const body = Option.isNone(json)
302
+ ? null
303
+ : mintSchema.safeParse(json.value);
304
+ if (body?.success !== true)
305
+ return context.json({ error: "invalid_input" }, 400);
254
306
  const channels = __addDisposableResource(env_3, await host.openSite(context, site), false);
307
+ const facts = await channels.readChannelSite({
308
+ bindingId: site.bindingId,
309
+ siteKey: context.req.param("siteKey"),
310
+ });
311
+ // An unreadable site is refused by the mint itself, with its own reason.
312
+ if (facts?.turnstile === true) {
313
+ const refusal = await refuseWithoutTurnstile(host.turnstile(context), body.data.turnstileToken, context.req.header("cf-connecting-ip"));
314
+ if (refusal !== null)
315
+ return denied(refusal);
316
+ }
255
317
  const grant = await channels.mintChannelVisitor({
256
318
  bindingId: site.bindingId,
257
319
  siteKey: context.req.param("siteKey"),
@@ -41,7 +41,11 @@ export declare function createChannelVisitors(options: Readonly<{
41
41
  expiresAt: number;
42
42
  addressHash: string;
43
43
  }> | null>;
44
+ live: (bindingId: string, visitorId: string) => boolean;
44
45
  forget: (visitorId: string) => void;
46
+ rotate: (binding: ConversationBinding | null, siteKey: string, token: string, addressHash: string) => Promise<VisitorGrant | Readonly<{
47
+ kind: "unauthorized";
48
+ }>>;
45
49
  };
46
50
  /** Anonymous visitor identity owner. */
47
51
  export type ChannelVisitors = ReturnType<typeof createChannelVisitors>;
@@ -169,6 +169,17 @@ export function createChannelVisitors(options) {
169
169
  addressHash: address.address_hash,
170
170
  };
171
171
  };
172
+ /**
173
+ * Whether this visitor may still be served: not revoked and holding an
174
+ * unexpired access token. A host that does not keep the bearer asks this at
175
+ * every stream beat, so revocation ends a stream without the token.
176
+ */
177
+ const live = (bindingId, visitorId) => {
178
+ ensure();
179
+ return (sql
180
+ .exec("SELECT 1 FROM hub_channel_visitors v WHERE v.visitor_id=? AND v.binding_id=? AND v.revoked=0 AND EXISTS (SELECT 1 FROM hub_channel_visitor_tokens t WHERE t.visitor_id=v.visitor_id AND t.kind='access' AND t.expires_at>?)", visitorId, bindingId, options.now())
181
+ .toArray().length > 0);
182
+ };
172
183
  /** Revoke a swept visitor and drop its token hashes. */
173
184
  const forget = (visitorId) => {
174
185
  ensure();
@@ -177,5 +188,15 @@ export function createChannelVisitors(options) {
177
188
  sql.exec("DELETE FROM hub_channel_visitor_tokens WHERE visitor_id=?", visitorId);
178
189
  });
179
190
  };
180
- return { ensure, mint, refresh, authenticate, forget };
191
+ /** Revoke the old identity before issuing a replacement on this binding. */
192
+ const rotate = async (binding, siteKey, token, addressHash) => {
193
+ if (binding === null)
194
+ return { kind: "unauthorized" };
195
+ const visitor = await authenticate(binding.bindingId, token);
196
+ if (visitor === null)
197
+ return { kind: "unauthorized" };
198
+ forget(visitor.visitorId);
199
+ return mint(binding, siteKey, addressHash);
200
+ };
201
+ return { ensure, mint, refresh, authenticate, live, forget, rotate };
181
202
  }
@@ -0,0 +1,117 @@
1
+ import { z } from "zod";
2
+ import type { VisitorSql } from "./visitors.js";
3
+ /**
4
+ * The website channel's neutral binding rules: what a site key, its allowed
5
+ * origins and its accent are, how an owner's edit changes them, and the fixed
6
+ * words every website Agent starts from. Team, billing and member authority
7
+ * stay with the host that stores the binding.
8
+ */
9
+ /** Owner-set widget accent: exactly `#rrggbb`, stored lowercase. */
10
+ export declare const hexColorSchema: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
11
+ /** The exact selector of a web binding; the site key is how the embed finds it. */
12
+ export declare const webSelectorSchema: z.ZodObject<{
13
+ provider: z.ZodLiteral<"web">;
14
+ siteKey: z.ZodString;
15
+ origins: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
16
+ accent: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
17
+ turnstile: z.ZodOptional<z.ZodBoolean>;
18
+ }, z.core.$strict>;
19
+ /** One parsed web selector. */
20
+ export type WebSelector = z.infer<typeof webSelectorSchema>;
21
+ /** Owner input for a new web selector. The site key is minted, never supplied. */
22
+ export declare const webSelectorRequestSchema: z.ZodObject<{
23
+ provider: z.ZodLiteral<"web">;
24
+ origins: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
25
+ accent: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
26
+ turnstile: z.ZodOptional<z.ZodBoolean>;
27
+ }, z.core.$strict>;
28
+ /** The edits an owner may make to a web selector. */
29
+ export declare const webSelectorEditSchema: z.ZodObject<{
30
+ origins: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
31
+ accent: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
32
+ turnstile: z.ZodOptional<z.ZodBoolean>;
33
+ rotateSiteKey: z.ZodOptional<z.ZodLiteral<true>>;
34
+ }, z.core.$strict>;
35
+ /** One owner edit of a web selector, as parsed. */
36
+ export type WebSelectorEdit = z.output<typeof webSelectorEditSchema>;
37
+ /** Does this edit touch the web selector at all? */
38
+ export declare function editsWebSelector(edit: Readonly<z.input<typeof webSelectorEditSchema>>): boolean;
39
+ /** Mint the selector of a new web binding. */
40
+ export declare function mintWebSelector(requested: z.output<typeof webSelectorRequestSchema>): WebSelector;
41
+ /** Apply one owner edit to a selector; unmentioned facts are unchanged. */
42
+ export declare function editWebSelector(selector: WebSelector, edit: WebSelectorEdit): WebSelector;
43
+ /** The fixed preamble, then the owner's persona for a person-facing channel. */
44
+ export declare function personChannelInstructions(persona: string): string;
45
+ /** A standalone website: one owner's Agent behind one site key. */
46
+ export declare const websiteBindingSchema: z.ZodObject<{
47
+ bindingId: z.ZodString;
48
+ agentId: z.ZodString;
49
+ selector: z.ZodObject<{
50
+ provider: z.ZodLiteral<"web">;
51
+ siteKey: z.ZodString;
52
+ origins: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
53
+ accent: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
54
+ turnstile: z.ZodOptional<z.ZodBoolean>;
55
+ }, z.core.$strict>;
56
+ lifecycle: z.ZodEnum<{
57
+ active: "active";
58
+ suspended: "suspended";
59
+ }>;
60
+ authorityVersion: z.ZodNumber;
61
+ persona: z.ZodString;
62
+ }, z.core.$strict>;
63
+ /** One standalone website binding. */
64
+ export type WebsiteBinding = z.infer<typeof websiteBindingSchema>;
65
+ /** Owner input for a new website. */
66
+ export declare const createWebsiteInputSchema: z.ZodObject<{
67
+ agentId: z.ZodString;
68
+ selector: z.ZodObject<{
69
+ provider: z.ZodLiteral<"web">;
70
+ origins: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
71
+ accent: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
72
+ turnstile: z.ZodOptional<z.ZodBoolean>;
73
+ }, z.core.$strict>;
74
+ persona: z.ZodDefault<z.ZodString>;
75
+ }, z.core.$strict>;
76
+ /** Owner input for a new website. */
77
+ export type CreateWebsiteInput = z.input<typeof createWebsiteInputSchema>;
78
+ /** Owner edit of one website, fenced by the version the owner last read. */
79
+ export declare const updateWebsiteInputSchema: z.ZodObject<{
80
+ origins: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
81
+ accent: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>>;
82
+ turnstile: z.ZodOptional<z.ZodBoolean>;
83
+ rotateSiteKey: z.ZodOptional<z.ZodLiteral<true>>;
84
+ expectedVersion: z.ZodNumber;
85
+ persona: z.ZodOptional<z.ZodString>;
86
+ lifecycle: z.ZodOptional<z.ZodEnum<{
87
+ active: "active";
88
+ suspended: "suspended";
89
+ }>>;
90
+ }, z.core.$strict>;
91
+ /** Owner edit of one website. */
92
+ export type UpdateWebsiteInput = z.input<typeof updateWebsiteInputSchema>;
93
+ /** Closed owner failures; routes map each to one status. */
94
+ export declare class WebsiteBindingError extends Error {
95
+ readonly code: "not_found" | "version_conflict" | "request_conflict" | "invalid_input";
96
+ constructor(code: "not_found" | "version_conflict" | "request_conflict" | "invalid_input");
97
+ }
98
+ /**
99
+ * One standalone owner's website bindings, behind a SQL port. The owner
100
+ * authorizes the caller; this module fences versions and mints site keys.
101
+ */
102
+ export declare function createWebsiteBindings(options: Readonly<{
103
+ sql: VisitorSql;
104
+ transactionSync: <T>(body: () => T) => T;
105
+ /** Whether the Agent is in this owner's directory. */
106
+ agentExists: (agentId: string) => boolean;
107
+ }>): {
108
+ read: (bindingId: string) => WebsiteBinding | null;
109
+ /** The only way a public site key resolves; a rotated key does not. */
110
+ readBySiteKey: (siteKey: string) => WebsiteBinding | null;
111
+ list: () => readonly WebsiteBinding[];
112
+ /** Create once per request identity; a replay returns the first result. */
113
+ create: (rawInput: CreateWebsiteInput, requestId: string) => WebsiteBinding;
114
+ update: (bindingId: string, rawInput: UpdateWebsiteInput) => WebsiteBinding;
115
+ };
116
+ /** The standalone website binding owner. */
117
+ export type WebsiteBindings = ReturnType<typeof createWebsiteBindings>;