@takosjp/yurucommu-core 4.1.1 → 4.1.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@takosjp/yurucommu-core",
3
- "version": "4.1.1",
3
+ "version": "4.1.2",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "workspaces": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@takosjp/yurucommu-api",
3
- "version": "4.1.1",
3
+ "version": "4.1.2",
4
4
  "description": "Typed client SDK and public API contract for yurucommu-server clients.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -1,4 +1,4 @@
1
- import { Hono, type Context } from "hono";
1
+ import { Hono, type Context, type Next } from "hono";
2
2
  import { MOBILE_PUSH_REGISTRATION_PATH } from "./lib/mobile-contract.ts";
3
3
  import { NOTIFICATION_PUSHER_REGISTRATION_PATH } from "./lib/notification-pusher-contract.ts";
4
4
  import type { Env, EnvVars, Variables } from "./types.ts";
@@ -9,7 +9,13 @@ import {
9
9
  wrapRuntimeBindings,
10
10
  wrapRuntimeMessageBatch,
11
11
  type PortableWorkerBindings,
12
+ type RuntimeLane,
12
13
  } from "./runtime/lane.ts";
14
+ import {
15
+ configuredAppUrl,
16
+ establishRequestPublicOrigin,
17
+ withRequiredBackgroundPublicOrigin,
18
+ } from "./runtime/public-origin.ts";
13
19
  import type { EdgeQueueBatch } from "./runtime/edge-facades.ts";
14
20
  import {
15
21
  getMobileOidcAudience,
@@ -925,6 +931,65 @@ function mountStaticFallback(app: YurucommuApp): void {
925
931
  });
926
932
  }
927
933
 
934
+ /**
935
+ * Give this request an `APP_URL` when the Host, not the deployer, chose it.
936
+ *
937
+ * Registered BEFORE every other route so `/readyz` and the `.well-known`
938
+ * discovery documents see the same origin the rest of the app mints ids from —
939
+ * a readiness probe that reported `APP_URL` missing on a Worker whose origin
940
+ * only its own traffic can reveal would never go ready.
941
+ *
942
+ * It runs on the `portable` lane alone. There, a wrapper host routes by
943
+ * hostname and delivers the request it received on the Worker's public
944
+ * endpoint, so the request URL IS the assigned origin (see
945
+ * runtime/public-origin.ts). A Worker deployed straight to Cloudflare answers
946
+ * on workers.dev, on every custom domain, and on every route pattern its
947
+ * account holds, so the same inference there would let whichever hostname
948
+ * happened to arrive first name the instance for good; that lane keeps
949
+ * requiring an explicit `APP_URL` exactly as before.
950
+ *
951
+ * It never fails a request. When no origin can be established — the request is
952
+ * plain http, KV is unbound, an operator hand-wrote the pin — `APP_URL` simply
953
+ * stays unset, which `/readyz` already reports as a hard missing binding.
954
+ * Turning that into a 500 would take the readiness probe down with it and
955
+ * replace a precise answer with a generic one.
956
+ */
957
+ function publicOriginMiddleware() {
958
+ let warned = false;
959
+ return async (
960
+ c: Context<{ Bindings: Env; Variables: Variables }>,
961
+ next: Next,
962
+ ) => {
963
+ if (configuredAppUrl(c.env) !== null) return next();
964
+ // An unrecognised lane declaration is refused at the binding boundary by
965
+ // wrapRuntimeBindings. Reaching here with one means the app was composed
966
+ // directly, and the safe reading of "not a lane I know" is "do not infer".
967
+ let lane: RuntimeLane;
968
+ try {
969
+ lane = resolveRuntimeLane(c.env.YURUCOMMU_RUNTIME_LANE);
970
+ } catch {
971
+ return next();
972
+ }
973
+ if (lane !== "portable") return next();
974
+ try {
975
+ const origin = await establishRequestPublicOrigin(c.env, c.req.raw);
976
+ c.env = { ...c.env, APP_URL: origin };
977
+ warned = false;
978
+ } catch (error) {
979
+ // Once per isolate: this condition is a property of the deployment, not
980
+ // of the request, so it would otherwise repeat on every single one.
981
+ if (!warned) {
982
+ warned = true;
983
+ log.warn("Could not establish this instance's public origin", {
984
+ event: "runtime.public_origin.unestablished",
985
+ error,
986
+ });
987
+ }
988
+ }
989
+ return next();
990
+ };
991
+ }
992
+
928
993
  export function createYurucommuBackendApp(
929
994
  options: CreateYurucommuBackendAppOptionsV1 = {},
930
995
  ): YurucommuApp {
@@ -941,6 +1006,10 @@ export function createYurucommuBackendApp(
941
1006
  }
942
1007
  }
