@syncular/server-workers 0.31.0 → 0.32.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/dist/index.d.ts CHANGED
@@ -26,7 +26,7 @@
26
26
  * WebSockets are optional, the per-partition push queue is not.
27
27
  */
28
28
  import { type D1Database, D1ServerStorage, type StoredCommit, type SyncServerConfig } from '@syncular/server';
29
- import { type SyncularHonoOptions } from '@syncular/server-hono';
29
+ import { type SyncularAdminGuards, type SyncularHonoOptions } from '@syncular/server-hono';
30
30
  import { type RealtimeUpgradeIdentity } from './realtime-do.js';
31
31
  export { type D1Database, D1ServerStorage } from '@syncular/server';
32
32
  export * from './realtime-do.js';
@@ -80,6 +80,20 @@ export interface WorkersCoordinatorOptions {
80
80
  readonly namespace: DurableObjectNamespaceLike;
81
81
  }
82
82
  export type WorkersCoordinatorFactory<Env = unknown> = (env: Env, ctx: ExecutionContextLike) => WorkersCoordinatorOptions | Promise<WorkersCoordinatorOptions>;
83
+ /**
84
+ * The admin console for `createWorkersFetchHandler`. The host guards run in
85
+ * the Worker. With a coordinator (or realtime) namespace, every
86
+ * partition-scoped admin request then goes to the partition's Durable
87
+ * Object: its event ring sees that partition's sync rounds, and actions
88
+ * share its FIFO. The page and the fleet view (`GET <path>/partitions`) are
89
+ * served by the Worker. Without a namespace the Worker serves everything
90
+ * and has no event ring.
91
+ */
92
+ export interface WorkersAdminOptions extends SyncularAdminGuards {
93
+ /** The mount path; default `/admin`. */
94
+ readonly path?: string;
95
+ }
96
+ export type WorkersAdminFactory<Env = unknown> = (env: Env, ctx: ExecutionContextLike) => WorkersAdminOptions | Promise<WorkersAdminOptions>;
83
97
  export interface WorkersFetchHandlerOptions<Env = unknown> {
84
98
  /** Build the HTTP handler config + auth per request (see the type doc). */
85
99
  readonly config: WorkersConfigFactory<Env>;
@@ -94,6 +108,8 @@ export interface WorkersFetchHandlerOptions<Env = unknown> {
94
108
  * (still fully conformant — clients sync over `POST /sync`).
95
109
  */
96
110
  readonly realtime?: WorkersRealtimeFactory<Env>;
111
+ /** Mount the admin console (see `WorkersAdminOptions`). */
112
+ readonly admin?: WorkersAdminFactory<Env>;
97
113
  }
98
114
  /**
99
115
  * Wrap a config factory (or a `{ config, realtime }` options object) into a
package/dist/index.js CHANGED
@@ -25,9 +25,9 @@
25
25
  * `/sync`. An HTTP-only D1 deployment uses the `coordinator` option instead:
26
26
  * WebSockets are optional, the per-partition push queue is not.
27
27
  */
28
- import { D1ServerStorage, errorBody, SSP2_CONTENT_TYPE, SyncError, } from '@syncular/server';
29
- import { createSyncularHono, } from '@syncular/server-hono';
30
- import { REALTIME_DO_UPGRADE_PATH, REALTIME_DO_WAKE_PATH, SYNC_DO_REQUEST_PATH, writeIdentityHeaders, writeRequestIdentityHeaders, } from './realtime-do.js';
28
+ import { D1ServerStorage, errorBody, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, } from '@syncular/server';
29
+ import { createSyncularAdminRoutes, createSyncularHono, } from '@syncular/server-hono';
30
+ import { adminRequestForDurableObject, REALTIME_DO_UPGRADE_PATH, REALTIME_DO_WAKE_PATH, SYNC_DO_REQUEST_PATH, writeIdentityHeaders, writeRequestIdentityHeaders, } from './realtime-do.js';
31
31
  export { D1ServerStorage } from '@syncular/server';
32
32
  export * from './realtime-do.js';
33
33
  /**
@@ -96,6 +96,35 @@ export function createWorkersFetchHandler(factoryOrOptions) {
96
96
  }
97
97
  return forwardSyncRequest(request, coordinator.namespace, auth);
98
98
  }
99
+ if (options.admin !== undefined) {
100
+ const admin = await options.admin(env, ctx);
101
+ const path = admin.path ?? '/admin';
102
+ const url = new URL(request.url);
103
+ if (url.pathname === path || url.pathname.startsWith(`${path}/`)) {
104
+ const routePath = url.pathname.slice(path.length);
105
+ const routes = createSyncularAdminRoutes(SyncularAdmin.fromConfig(honoOptions.config), {
106
+ authorize: admin.authorize,
107
+ ...(admin.authorizeActions !== undefined
108
+ ? { authorizeActions: admin.authorizeActions }
109
+ : {}),
110
+ ...(honoOptions.config.onError !== undefined
111
+ ? { onError: honoOptions.config.onError }
112
+ : {}),
113
+ ...(honoOptions.config.mapError !== undefined
114
+ ? { mapError: honoOptions.config.mapError }
115
+ : {}),
116
+ ...(coordinator !== undefined
117
+ ? {
118
+ forward: (forwarded, target) => coordinator.namespace
119
+ .get(coordinator.namespace.idFromName(target.partition))
120
+ .fetch(adminRequestForDurableObject(forwarded, routePath, target)),
121
+ }
122
+ : {}),
123
+ });
124
+ url.pathname = routePath === '' ? '/' : routePath;
125
+ return routes.fetch(new Request(url, request));
126
+ }
127
+ }
99
128
  const app = createSyncularHono(honoOptions);
100
129
  return app.fetch(request);
101
130
  };
@@ -89,7 +89,7 @@ export type WebSocketPairLike = {
89
89
  * the class constructor's second arg. `DB` is the D1 binding (the same one the
90
90
  * outer Worker config uses); `configFactory` builds the hub config from `env`.
91
91
  */
92
- export type RealtimeDOConfig = {
92
+ export type RealtimeDOConfig = ({
93
93
  /**
94
94
  * Preferred: build the complete canonical sync config around the DO's
95
95
  * coordinated D1 storage. Reuse this factory for the outer HTTP adapter
@@ -104,6 +104,15 @@ export type RealtimeDOConfig = {
104
104
  */
105
105
  hubConfig(storage: D1ServerStorage): RealtimeHubConfigInput;
106
106
  readonly syncConfig?: never;
107
+ }) & {
108
+ /**
109
+ * Events the admin console keeps for this partition; default 1000. The DO
110
+ * composes its event ring into the sync config's `events` and serves the
111
+ * admin routes the Worker forwards (`WorkersFetchHandlerOptions.admin`),
112
+ * so the event tail, metrics, failures and client drill-down see this
113
+ * partition's rounds.
114
+ */
115
+ readonly adminRingCapacity?: number;
107
116
  };
108
117
  /**
109
118
  * The subset of `RealtimeHubConfig` the DO host supplies (storage is wired by
@@ -120,6 +129,8 @@ export interface RealtimeUpgradeIdentity {
120
129
  export declare const REALTIME_DO_WAKE_PATH = "/__syncular_realtime/wake";
121
130
  export declare const REALTIME_DO_UPGRADE_PATH = "/__syncular_realtime/upgrade";
122
131
  export declare const SYNC_DO_REQUEST_PATH = "/__syncular_realtime/sync";
132
+ /** Prefix of forwarded admin routes; the admin route path follows it. */
133
+ export declare const ADMIN_DO_PATH = "/__syncular_realtime/admin";
123
134
  /**
124
135
  * The base `SyncularRealtimeDO`. A host subclasses (or instantiates) it with a
125
136
  * `RealtimeDOConfig`. The class is platform-shaped: `state.acceptWebSocket` +
@@ -166,6 +177,11 @@ export declare class SyncularRealtimeHost {
166
177
  }
167
178
  /** Inject a `WebSocketPair` implementation (hermetic tests). */
168
179
  export declare function setWebSocketPair(impl: (new () => WebSocketPairLike) | undefined): void;
180
+ /** Address a Worker-authorized admin request to the DO (Worker side). */
181
+ export declare function adminRequestForDurableObject(request: Request, routePath: string, target: {
182
+ readonly partition: string;
183
+ readonly actions: boolean;
184
+ }): Request;
169
185
  export declare function writeRequestIdentityHeaders(headers: Headers, identity: {
170
186
  readonly partition: string;
171
187
  readonly actorId: string;
@@ -67,7 +67,8 @@
67
67
  * partition serialization may call `/__wake` after its own commit so sockets
68
68
  * re-pull. See `durableObjectRealtimeNotifier` for that caller side.
69
69
  */
70
- import { adapterSyncError, createRealtimeHub, D1ServerStorage, errorBody, handleSyncRequest, pruneCommitLog, SSP2_CONTENT_TYPE, SyncError, } from '@syncular/server';
70
+ import { adapterSyncError, composeEvents, createRealtimeHub, D1ServerStorage, errorBody, handleSyncRequest, pruneCommitLog, RingBufferEvents, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, } from '@syncular/server';
71
+ import { createSyncularAdminRoutes } from '@syncular/server-hono';
71
72
  function isAttachment(value) {
72
73
  return (typeof value === 'object' &&
73
74
  value !== null &&
@@ -79,6 +80,8 @@ function isAttachment(value) {
79
80
  export const REALTIME_DO_WAKE_PATH = '/__syncular_realtime/wake';
80
81
  export const REALTIME_DO_UPGRADE_PATH = '/__syncular_realtime/upgrade';
81
82
  export const SYNC_DO_REQUEST_PATH = '/__syncular_realtime/sync';
83
+ /** Prefix of forwarded admin routes; the admin route path follows it. */
84
+ export const ADMIN_DO_PATH = '/__syncular_realtime/admin';
82
85
  /**
83
86
  * The base `SyncularRealtimeDO`. A host subclasses (or instantiates) it with a
84
87
  * `RealtimeDOConfig`. The class is platform-shaped: `state.acceptWebSocket` +
@@ -107,6 +110,7 @@ export class SyncularRealtimeHost {
107
110
  #storage;
108
111
  #config;
109
112
  #hub;
113
+ #admin;
110
114
  /** Live sessions, keyed by their socket. Empty after a hibernation wake;
111
115
  * lazily rehydrated on the first message per socket (see the class doc). */
112
116
  #sessions = new Map();
@@ -135,7 +139,18 @@ export class SyncularRealtimeHost {
135
139
  if (config.storage !== this.#storage) {
136
140
  throw new Error('RealtimeDOConfig.syncConfig must use the coordinated storage argument');
137
141
  }
138
- this.#hub = createRealtimeHub(config);
142
+ const ring = new RingBufferEvents(this.#config.adminRingCapacity !== undefined
143
+ ? { capacity: this.#config.adminRingCapacity }
144
+ : undefined);
145
+ const withRing = {
146
+ ...config,
147
+ events: config.events !== undefined
148
+ ? composeEvents(ring, config.events)
149
+ : ring,
150
+ };
151
+ const hub = createRealtimeHub(withRing);
152
+ this.#hub = hub;
153
+ this.#admin = SyncularAdmin.fromConfig({ ...withRing, realtime: hub }, { ring });
139
154
  }
140
155
  return this.#hub;
141
156
  }
@@ -156,6 +171,9 @@ export class SyncularRealtimeHost {
156
171
  if (url.pathname === REALTIME_DO_UPGRADE_PATH) {
157
172
  return this.#handleUpgrade(request);
158
173
  }
174
+ if (url.pathname.startsWith(`${ADMIN_DO_PATH}/`)) {
175
+ return this.#handleAdmin(request, url);
176
+ }
159
177
  return new Response('not found', { status: 404 });
160
178
  }
161
179
  /** Trusted maintenance shares the partition FIFO with HTTP/socket writes. */
@@ -197,6 +215,34 @@ export class SyncularRealtimeHost {
197
215
  return Response.json(errorBody(sync), { status: sync.httpStatus });
198
216
  }
199
217
  }
218
+ /**
219
+ * A Worker-authorized admin request: the Worker ran the host guards and
220
+ * names the partition and whether actions are granted in headers.
221
+ * Actions share the partition FIFO with sync rounds.
222
+ */
223
+ async #handleAdmin(request, url) {
224
+ this.#getHub();
225
+ const partition = request.headers.get(REALTIME_ID_HEADER.partition);
226
+ if (this.#admin === undefined || partition === null || partition === '') {
227
+ const error = new SyncError('sync.invalid_request', 'forwarded admin request names no partition');
228
+ return Response.json(errorBody(error), { status: error.httpStatus });
229
+ }
230
+ const routes = createSyncularAdminRoutes(this.#admin, {
231
+ authorize: () => true,
232
+ ...(request.headers.get(ADMIN_ACTIONS_HEADER) === '1'
233
+ ? { authorizeActions: () => true }
234
+ : {}),
235
+ });
236
+ url.pathname = url.pathname.slice(ADMIN_DO_PATH.length);
237
+ url.searchParams.set('partition', partition);
238
+ const routed = new Request(url, request);
239
+ if (request.method !== 'POST')
240
+ return routes.fetch(routed);
241
+ return this.#serializePartition(async () => {
242
+ await this.#storage.migrate();
243
+ return routes.fetch(routed);
244
+ });
245
+ }
200
246
  /** §8.3 wake: an external coordinated command landed; re-pull the delta. */
201
247
  async #handleWake(request) {
202
248
  const body = (await request.json().catch(() => null));
@@ -378,6 +424,18 @@ const REALTIME_ID_HEADER = {
378
424
  actorId: 'x-syncular-actor',
379
425
  clientId: 'x-syncular-client',
380
426
  };
427
+ const ADMIN_ACTIONS_HEADER = 'x-syncular-admin-actions';
428
+ /** Address a Worker-authorized admin request to the DO (Worker side). */
429
+ export function adminRequestForDurableObject(request, routePath, target) {
430
+ const source = new URL(request.url);
431
+ const forwarded = new Request(new URL(`${ADMIN_DO_PATH}${routePath}${source.search}`, request.url), request);
432
+ forwarded.headers.set(REALTIME_ID_HEADER.partition, target.partition);
433
+ if (target.actions)
434
+ forwarded.headers.set(ADMIN_ACTIONS_HEADER, '1');
435
+ else
436
+ forwarded.headers.delete(ADMIN_ACTIONS_HEADER);
437
+ return forwarded;
438
+ }
381
439
  export function writeRequestIdentityHeaders(headers, identity) {
382
440
  headers.set(REALTIME_ID_HEADER.partition, identity.partition);
383
441
  headers.set(REALTIME_ID_HEADER.actorId, identity.actorId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/server-workers",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "Cloudflare Workers adapter for the Syncular sync server",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -45,11 +45,11 @@
45
45
  "!dist/**/*.test.d.ts"
46
46
  ],
47
47
  "dependencies": {
48
- "@syncular/server": "0.31.0",
49
- "@syncular/server-hono": "0.31.0"
48
+ "@syncular/server": "0.32.0",
49
+ "@syncular/server-hono": "0.32.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@syncular/core": "0.31.0",
52
+ "@syncular/core": "0.32.0",
53
53
  "miniflare": "4.20260701.0"
54
54
  }
55
55
  }
package/src/index.ts CHANGED
@@ -32,13 +32,17 @@ import {
32
32
  SSP2_CONTENT_TYPE,
33
33
  type StoredCommit,
34
34
  SyncError,
35
+ SyncularAdmin,
35
36
  type SyncServerConfig,
36
37
  } from '@syncular/server';
37
38
  import {
39
+ createSyncularAdminRoutes,
38
40
  createSyncularHono,
41
+ type SyncularAdminGuards,
39
42
  type SyncularHonoOptions,
40
43
  } from '@syncular/server-hono';
41
44
  import {
45
+ adminRequestForDurableObject,
42
46
  REALTIME_DO_UPGRADE_PATH,
43
47
  REALTIME_DO_WAKE_PATH,
44
48
  type RealtimeUpgradeIdentity,
@@ -125,6 +129,25 @@ export type WorkersCoordinatorFactory<Env = unknown> = (
125
129
  ctx: ExecutionContextLike,
126
130
  ) => WorkersCoordinatorOptions | Promise<WorkersCoordinatorOptions>;
127
131
 
132
+ /**
133
+ * The admin console for `createWorkersFetchHandler`. The host guards run in
134
+ * the Worker. With a coordinator (or realtime) namespace, every
135
+ * partition-scoped admin request then goes to the partition's Durable
136
+ * Object: its event ring sees that partition's sync rounds, and actions
137
+ * share its FIFO. The page and the fleet view (`GET <path>/partitions`) are
138
+ * served by the Worker. Without a namespace the Worker serves everything
139
+ * and has no event ring.
140
+ */
141
+ export interface WorkersAdminOptions extends SyncularAdminGuards {
142
+ /** The mount path; default `/admin`. */
143
+ readonly path?: string;
144
+ }
145
+
146
+ export type WorkersAdminFactory<Env = unknown> = (
147
+ env: Env,
148
+ ctx: ExecutionContextLike,
149
+ ) => WorkersAdminOptions | Promise<WorkersAdminOptions>;
150
+
128
151
  export interface WorkersFetchHandlerOptions<Env = unknown> {
129
152
  /** Build the HTTP handler config + auth per request (see the type doc). */
130
153
  readonly config: WorkersConfigFactory<Env>;
@@ -139,6 +162,8 @@ export interface WorkersFetchHandlerOptions<Env = unknown> {
139
162
  * (still fully conformant — clients sync over `POST /sync`).
140
163
  */
141
164
  readonly realtime?: WorkersRealtimeFactory<Env>;
165
+ /** Mount the admin console (see `WorkersAdminOptions`). */
166
+ readonly admin?: WorkersAdminFactory<Env>;
142
167
  }
143
168
 
144
169
  /**
@@ -214,6 +239,45 @@ export function createWorkersFetchHandler<Env = unknown>(
214
239
  }
215
240
  return forwardSyncRequest(request, coordinator.namespace, auth);
216
241
  }
242
+ if (options.admin !== undefined) {
243
+ const admin = await options.admin(env, ctx);
244
+ const path = admin.path ?? '/admin';
245
+ const url = new URL(request.url);
246
+ if (url.pathname === path || url.pathname.startsWith(`${path}/`)) {
247
+ const routePath = url.pathname.slice(path.length);
248
+ const routes = createSyncularAdminRoutes(
249
+ SyncularAdmin.fromConfig(honoOptions.config),
250
+ {
251
+ authorize: admin.authorize,
252
+ ...(admin.authorizeActions !== undefined
253
+ ? { authorizeActions: admin.authorizeActions }
254
+ : {}),
255
+ ...(honoOptions.config.onError !== undefined
256
+ ? { onError: honoOptions.config.onError }
257
+ : {}),
258
+ ...(honoOptions.config.mapError !== undefined
259
+ ? { mapError: honoOptions.config.mapError }
260
+ : {}),
261
+ ...(coordinator !== undefined
262
+ ? {
263
+ forward: (forwarded, target) =>
264
+ coordinator.namespace
265
+ .get(coordinator.namespace.idFromName(target.partition))
266
+ .fetch(
267
+ adminRequestForDurableObject(
268
+ forwarded,
269
+ routePath,
270
+ target,
271
+ ),
272
+ ),
273
+ }
274
+ : {}),
275
+ },
276
+ );
277
+ url.pathname = routePath === '' ? '/' : routePath;
278
+ return routes.fetch(new Request(url, request));
279
+ }
280
+ }
217
281
  const app = createSyncularHono(honoOptions);
218
282
  return app.fetch(request);
219
283
  };
@@ -69,6 +69,7 @@
69
69
  */
70
70
  import {
71
71
  adapterSyncError,
72
+ composeEvents,
72
73
  createRealtimeHub,
73
74
  D1ServerStorage,
74
75
  errorBody,
@@ -78,9 +79,12 @@ import {
78
79
  type RealtimeHub,
79
80
  type RealtimeHubConfig,
80
81
  type RealtimeSession,
82
+ RingBufferEvents,
81
83
  SSP2_CONTENT_TYPE,
82
84
  SyncError,
85
+ SyncularAdmin,
83
86
  } from '@syncular/server';
87
+ import { createSyncularAdminRoutes } from '@syncular/server-hono';
84
88
 
85
89
  // -- The Durable Object platform surface this class uses (structural) -------
86
90
  // Declared locally so the package takes no `@cloudflare/workers-types`
@@ -108,7 +112,7 @@ export type WebSocketPairLike = { 0: WebSocketLike; 1: WebSocketLike };
108
112
  * the class constructor's second arg. `DB` is the D1 binding (the same one the
109
113
  * outer Worker config uses); `configFactory` builds the hub config from `env`.
110
114
  */
111
- export type RealtimeDOConfig =
115
+ export type RealtimeDOConfig = (
112
116
  | {
113
117
  /**
114
118
  * Preferred: build the complete canonical sync config around the DO's
@@ -125,7 +129,17 @@ export type RealtimeDOConfig =
125
129
  */
126
130
  hubConfig(storage: D1ServerStorage): RealtimeHubConfigInput;
127
131
  readonly syncConfig?: never;
128
- };
132
+ }
133
+ ) & {
134
+ /**
135
+ * Events the admin console keeps for this partition; default 1000. The DO
136
+ * composes its event ring into the sync config's `events` and serves the
137
+ * admin routes the Worker forwards (`WorkersFetchHandlerOptions.admin`),
138
+ * so the event tail, metrics, failures and client drill-down see this
139
+ * partition's rounds.
140
+ */
141
+ readonly adminRingCapacity?: number;
142
+ };
129
143
 
130
144
  /**
131
145
  * The subset of `RealtimeHubConfig` the DO host supplies (storage is wired by
@@ -161,6 +175,8 @@ export interface RealtimeUpgradeIdentity {
161
175
  export const REALTIME_DO_WAKE_PATH = '/__syncular_realtime/wake';
162
176
  export const REALTIME_DO_UPGRADE_PATH = '/__syncular_realtime/upgrade';
163
177
  export const SYNC_DO_REQUEST_PATH = '/__syncular_realtime/sync';
178
+ /** Prefix of forwarded admin routes; the admin route path follows it. */
179
+ export const ADMIN_DO_PATH = '/__syncular_realtime/admin';
164
180
 
165
181
  /**
166
182
  * The base `SyncularRealtimeDO`. A host subclasses (or instantiates) it with a
@@ -190,6 +206,7 @@ export class SyncularRealtimeHost {
190
206
  readonly #storage: D1ServerStorage;
191
207
  readonly #config: RealtimeDOConfig;
192
208
  #hub: RealtimeHub | undefined;
209
+ #admin: SyncularAdmin | undefined;
193
210
  /** Live sessions, keyed by their socket. Empty after a hibernation wake;
194
211
  * lazily rehydrated on the first message per socket (see the class doc). */
195
212
  readonly #sessions = new Map<WebSocketLike, RealtimeSession>();
@@ -227,7 +244,24 @@ export class SyncularRealtimeHost {
227
244
  'RealtimeDOConfig.syncConfig must use the coordinated storage argument',
228
245
  );
229
246
  }
230
- this.#hub = createRealtimeHub(config);
247
+ const ring = new RingBufferEvents(
248
+ this.#config.adminRingCapacity !== undefined
249
+ ? { capacity: this.#config.adminRingCapacity }
250
+ : undefined,
251
+ );
252
+ const withRing = {
253
+ ...config,
254
+ events:
255
+ config.events !== undefined
256
+ ? composeEvents(ring, config.events)
257
+ : ring,
258
+ };
259
+ const hub = createRealtimeHub(withRing);
260
+ this.#hub = hub;
261
+ this.#admin = SyncularAdmin.fromConfig(
262
+ { ...withRing, realtime: hub },
263
+ { ring },
264
+ );
231
265
  }
232
266
  return this.#hub;
233
267
  }