943
1008
 
1009
+ // Before the readiness probes, because they report on APP_URL and the
1010
+ // `.well-known` discovery documents publish it. Reads no body and consults no
1011
+ // route, so it does not weaken the body-cap ordering below.
1012
+ app.use("*", publicOriginMiddleware());
944
1013
  mountReadinessRoutes(app, options.discovery);
945
1014
  // Body-size cap must run BEFORE any handler reads the body or executes
946
1015
  // expensive auth / rate-limit logic. Mounted after readiness probes so
@@ -1056,9 +1125,15 @@ export default {
1056
1125
  bindings: WorkerBindings,
1057
1126
  ): Promise<void> {
1058
1127
  const lane = resolveRuntimeLane(bindings.YURUCOMMU_RUNTIME_LANE);
1128
+ // Federation delivery signs and addresses from this instance's own actor
1129
+ // ids, and a queue invocation has no request to learn the origin from. When
1130
+ // `APP_URL` is unset and no request has pinned one yet, this THROWS: the
1131
+ // batch is retried later, after traffic has established the origin, instead
1132
+ // of being delivered under `undefined/ap/users/…` to peers that would cache
1133
+ // it. See runtime/public-origin.ts.
1059
1134
  return handleYurucommuQueueBatch(
1060
1135
  wrapRuntimeMessageBatch(batch, lane),
1061
- wrapRuntimeBindings(bindings),
1136
+ await withRequiredBackgroundPublicOrigin(wrapRuntimeBindings(bindings)),
1062
1137
  );
1063
1138
  },
1064
1139
 
@@ -53,6 +53,21 @@ export {
53
53
  wrapRuntimeBindings,
54
54
  wrapRuntimeMessageBatch,
55
55
  } from "./runtime/lane.ts";
56
+ // The public origin: `APP_URL` when the deployment could carry one, and the
57
+ // origin one request established when only the Host knew it. A product that
58
+ // composes its own Worker entry uses these for the handlers the core default
59
+ // export does not own.
60
+ export {
61
+ CANONICAL_ORIGIN_KV_KEY,
62
+ PublicOriginError,
63
+ canonicalPublicOrigin,
64
+ configuredAppUrl,
65
+ establishRequestPublicOrigin,
66
+ peekObservedPublicOrigin,
67
+ requireBackgroundPublicOrigin,
68
+ resetObservedPublicOrigin,
69
+ withRequiredBackgroundPublicOrigin,
70
+ } from "./runtime/public-origin.ts";
56
71
  export {
57
72
  EDGE_KV_MAX_EXPIRATION_TTL_SECONDS,
58
73
  EDGE_KV_MIN_EXPIRATION_TTL_SECONDS,
@@ -0,0 +1,263 @@
1
+ /**
2
+ * The one absolute origin this instance is: `APP_URL`, or the one a request
3
+ * established when the Host — not the deployer — chose it.
4
+ *
5
+ * Every federated identity this app mints is absolute. Actor ids, activity and
6
+ * object ids, `inbox` / `outbox` / `followers` collections, the OIDC
7
+ * `redirect_uri`, notification links, and the `.well-known` discovery documents
8
+ * are all `${APP_URL}/…`, and a wrong one is not a broken page — it is a
9
+ * permanent, federated wrong answer that remote servers have already cached.
10
+ *
11
+ * `APP_URL` is a plain variable, and on a wrapper host it cannot always be one.
12
+ * A Takoform `WorkerEndpoint` allocates the Worker's public origin AFTER the
13
+ * `WorkerVersion` that would have carried the variable is already immutable, so
14
+ * the deployer does not know the value at apply time and there is no second
15
+ * apply that could inject it. The origin exists, but only the Host knows it,
16
+ * and the only place it is ever spoken is on the requests the Host routes here.
17
+ *
18
+ * So on the `portable` lane an unset `APP_URL` is answered by OBSERVING one
19
+ * request and PINNING what it observed:
20
+ *
21
+ * 1. `APP_URL` is authoritative whenever it is set. It is used exactly as the
22
+ * operator wrote it and is never validated, cached, or persisted here —
23
+ * an operator who sets it has already decided, and this module has no
24
+ * standing to refuse a value the previous release accepted.
25
+ * 2. Otherwise the origin PINNED IN KV wins, for every request and for
26
+ * background work alike. First writer wins: once a value is stored, no
27
+ * later request replaces it, whatever `Host` that request carried.
28
+ * 3. Otherwise a request may establish it, from the request URL's own origin
29
+ * and from nothing else.
30
+ * 4. Otherwise there is no origin, and background work refuses rather than
31
+ * minting `undefined/ap/users/alice`.
32
+ *
33
+ * WHAT IS TRUSTED. The request URL as the runtime delivers it, and only that.
34
+ * Not `X-Forwarded-Host`, not `X-Forwarded-Proto`, not `Host` read out of the
35
+ * headers — nothing a client can write. Both wrapper hosts route by hostname
36
+ * and deliver the request they received on the Worker's own public endpoint:
37
+ * Takoserver's managed Workers-for-Platforms gateway looks up a host route for
38
+ * `new URL(request.url).hostname` and dispatches the SAME `Request` object, and
39
+ * the self-host workerd router picks a service from a table keyed by hostname
40
+ * and forwards unchanged. A hostname nobody published for this Worker is a 404
41
+ * before any of this code runs, so the origin on the request is one the Host
42
+ * assigned — which is exactly the value that could not be delivered as a var.
43
+ *
44
+ * WHY HTTPS. A public fediverse origin is https, and Takoserver's own
45
+ * `WorkerEndpoint` can only ever assign an https origin. Requiring it here
46
+ * means an http request cannot pin an origin that would then sign deliveries
47
+ * and mint actor ids. Loopback http is the one exception, because `localhost`
48
+ * is not routable and is the origin a developer actually serves on.
49
+ *
50
+ * A wrapper host that terminates TLS in FRONT of workerd and speaks plain http
51
+ * to it therefore establishes nothing: `request.url` is `http://…` and the
52
+ * derivation refuses. That deployment must set `APP_URL`, which it can, because
53
+ * an operator who terminates TLS chose the hostname themselves. Refusing is the
54
+ * point — the alternative is trusting a forwarded-proto header that the same
55
+ * proxy may or may not be the only writer of.
56
+ */
57
+
58
+ import type { Env, EnvVars } from "../types.ts";
59
+ import type { IKeyValueStore } from "./types.ts";
60
+
61
+ /**
62
+ * Where the observed origin is pinned.
63
+ *
64
+ * The key is shared with the origin pin Yurucommu's own generated Worker entry
65
+ * writes, so a deployment that pinned an origin under the product's
66
+ * implementation keeps it when the product delegates to this one.
67
+ */
68
+ export const CANONICAL_ORIGIN_KV_KEY =
69
+ "__yurucommu/runtime/canonical-origin/v1";
70
+
71
+ /** No usable public origin, or a candidate that may not become one. */
72
+ export class PublicOriginError extends Error {
73
+ constructor(message: string) {
74
+ super(message);
75
+ this.name = "PublicOriginError";
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Hostnames whose http origin is still trustworthy, because they are not
81
+ * routable off the machine. `*.localhost` is included: RFC 6761 reserves the
82
+ * whole tree for loopback, and a self-host Worker endpoint on a local Takoserver
83
+ * is `<script>.localhost`.
84
+ */
85
+ function isLoopbackHostname(hostname: string): boolean {
86
+ return (
87
+ hostname === "localhost" ||
88
+ hostname === "127.0.0.1" ||
89
+ hostname === "[::1]" ||
90
+ hostname.endsWith(".localhost")
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Reduce a candidate to a bare origin, or refuse it.
96
+ *
97
+ * Refuses anything that is not just an origin — a path, a query, a fragment,
98
+ * embedded credentials — because the value is concatenated with `/ap/users/…`
99
+ * at hundreds of call sites and a stray path would silently produce a second,
100
+ * parallel set of actor ids.
101
+ */
102
+ export function canonicalPublicOrigin(value: string): string {
103
+ let url: URL;
104
+ try {
105
+ url = new URL(value);
106
+ } catch {
107
+ throw new PublicOriginError(
108
+ `"${value}" is not a URL and cannot be this instance's public origin.`,
109
+ );
110
+ }
111
+ if (
112
+ url.username !== "" ||
113
+ url.password !== "" ||
114
+ url.search !== "" ||
115
+ url.hash !== "" ||
116
+ url.pathname !== "/"
117
+ ) {
118
+ throw new PublicOriginError(
119
+ `"${value}" is not a bare origin; this instance's public origin must ` +
120
+ `carry no path, query, fragment, or credentials.`,
121
+ );
122
+ }
123
+ if (
124
+ url.protocol !== "https:" &&
125
+ !(url.protocol === "http:" && isLoopbackHostname(url.hostname))
126
+ ) {
127
+ throw new PublicOriginError(
128
+ `"${value}" is not an https origin. A public origin observed from a ` +
129
+ `request must be https (loopback http is the only exception); set ` +
130
+ `APP_URL explicitly when this Worker is served over plain http.`,
131
+ );
132
+ }
133
+ return url.origin;
134
+ }
135
+
136
+ /** `APP_URL` exactly as the operator set it, or null when it is not set. */
137
+ export function configuredAppUrl(env: Partial<EnvVars>): string | null {
138
+ const raw = typeof env.APP_URL === "string" ? env.APP_URL.trim() : "";
139
+ return raw.length > 0 ? raw : null;
140
+ }
141
+
142
+ /**
143
+ * The origin this isolate has already established.
144
+ *
145
+ * Cached because the alternative is a KV read on the hot path of every single
146
+ * request, and because the value cannot legitimately change: first writer wins,
147
+ * so a second read can only ever return what the first one did. An operator who
148
+ * deliberately re-pins a different origin (see {@link resetObservedPublicOrigin})
149
+ * is served the new value by isolates started after the change.
150
+ */
151
+ let observedPublicOrigin: string | null = null;
152
+
153
+ /** Forget this isolate's observation. Tests, and an operator-driven re-pin. */
154
+ export function resetObservedPublicOrigin(): void {
155
+ observedPublicOrigin = null;
156
+ }
157
+
158
+ /** What this isolate has observed so far, without touching KV. */
159
+ export function peekObservedPublicOrigin(): string | null {
160
+ return observedPublicOrigin;
161
+ }
162
+
163
+ type PublicOriginEnv = Partial<EnvVars> & { KV?: IKeyValueStore };
164
+
165
+ function requireKv(env: PublicOriginEnv): IKeyValueStore {
166
+ if (!env.KV) {
167
+ throw new PublicOriginError(
168
+ "KV is not bound, so this instance's public origin can be neither read " +
169
+ "nor pinned. Bind KV, or set APP_URL.",
170
+ );
171
+ }
172
+ return env.KV;
173
+ }
174
+
175
+ async function readPinnedOrigin(kv: IKeyValueStore): Promise<string | null> {
176
+ const stored = await kv.get(CANONICAL_ORIGIN_KV_KEY);
177
+ if (stored === null) return null;
178
+ // A stored value that no longer canonicalizes is a refusal, never a silent
179
+ // fallback to the current request: it means somebody wrote the key by hand.
180
+ return canonicalPublicOrigin(stored);
181
+ }
182
+
183
+ /**
184
+ * Establish this instance's public origin from one request, once.
185
+ *
186
+ * CONSISTENCY. The pin lives in KV, the one store both lanes always have (`DB`
187
+ * is equally present, but the origin is needed by the readiness probe and by
188
+ * queue work that must not open a transaction to learn its own name). KV is
189
+ * eventually consistent and has no compare-and-swap, so "first writer wins" is
190
+ * enforced by reading before writing and then READING BACK: an isolate that
191
+ * finds a different origin on the read-back lost the race and refuses this
192
+ * request rather than serving two identities. The next request reads the
193
+ * winner's value through the ordinary stored-value path. A read-back that has
194
+ * not converged yet (null) is treated as our own write, because we wrote it.
195
+ */
196
+ export async function establishRequestPublicOrigin(
197
+ env: PublicOriginEnv,
198
+ request: Request,
199
+ ): Promise<string> {
200
+ if (observedPublicOrigin !== null) return observedPublicOrigin;
201
+
202
+ const kv = requireKv(env);
203
+ const pinned = await readPinnedOrigin(kv);
204
+ if (pinned !== null) {
205
+ observedPublicOrigin = pinned;
206
+ return pinned;
207
+ }
208
+
209
+ const requestOrigin = canonicalPublicOrigin(new URL(request.url).origin);
210
+ await kv.put(CANONICAL_ORIGIN_KV_KEY, requestOrigin);
211
+ const readback = await kv.get(CANONICAL_ORIGIN_KV_KEY);
212
+ if (readback !== null && canonicalPublicOrigin(readback) !== requestOrigin) {
213
+ throw new PublicOriginError(
214
+ `this instance's public origin was concurrently pinned to ` +
215
+ `"${readback}" while this request was establishing ` +
216
+ `"${requestOrigin}". The pinned origin stands; retry.`,
217
+ );
218
+ }
219
+ observedPublicOrigin = requestOrigin;
220
+ return requestOrigin;
221
+ }
222
+
223
+ /**
224
+ * The public origin for work that has no request to read it from.
225
+ *
226
+ * Queue consumers sign federation deliveries and address them from this
227
+ * instance's actor ids; there is no request in scope and nothing to derive one
228
+ * from. `APP_URL` first, then the pinned origin, then a refusal — never a
229
+ * guess, and never `undefined` concatenated into an actor id.
230
+ */
231
+ export async function requireBackgroundPublicOrigin(
232
+ env: PublicOriginEnv,
233
+ ): Promise<string> {
234
+ const configured = configuredAppUrl(env);
235
+ if (configured !== null) return configured;
236
+ if (observedPublicOrigin !== null) return observedPublicOrigin;
237
+
238
+ const pinned = await readPinnedOrigin(requireKv(env));
239
+ if (pinned === null) {
240
+ throw new PublicOriginError(
241
+ "this instance's public origin has not been observed yet: APP_URL is " +
242
+ "unset and no request has pinned an origin. Serve one request on the " +
243
+ "Worker's public endpoint before background delivery can address " +
244
+ "anything.",
245
+ );
246
+ }
247
+ observedPublicOrigin = pinned;
248
+ return pinned;
249
+ }
250
+
251
+ /**
252
+ * The env background work should run with: `APP_URL` present, or a refusal.
253
+ *
254
+ * Returned as a copy rather than by mutating the caller's bindings, so the same
255
+ * `env` may be handed to several handlers without one of them rewriting what
256
+ * the others read.
257
+ */
258
+ export async function withRequiredBackgroundPublicOrigin(
259
+ env: Env,
260
+ ): Promise<Env> {
261
+ if (configuredAppUrl(env) !== null) return env;
262
+ return { ...env, APP_URL: await requireBackgroundPublicOrigin(env) };
263
+ }