@@ -249,6 +283,9 @@ export class SyncularRealtimeHost {
249
283
  if (url.pathname === REALTIME_DO_UPGRADE_PATH) {
250
284
  return this.#handleUpgrade(request);
251
285
  }
286
+ if (url.pathname.startsWith(`${ADMIN_DO_PATH}/`)) {
287
+ return this.#handleAdmin(request, url);
288
+ }
252
289
  return new Response('not found', { status: 404 });
253
290
  }
254
291
 
@@ -307,6 +344,37 @@ export class SyncularRealtimeHost {
307
344
  }
308
345
  }
309
346
 
347
+ /**
348
+ * A Worker-authorized admin request: the Worker ran the host guards and
349
+ * names the partition and whether actions are granted in headers.
350
+ * Actions share the partition FIFO with sync rounds.
351
+ */
352
+ async #handleAdmin(request: Request, url: URL): Promise<Response> {
353
+ this.#getHub();
354
+ const partition = request.headers.get(REALTIME_ID_HEADER.partition);
355
+ if (this.#admin === undefined || partition === null || partition === '') {
356
+ const error = new SyncError(
357
+ 'sync.invalid_request',
358
+ 'forwarded admin request names no partition',
359
+ );
360
+ return Response.json(errorBody(error), { status: error.httpStatus });
361
+ }
362
+ const routes = createSyncularAdminRoutes(this.#admin, {
363
+ authorize: () => true,
364
+ ...(request.headers.get(ADMIN_ACTIONS_HEADER) === '1'
365
+ ? { authorizeActions: () => true }
366
+ : {}),
367
+ });
368
+ url.pathname = url.pathname.slice(ADMIN_DO_PATH.length);
369
+ url.searchParams.set('partition', partition);
370
+ const routed = new Request(url, request);
371
+ if (request.method !== 'POST') return routes.fetch(routed);
372
+ return this.#serializePartition(async () => {
373
+ await this.#storage.migrate();
374
+ return routes.fetch(routed);
375
+ });
376
+ }
377
+
310
378
  /** §8.3 wake: an external coordinated command landed; re-pull the delta. */
311
379
  async #handleWake(request: Request): Promise<Response> {
312
380
  const body = (await request.json().catch(() => null)) as {
@@ -512,6 +580,25 @@ const REALTIME_ID_HEADER = {
512
580
  clientId: 'x-syncular-client',
513
581
  } as const;
514
582
 
583
+ const ADMIN_ACTIONS_HEADER = 'x-syncular-admin-actions';
584
+
585
+ /** Address a Worker-authorized admin request to the DO (Worker side). */
586
+ export function adminRequestForDurableObject(
587
+ request: Request,
588
+ routePath: string,
589
+ target: { readonly partition: string; readonly actions: boolean },
590
+ ): Request {
591
+ const source = new URL(request.url);
592
+ const forwarded = new Request(
593
+ new URL(`${ADMIN_DO_PATH}${routePath}${source.search}`, request.url),
594
+ request,
595
+ );
596
+ forwarded.headers.set(REALTIME_ID_HEADER.partition, target.partition);
597
+ if (target.actions) forwarded.headers.set(ADMIN_ACTIONS_HEADER, '1');
598
+ else forwarded.headers.delete(ADMIN_ACTIONS_HEADER);
599
+ return forwarded;
600
+ }
601
+
515
602
  export function writeRequestIdentityHeaders(
516
603
  headers: Headers,
517
604
  identity: { readonly partition: string; readonly actorId: string },