ras-stack 4.3.0 → 4.4.1

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 (58) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/secret.js +5 -6
  3. package/dist/auth/secret.js.map +1 -1
  4. package/dist/build/index.js +1 -3
  5. package/dist/build/index.js.map +1 -1
  6. package/dist/changesets/index.js +2 -1
  7. package/dist/changesets/index.js.map +1 -1
  8. package/dist/cli.d.ts +1 -2
  9. package/dist/cli.js +9 -3
  10. package/dist/cli.js.map +1 -1
  11. package/dist/conformance/index.d.ts +3 -11
  12. package/dist/conformance/index.js +11 -6
  13. package/dist/conformance/index.js.map +1 -1
  14. package/dist/email/index.d.ts +2 -2
  15. package/dist/email/index.js +3 -6
  16. package/dist/email/index.js.map +1 -1
  17. package/dist/posthog/react.js +36 -18
  18. package/dist/posthog/react.js.map +1 -1
  19. package/dist/posthog/server.js +13 -28
  20. package/dist/posthog/server.js.map +1 -1
  21. package/dist/preview/cloudflare.js +2 -4
  22. package/dist/preview/cloudflare.js.map +1 -1
  23. package/dist/preview/dokploy-cli.js +14 -28
  24. package/dist/preview/dokploy-cli.js.map +1 -1
  25. package/dist/preview/dokploy-preview.d.ts +3 -0
  26. package/dist/preview/dokploy-preview.js +15 -21
  27. package/dist/preview/dokploy-preview.js.map +1 -1
  28. package/dist/preview/environment.d.ts +6 -14
  29. package/dist/preview/environment.js +12 -19
  30. package/dist/preview/environment.js.map +1 -1
  31. package/dist/preview/github.d.ts +12 -5
  32. package/dist/preview/github.js +22 -22
  33. package/dist/preview/github.js.map +1 -1
  34. package/dist/realtime/environment.js +2 -1
  35. package/dist/realtime/environment.js.map +1 -1
  36. package/dist/realtime/publisher.d.ts +1 -0
  37. package/dist/realtime/publisher.js +7 -5
  38. package/dist/realtime/publisher.js.map +1 -1
  39. package/dist/runtime/dev.d.ts +2 -2
  40. package/dist/runtime/dev.js +47 -71
  41. package/dist/runtime/dev.js.map +1 -1
  42. package/dist/runtime/stack.d.ts +2 -1
  43. package/dist/runtime/stack.js +14 -40
  44. package/dist/runtime/stack.js.map +1 -1
  45. package/dist/server/canonical-host.d.ts +1 -0
  46. package/dist/server/canonical-host.js +1 -1
  47. package/dist/server/canonical-host.js.map +1 -1
  48. package/dist/spacetime/index.js +2 -1
  49. package/dist/spacetime/index.js.map +1 -1
  50. package/dist/tanstack/server.d.ts +1 -1
  51. package/dist/tanstack/server.js.map +1 -1
  52. package/package.json +1 -1
  53. package/dist/posthog/client.d.ts +0 -9
  54. package/dist/posthog/client.js +0 -34
  55. package/dist/posthog/client.js.map +0 -1
  56. package/dist/runtime/dev-cli.d.ts +0 -1
  57. package/dist/runtime/dev-cli.js +0 -11
  58. package/dist/runtime/dev-cli.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"publisher.js","sourceRoot":"","sources":["../../src/realtime/publisher.ts"],"names":[],"mappings":"AAeA,MAAM,OAAO,mBAAmB;IAUD,OAAO;IATnB,OAAO,GAAG,IAAI,GAAG,EAA8B,CAAA;IAC/C,KAAK,GAAa,EAAE,CAAA;IACpB,WAAW,GAAG,IAAI,GAAG,EAAc,CAAA;IACnC,OAAO,CAAc;IACrB,qBAAqB,CAAQ;IAC7B,kBAAkB,CAAQ;IACnC,MAAM,GAAG,CAAC,CAAA;IACV,MAAM,GAAG,KAAK,CAAA;IAEtB,YAA6B,OAAmC;uBAAnC,OAAO;QAClC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,KAAK,CAAA;QACrC,IAAI,CAAC,qBAAqB,GAAG,eAAe,CAAC,OAAO,CAAC,qBAAqB,IAAI,CAAC,EAAE,uBAAuB,CAAC,CAAA;QACzG,IAAI,CAAC,kBAAkB,GAAG,eAAe,CAAC,OAAO,CAAC,kBAAkB,IAAI,KAAK,EAAE,oBAAoB,CAAC,CAAA;IACtG,CAAC;IAED,OAAO,CAAC,OAAe,EAAE,IAAa;QACpC,IAAI,CAAC,IAAI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AE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAA;AACnG,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,6BAA6B,CAAC,CAAA;IACzG,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["export type CentrifugoPublisherOptions = {\n apiUrl: string\n apiKey: string\n fetch?: typeof fetch\n timeoutMs?: number\n retryMs?: number\n maxRetries?: number\n maxConcurrentChannels?: number\n maxPendingChannels?: number\n onError: (error: unknown, channel: string) => void\n onRetry?: (error: unknown, channel: string) => void\n}\n\ntype PendingPublication = { dirty: boolean; data: unknown; running: boolean }\n\nexport class CentrifugoPublisher {\n private readonly pending = new Map<string, PendingPublication>()\n private readonly queue: string[] = []\n private readonly idleWaiters = new Set<() => void>()\n private readonly request: typeof fetch\n private readonly maxConcurrentChannels: number\n private readonly maxPendingChannels: number\n private active = 0\n private closed = false\n\n constructor(private readonly options: CentrifugoPublisherOptions) {\n this.request = options.fetch ?? fetch\n this.maxConcurrentChannels = positiveInteger(options.maxConcurrentChannels ?? 8, 'maxConcurrentChannels')\n this.maxPendingChannels = positiveInteger(options.maxPendingChannels ?? 1_024, 'maxPendingChannels')\n }\n\n publish(channel: string, data: unknown) {\n if (!this.options.apiUrl) return false\n if (this.closed) {\n this.reportError(new Error('Realtime publisher is closed'), channel)\n return false\n }\n const pending = this.pending.get(channel)\n if (pending) {\n pending.dirty = true\n pending.data = data\n return true\n }\n if (this.pending.size >= this.maxPendingChannels) {\n this.reportError(new Error('Realtime publisher queue is full'), channel)\n return false\n }\n\n const state = { dirty: true, data, running: false }\n this.pending.set(channel, state)\n this.queue.push(channel)\n this.pump()\n return true\n }\n\n idle() {\n if (this.isIdle()) return Promise.resolve()\n return new Promise<void>((resolve) => this.idleWaiters.add(resolve))\n }\n\n async close(options: { signal?: AbortSignal } = {}) {\n this.closed = true\n const idle = this.idle()\n if (!options.signal) return idle\n await abortable(idle, options.signal)\n }\n\n private pump() {\n while (this.active < this.maxConcurrentChannels) {\n const channel = this.queue.shift()\n if (!channel) break\n const state = this.pending.get(channel)\n if (!state || state.running) continue\n state.running = true\n this.active++\n void this.flush(channel, state).finally(() => {\n this.active--\n this.pump()\n this.resolveIdle()\n })\n }\n }\n\n private async flush(channel: string, state: PendingPublication) {\n let failure: unknown\n try {\n while (state.dirty) {\n state.dirty = false\n // Publications for one channel must preserve mutation order.\n // oxlint-disable-next-line no-await-in-loop\n await this.deliver(channel, state.data)\n }\n } catch (error) {\n failure = error\n } finally {\n if (this.pending.get(channel) === state) this.pending.delete(channel)\n }\n if (failure) {\n if (state.dirty) {\n this.pending.set(channel, { dirty: true, data: state.data, running: false })\n this.queue.push(channel)\n this.pump()\n }\n this.reportError(failure, channel)\n }\n }\n\n private async deliver(channel: string, data: unknown) {\n const maxRetries = this.options.maxRetries ?? 3\n for (let retries = 0; ; retries++) {\n try {\n // Retrying must finish before a later publication can overtake this one.\n // oxlint-disable-next-line no-await-in-loop\n await this.deliverOnce(channel, data)\n return\n } catch (error) {\n if (!(error instanceof TransientPublishError)) throw error\n if (retries >= maxRetries) throw error\n this.options.onRetry?.(error, channel)\n // oxlint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setTimeout(resolve, this.options.retryMs ?? 1_000))\n }\n }\n }\n\n private async deliverOnce(channel: string, data: unknown) {\n let response: Response\n try {\n response = await this.request(`${this.options.apiUrl.replace(/\\/$/, '')}/publish`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-API-Key': this.options.apiKey },\n body: JSON.stringify({ channel, data }),\n signal: AbortSignal.timeout(this.options.timeoutMs ?? 5_000),\n })\n } catch (error) {\n if (error instanceof TypeError || isTimeout(error))\n throw new TransientPublishError('Realtime publish request failed', { cause: error })\n throw error\n }\n\n if (!response.ok) {\n const message = `Realtime publish failed with status ${response.status}`\n if (response.status >= 500 || response.status === 429) throw new TransientPublishError(message)\n throw new Error(message)\n }\n\n const result: unknown = await response.json()\n const error = centrifugoError(result)\n if (!error) return\n const message = `Realtime publish failed: ${error.message ?? `code ${error.code ?? 'unknown'}`}`\n if (error.code === 100) throw new TransientPublishError(message)\n throw new Error(message)\n }\n\n private reportError(error: unknown, channel: string) {\n try {\n this.options.onError(error, channel)\n } catch {}\n }\n\n private isIdle() {\n return this.pending.size === 0 && this.active === 0 && this.queue.length === 0\n }\n\n private resolveIdle() {\n if (!this.isIdle()) return\n for (const resolve of this.idleWaiters) resolve()\n this.idleWaiters.clear()\n }\n}\n\nasync function abortable(work: Promise<void>, signal: AbortSignal) {\n signal.throwIfAborted()\n let abort!: () => void\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => reject(signal.reason)\n signal.addEventListener('abort', abort, { once: true })\n })\n try {\n await Promise.race([work, aborted])\n } finally {\n signal.removeEventListener('abort', abort)\n }\n}\n\nclass TransientPublishError extends Error {}\n\nfunction isTimeout(error: unknown) {\n return error instanceof DOMException && error.name === 'TimeoutError'\n}\n\nfunction centrifugoError(result: unknown): { code?: number; message?: string } | undefined {\n if (!result || typeof result !== 'object' || !('error' in result) || !result.error || typeof result.error !== 'object') return undefined\n const code = 'code' in result.error && typeof result.error.code === 'number' ? result.error.code : undefined\n const message = 'message' in result.error && typeof result.error.message === 'string' ? result.error.message : undefined\n return { ...(code === undefined ? {} : { code }), ...(message === undefined ? {} : { message }) }\n}\n\nfunction positiveInteger(value: number, name: string) {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`)\n return value\n}\n"]}
1
+ {"version":3,"file":"publisher.js","sourceRoot":"","sources":["../../src/realtime/publisher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAiB1D,MAAM,OAAO,mBAAmB;IAWD,OAAO;IAVnB,OAAO,GAAG,I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CAAA;IACxI,MAAM,IAAI,GAAG,MAAM,IAAI,MAAM,CAAC,KAAK,IAAI,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IAC5G,MAAM,OAAO,GAAG,SAAS,IAAI,MAAM,CAAC,KAAK,IAAI,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAA;IACxH,OAAO,EAAE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAA;AACnG,CAAC;AAED,SAAS,eAAe,CAAC,KAAa,EAAE,IAAY;IAClD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,6BAA6B,CAAC,CAAA;IACzG,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { setTimeout as delay } from 'node:timers/promises'\n\nexport type CentrifugoPublisherOptions = {\n apiUrl: string\n apiKey: string\n fetch?: typeof fetch\n timeoutMs?: number\n retryMs?: number\n maxRetries?: number\n maxConcurrentChannels?: number\n maxPendingChannels?: number\n onError: (error: unknown, channel: string) => void\n onRetry?: (error: unknown, channel: string) => void\n}\n\ntype PendingPublication = { dirty: boolean; data: unknown; running: boolean }\n\nexport class CentrifugoPublisher {\n private readonly pending = new Map<string, PendingPublication>()\n private readonly queue: string[] = []\n private readonly idleWaiters = new Set<() => void>()\n private readonly request: typeof fetch\n private readonly publishUrl: string\n private readonly maxConcurrentChannels: number\n private readonly maxPendingChannels: number\n private active = 0\n private closed = false\n\n constructor(private readonly options: CentrifugoPublisherOptions) {\n this.request = options.fetch ?? fetch\n this.publishUrl = `${options.apiUrl.replace(/\\/$/, '')}/publish`\n this.maxConcurrentChannels = positiveInteger(options.maxConcurrentChannels ?? 8, 'maxConcurrentChannels')\n this.maxPendingChannels = positiveInteger(options.maxPendingChannels ?? 1_024, 'maxPendingChannels')\n }\n\n publish(channel: string, data: unknown) {\n if (!this.options.apiUrl) return false\n if (this.closed) {\n this.reportError(new Error('Realtime publisher is closed'), channel)\n return false\n }\n const pending = this.pending.get(channel)\n if (pending) {\n pending.dirty = true\n pending.data = data\n return true\n }\n if (this.pending.size >= this.maxPendingChannels) {\n this.reportError(new Error('Realtime publisher queue is full'), channel)\n return false\n }\n\n const state = { dirty: true, data, running: false }\n this.pending.set(channel, state)\n this.queue.push(channel)\n this.pump()\n return true\n }\n\n idle() {\n if (this.isIdle()) return Promise.resolve()\n return new Promise<void>((resolve) => this.idleWaiters.add(resolve))\n }\n\n async close(options: { signal?: AbortSignal } = {}) {\n this.closed = true\n const idle = this.idle()\n if (!options.signal) return idle\n await abortable(idle, options.signal)\n }\n\n private pump() {\n while (this.active < this.maxConcurrentChannels) {\n const channel = this.queue.shift()\n if (channel === undefined) break\n // A channel is queued only alongside a fresh, idle pending state.\n const state = this.pending.get(channel)!\n state.running = true\n this.active++\n void this.flush(channel, state).finally(() => {\n this.active--\n this.pump()\n this.resolveIdle()\n })\n }\n }\n\n private async flush(channel: string, state: PendingPublication) {\n let failure: unknown\n try {\n while (state.dirty) {\n state.dirty = false\n // Publications for one channel must preserve mutation order.\n // oxlint-disable-next-line no-await-in-loop\n await this.deliver(channel, state.data)\n }\n } catch (error) {\n failure = error\n } finally {\n if (this.pending.get(channel) === state) this.pending.delete(channel)\n }\n if (failure) {\n if (state.dirty) {\n this.pending.set(channel, { dirty: true, data: state.data, running: false })\n this.queue.push(channel)\n this.pump()\n }\n this.reportError(failure, channel)\n }\n }\n\n private async deliver(channel: string, data: unknown) {\n const maxRetries = this.options.maxRetries ?? 3\n for (let retries = 0; ; retries++) {\n try {\n // Retrying must finish before a later publication can overtake this one.\n // oxlint-disable-next-line no-await-in-loop\n await this.deliverOnce(channel, data)\n return\n } catch (error) {\n if (!(error instanceof TransientPublishError)) throw error\n if (retries >= maxRetries) throw error\n this.options.onRetry?.(error, channel)\n // oxlint-disable-next-line no-await-in-loop\n await delay(this.options.retryMs ?? 1_000)\n }\n }\n }\n\n private async deliverOnce(channel: string, data: unknown) {\n let response: Response\n try {\n response = await this.request(this.publishUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'X-API-Key': this.options.apiKey },\n body: JSON.stringify({ channel, data }),\n signal: AbortSignal.timeout(this.options.timeoutMs ?? 5_000),\n })\n } catch (error) {\n if (error instanceof TypeError || isTimeout(error))\n throw new TransientPublishError('Realtime publish request failed', { cause: error })\n throw error\n }\n\n if (!response.ok) {\n const message = `Realtime publish failed with status ${response.status}`\n if (response.status >= 500 || response.status === 429) throw new TransientPublishError(message)\n throw new Error(message)\n }\n\n const result: unknown = await response.json()\n const error = centrifugoError(result)\n if (!error) return\n const message = `Realtime publish failed: ${error.message ?? `code ${error.code ?? 'unknown'}`}`\n if (error.code === 100) throw new TransientPublishError(message)\n throw new Error(message)\n }\n\n private reportError(error: unknown, channel: string) {\n try {\n this.options.onError(error, channel)\n } catch {}\n }\n\n private isIdle() {\n return this.pending.size === 0 && this.active === 0 && this.queue.length === 0\n }\n\n private resolveIdle() {\n if (!this.isIdle()) return\n for (const resolve of this.idleWaiters) resolve()\n this.idleWaiters.clear()\n }\n}\n\nasync function abortable(work: Promise<void>, signal: AbortSignal) {\n signal.throwIfAborted()\n let abort!: () => void\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => reject(signal.reason)\n signal.addEventListener('abort', abort, { once: true })\n })\n try {\n await Promise.race([work, aborted])\n } finally {\n signal.removeEventListener('abort', abort)\n }\n}\n\nclass TransientPublishError extends Error {}\n\nfunction isTimeout(error: unknown) {\n return error instanceof DOMException && error.name === 'TimeoutError'\n}\n\nfunction centrifugoError(result: unknown): { code?: number; message?: string } | undefined {\n if (!result || typeof result !== 'object' || !('error' in result) || !result.error || typeof result.error !== 'object') return undefined\n const code = 'code' in result.error && typeof result.error.code === 'number' ? result.error.code : undefined\n const message = 'message' in result.error && typeof result.error.message === 'string' ? result.error.message : undefined\n return { ...(code === undefined ? {} : { code }), ...(message === undefined ? {} : { message }) }\n}\n\nfunction positiveInteger(value: number, name: string) {\n if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`)\n return value\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { type StdioOptions } from 'node:child_process';
1
2
  export type RealtimeDevOptions = {
2
3
  configPath: string;
3
4
  containerName: string;
@@ -11,9 +12,8 @@ export type RealtimeDevOptions = {
11
12
  type CommandResult = {
12
13
  code: number;
13
14
  };
14
- type RunCommand = (command: string, args: readonly string[]) => Promise<CommandResult>;
15
+ type RunCommand = (command: string, args: readonly string[], stdio?: StdioOptions) => Promise<CommandResult>;
15
16
  type RealtimeDevDependencies = {
16
- remove?: (containerName: string) => Promise<void>;
17
17
  run?: RunCommand;
18
18
  };
19
19
  export declare function runRealtimeDev(options: RealtimeDevOptions, dependencies?: RealtimeDevDependencies): Promise<void>;
@@ -1,6 +1,10 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { once } from 'node:events';
2
3
  import { access } from 'node:fs/promises';
3
4
  import path from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { errorHasCode } from '../server/errors.js';
7
+ import { centrifugoEnvironment, port, requiredValue } from './stack.js';
4
8
  const runtimeImage = 'ghcr.io/richardsolomou/ras-stack-runtime-binaries:runtime-v1.0.4@sha256:183261400ef822d3dfb7ae9391dc3836d343e01de41ab131df6a42751f87288e';
5
9
  export async function runRealtimeDev(options, dependencies = {}) {
6
10
  const configPath = path.resolve(options.configPath);
@@ -11,16 +15,27 @@ export async function runRealtimeDev(options, dependencies = {}) {
11
15
  throw new Error(`realtime config is unavailable: ${configPath}`, { cause: error });
12
16
  }
13
17
  const containerName = dockerName(options.containerName);
14
- const publicPort = tcpPort(options.port);
18
+ const publicPort = port(options.port, 'port');
15
19
  const bindAddress = dockerBindAddress(options.bindAddress ?? '127.0.0.1');
16
20
  const origin = httpUrl(options.origin, 'origin');
17
- const secret = required(options.secret, 'secret');
21
+ const secret = requiredValue(options.secret, 'secret');
18
22
  const connectProxyEndpoint = options.connectProxyEndpoint ? httpEndpoint(options.connectProxyEndpoint) : undefined;
19
23
  const run = dependencies.run ?? runCommand;
20
- const remove = dependencies.remove ?? removeContainer;
24
+ // Docker publishes the port to the container's network interface, which a loopback-only listener would not accept.
25
+ const { CENTRIFUGO_HTTP_SERVER_ADDRESS: _loopback, ...centrifugo } = centrifugoEnvironment({
26
+ apiKey: secret,
27
+ clientTokenSecret: secret,
28
+ subscriptionTokenSecret: secret,
29
+ allowedOrigins: origin,
30
+ });
31
+ const environment = {
32
+ ...centrifugo,
33
+ CENTRIFUGO_VAR_PROXY_SECRET: secret,
34
+ ...(connectProxyEndpoint ? { CENTRIFUGO_CLIENT_PROXY_CONNECT_ENDPOINT: connectProxyEndpoint } : {}),
35
+ };
21
36
  try {
22
37
  if (options.detached)
23
- await remove(containerName);
38
+ await run('docker', ['rm', '--force', containerName], 'ignore');
24
39
  const result = await run('docker', [
25
40
  'run',
26
41
  '--rm',
@@ -31,98 +46,59 @@ export async function runRealtimeDev(options, dependencies = {}) {
31
46
  'host.docker.internal:host-gateway',
32
47
  '-p',
33
48
  `${bindAddress}:${publicPort}:8000`,
34
- '-e',
35
- `CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY=${secret}`,
36
- '-e',
37
- 'CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED=true',
38
- '-e',
39
- `CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY=${secret}`,
40
- '-e',
41
- `CENTRIFUGO_HTTP_API_KEY=${secret}`,
42
- '-e',
43
- `CENTRIFUGO_CLIENT_ALLOWED_ORIGINS=${origin}`,
44
- '-e',
45
- `CENTRIFUGO_VAR_PROXY_SECRET=${secret}`,
46
- ...(connectProxyEndpoint ? ['-e', `CENTRIFUGO_CLIENT_PROXY_CONNECT_ENDPOINT=${connectProxyEndpoint}`] : []),
49
+ ...Object.entries(environment).flatMap(([name, value]) => ['-e', `${name}=${value}`]),
47
50
  '-v',
48
51
  `${configPath}:/centrifugo/config.json:ro`,
49
52
  runtimeImage,
50
53
  '/usr/local/bin/centrifugo',
51
54
  '--config=/centrifugo/config.json',
52
- '--health.enabled',
53
55
  ]);
54
56
  if (result.code !== 0)
55
57
  throw new Error(`Docker exited with status ${result.code}`);
56
58
  }
57
59
  catch (error) {
58
- if (error.code === 'ENOENT') {
60
+ if (errorHasCode(error, 'ENOENT')) {
59
61
  throw new Error('Docker is required but was not found', { cause: error });
60
62
  }
61
63
  throw error;
62
64
  }
63
65
  }
64
66
  export function parseRealtimeDevArguments(arguments_) {
65
- const values = new Map();
66
- let detached = false;
67
- for (let index = 0; index < arguments_.length; index += 1) {
68
- const argument = arguments_[index];
69
- if (argument === '--detach') {
70
- detached = true;
71
- continue;
72
- }
73
- if (!['--config', '--name', '--port', '--bind-address', '--origin', '--secret', '--connect-proxy-endpoint'].includes(argument)) {
74
- throw new Error(`unknown argument: ${argument}`);
75
- }
76
- const value = arguments_[index + 1];
77
- if (!value || value.startsWith('--'))
78
- throw new Error(`${argument} requires a value`);
79
- values.set(argument, value);
80
- index += 1;
81
- }
82
- const connectProxyEndpoint = values.get('--connect-proxy-endpoint');
83
- const bindAddress = values.get('--bind-address');
67
+ const { values } = parseArgs({
68
+ args: [...arguments_],
69
+ options: {
70
+ config: { type: 'string' },
71
+ name: { type: 'string' },
72
+ port: { type: 'string' },
73
+ 'bind-address': { type: 'string' },
74
+ origin: { type: 'string' },
75
+ secret: { type: 'string' },
76
+ 'connect-proxy-endpoint': { type: 'string' },
77
+ detach: { type: 'boolean' },
78
+ },
79
+ strict: true,
80
+ });
84
81
  return {
85
- configPath: required(values.get('--config'), '--config'),
86
- containerName: required(values.get('--name'), '--name'),
87
- port: Number(required(values.get('--port'), '--port')),
88
- ...(bindAddress ? { bindAddress } : {}),
89
- origin: required(values.get('--origin'), '--origin'),
90
- secret: required(values.get('--secret'), '--secret'),
91
- ...(detached ? { detached: true } : {}),
92
- ...(connectProxyEndpoint ? { connectProxyEndpoint } : {}),
82
+ configPath: requiredValue(values.config, '--config'),
83
+ containerName: requiredValue(values.name, '--name'),
84
+ port: Number(requiredValue(values.port, '--port')),
85
+ ...(values['bind-address'] ? { bindAddress: values['bind-address'] } : {}),
86
+ origin: requiredValue(values.origin, '--origin'),
87
+ secret: requiredValue(values.secret, '--secret'),
88
+ ...(values.detach ? { detached: true } : {}),
89
+ ...(values['connect-proxy-endpoint'] ? { connectProxyEndpoint: values['connect-proxy-endpoint'] } : {}),
93
90
  };
94
91
  }
95
- async function runCommand(command, args) {
96
- return new Promise((resolve, reject) => {
97
- const child = spawn(command, [...args], { stdio: 'inherit' });
98
- child.once('error', reject);
99
- child.once('exit', (code) => resolve({ code: code ?? 1 }));
100
- });
101
- }
102
- async function removeContainer(containerName) {
103
- await new Promise((resolve, reject) => {
104
- const child = spawn('docker', ['rm', '--force', containerName], { stdio: 'ignore' });
105
- child.once('error', reject);
106
- child.once('exit', () => resolve());
107
- });
108
- }
109
- function required(value, name) {
110
- const normalized = value?.trim();
111
- if (!normalized)
112
- throw new Error(`${name} is required`);
113
- return normalized;
92
+ async function runCommand(command, args, stdio = 'inherit') {
93
+ const [code] = (await once(spawn(command, [...args], { stdio }), 'exit'));
94
+ return { code: code ?? 1 };
114
95
  }
115
96
  function dockerName(value) {
116
- const normalized = required(value, 'containerName');
97
+ const normalized = requiredValue(value, 'containerName');
117
98
  if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(normalized))
118
99
  throw new Error('containerName is invalid');
119
100
  return normalized;
120
101
  }
121
- function tcpPort(value) {
122
- if (!Number.isInteger(value) || value < 1 || value > 65_535)
123
- throw new Error('port must be a valid TCP port');
124
- return value;
125
- }
126
102
  function dockerBindAddress(value) {
127
103
  if (value !== '127.0.0.1' && value !== '0.0.0.0')
128
104
  throw new Error('bindAddress must be 127.0.0.1 or 0.0.0.0');
@@ -1 +1 @@
1
- {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/runtime/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,IAAI,MAAM,WAAW,CAAA;AAE5B,MAAM,YAAY,GAChB,0IAA0I,CAAA;AAiB5I,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,OAA2B,EAAE,YAAY,GAA4B,EAAE;IAC1G,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;IACnD,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,UAAU,CAAC,CAAA;IAC1B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,mCAAmC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IACpF,CAAC;IACD,MAAM,aAAa,GAAG,UAAU,CAAC,OAAO,CAAC,aAAa,CAAC,CAAA;IACvD,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IACxC,MAAM,WAAW,GAAG,iBAAiB,CAAC,OAAO,CAAC,WAAW,IAAI,WAAW,CAAC,CAAA;IACzE,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IAChD,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,QAA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AAA;AAC1B,CAAC","sourcesContent":["import { spawn } from 'node:child_process'\nimport { access } from 'node:fs/promises'\nimport path from 'node:path'\n\nconst runtimeImage =\n 'ghcr.io/richardsolomou/ras-stack-runtime-binaries:runtime-v1.0.4@sha256:183261400ef822d3dfb7ae9391dc3836d343e01de41ab131df6a42751f87288e'\n\nexport type RealtimeDevOptions = {\n configPath: string\n containerName: string\n port: number\n bindAddress?: string\n origin: string\n secret: string\n detached?: boolean\n connectProxyEndpoint?: string\n}\n\ntype CommandResult = { code: number }\ntype RunCommand = (command: string, args: readonly string[]) => Promise<CommandResult>\ntype RealtimeDevDependencies = { remove?: (containerName: string) => Promise<void>; run?: RunCommand }\n\nexport async function runRealtimeDev(options: RealtimeDevOptions, dependencies: RealtimeDevDependencies = {}) {\n const configPath = path.resolve(options.configPath)\n try {\n await access(configPath)\n } catch (error) {\n throw new Error(`realtime config is unavailable: ${configPath}`, { cause: error })\n }\n const containerName = dockerName(options.containerName)\n const publicPort = tcpPort(options.port)\n const bindAddress = dockerBindAddress(options.bindAddress ?? '127.0.0.1')\n const origin = httpUrl(options.origin, 'origin')\n const secret = required(options.secret, 'secret')\n const connectProxyEndpoint = options.connectProxyEndpoint ? httpEndpoint(options.connectProxyEndpoint) : undefined\n const run = dependencies.run ?? runCommand\n const remove = dependencies.remove ?? removeContainer\n\n try {\n if (options.detached) await remove(containerName)\n const result = await run('docker', [\n 'run',\n '--rm',\n ...(options.detached ? ['-d'] : []),\n '--name',\n containerName,\n '--add-host',\n 'host.docker.internal:host-gateway',\n '-p',\n `${bindAddress}:${publicPort}:8000`,\n '-e',\n `CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY=${secret}`,\n '-e',\n 'CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED=true',\n '-e',\n `CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY=${secret}`,\n '-e',\n `CENTRIFUGO_HTTP_API_KEY=${secret}`,\n '-e',\n `CENTRIFUGO_CLIENT_ALLOWED_ORIGINS=${origin}`,\n '-e',\n `CENTRIFUGO_VAR_PROXY_SECRET=${secret}`,\n ...(connectProxyEndpoint ? ['-e', `CENTRIFUGO_CLIENT_PROXY_CONNECT_ENDPOINT=${connectProxyEndpoint}`] : []),\n '-v',\n `${configPath}:/centrifugo/config.json:ro`,\n runtimeImage,\n '/usr/local/bin/centrifugo',\n '--config=/centrifugo/config.json',\n '--health.enabled',\n ])\n if (result.code !== 0) throw new Error(`Docker exited with status ${result.code}`)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error('Docker is required but was not found', { cause: error })\n }\n throw error\n }\n}\n\nexport function parseRealtimeDevArguments(arguments_: readonly string[]): RealtimeDevOptions {\n const values = new Map<string, string>()\n let detached = false\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index]!\n if (argument === '--detach') {\n detached = true\n continue\n }\n if (!['--config', '--name', '--port', '--bind-address', '--origin', '--secret', '--connect-proxy-endpoint'].includes(argument)) {\n throw new Error(`unknown argument: ${argument}`)\n }\n const value = arguments_[index + 1]\n if (!value || value.startsWith('--')) throw new Error(`${argument} requires a value`)\n values.set(argument, value)\n index += 1\n }\n const connectProxyEndpoint = values.get('--connect-proxy-endpoint')\n const bindAddress = values.get('--bind-address')\n return {\n configPath: required(values.get('--config'), '--config'),\n containerName: required(values.get('--name'), '--name'),\n port: Number(required(values.get('--port'), '--port')),\n ...(bindAddress ? { bindAddress } : {}),\n origin: required(values.get('--origin'), '--origin'),\n secret: required(values.get('--secret'), '--secret'),\n ...(detached ? { detached: true } : {}),\n ...(connectProxyEndpoint ? { connectProxyEndpoint } : {}),\n }\n}\n\nasync function runCommand(command: string, args: readonly string[]) {\n return new Promise<CommandResult>((resolve, reject) => {\n const child = spawn(command, [...args], { stdio: 'inherit' })\n child.once('error', reject)\n child.once('exit', (code) => resolve({ code: code ?? 1 }))\n })\n}\n\nasync function removeContainer(containerName: string) {\n await new Promise<void>((resolve, reject) => {\n const child = spawn('docker', ['rm', '--force', containerName], { stdio: 'ignore' })\n child.once('error', reject)\n child.once('exit', () => resolve())\n })\n}\n\nfunction required(value: string | undefined, name: string) {\n const normalized = value?.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nfunction dockerName(value: string) {\n const normalized = required(value, 'containerName')\n if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(normalized)) throw new Error('containerName is invalid')\n return normalized\n}\n\nfunction tcpPort(value: number) {\n if (!Number.isInteger(value) || value < 1 || value > 65_535) throw new Error('port must be a valid TCP port')\n return value\n}\n\nfunction dockerBindAddress(value: string) {\n if (value !== '127.0.0.1' && value !== '0.0.0.0') throw new Error('bindAddress must be 127.0.0.1 or 0.0.0.0')\n return value\n}\n\nfunction httpUrl(value: string, name: string) {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n throw new Error(`${name} must be an HTTP URL`)\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== '/' ||\n parsed.search ||\n parsed.hash\n ) {\n throw new Error(`${name} must be an HTTP origin`)\n }\n return parsed.origin\n}\n\nfunction httpEndpoint(value: string) {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n throw new Error('connectProxyEndpoint must be an HTTP URL')\n }\n if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) {\n throw new Error('connectProxyEndpoint must be an HTTP URL without credentials, query, or fragment')\n }\n return parsed.toString()\n}\n"]}
1
+ {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/runtime/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,IAAI,MAAM,WAAW,CAAA;A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KAAK,CAAC,GAAG,IAAI,sBAAsB,CAAC,CAAA;IAChD,CAAC;IACD,IACE,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC;QAC9C,MAAM,CAAC,QAAQ;QACf,MAAM,CAAC,QAAQ;QACf,MAAM,CAAC,QAAQ,KAAK,GAAG;QACvB,MAAM,CAAC,MAAM;QACb,MAAM,CAAC,IAAI,EACX,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,yBAAyB,CAAC,CAAA;IACnD,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAA;AACtB,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,IAAI,MAAW,CAAA;IACf,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAA;IACzB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;IAC7D,CAAC;IACD,IAAI,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QACzH,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAA;IACrG,CAAC;IACD,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAA;AAC1B,CAAC","sourcesContent":["import { spawn, type StdioOptions } from 'node:child_process'\nimport { once } from 'node:events'\nimport { access } from 'node:fs/promises'\nimport path from 'node:path'\nimport { parseArgs } from 'node:util'\nimport { errorHasCode } from '../server/errors.js'\nimport { centrifugoEnvironment, port, requiredValue } from './stack.js'\n\nconst runtimeImage =\n 'ghcr.io/richardsolomou/ras-stack-runtime-binaries:runtime-v1.0.4@sha256:183261400ef822d3dfb7ae9391dc3836d343e01de41ab131df6a42751f87288e'\n\nexport type RealtimeDevOptions = {\n configPath: string\n containerName: string\n port: number\n bindAddress?: string\n origin: string\n secret: string\n detached?: boolean\n connectProxyEndpoint?: string\n}\n\ntype CommandResult = { code: number }\ntype RunCommand = (command: string, args: readonly string[], stdio?: StdioOptions) => Promise<CommandResult>\ntype RealtimeDevDependencies = { run?: RunCommand }\n\nexport async function runRealtimeDev(options: RealtimeDevOptions, dependencies: RealtimeDevDependencies = {}) {\n const configPath = path.resolve(options.configPath)\n try {\n await access(configPath)\n } catch (error) {\n throw new Error(`realtime config is unavailable: ${configPath}`, { cause: error })\n }\n const containerName = dockerName(options.containerName)\n const publicPort = port(options.port, 'port')\n const bindAddress = dockerBindAddress(options.bindAddress ?? '127.0.0.1')\n const origin = httpUrl(options.origin, 'origin')\n const secret = requiredValue(options.secret, 'secret')\n const connectProxyEndpoint = options.connectProxyEndpoint ? httpEndpoint(options.connectProxyEndpoint) : undefined\n const run = dependencies.run ?? runCommand\n // Docker publishes the port to the container's network interface, which a loopback-only listener would not accept.\n const { CENTRIFUGO_HTTP_SERVER_ADDRESS: _loopback, ...centrifugo } = centrifugoEnvironment({\n apiKey: secret,\n clientTokenSecret: secret,\n subscriptionTokenSecret: secret,\n allowedOrigins: origin,\n })\n const environment = {\n ...centrifugo,\n CENTRIFUGO_VAR_PROXY_SECRET: secret,\n ...(connectProxyEndpoint ? { CENTRIFUGO_CLIENT_PROXY_CONNECT_ENDPOINT: connectProxyEndpoint } : {}),\n }\n\n try {\n if (options.detached) await run('docker', ['rm', '--force', containerName], 'ignore')\n const result = await run('docker', [\n 'run',\n '--rm',\n ...(options.detached ? ['-d'] : []),\n '--name',\n containerName,\n '--add-host',\n 'host.docker.internal:host-gateway',\n '-p',\n `${bindAddress}:${publicPort}:8000`,\n ...Object.entries(environment).flatMap(([name, value]) => ['-e', `${name}=${value}`]),\n '-v',\n `${configPath}:/centrifugo/config.json:ro`,\n runtimeImage,\n '/usr/local/bin/centrifugo',\n '--config=/centrifugo/config.json',\n ])\n if (result.code !== 0) throw new Error(`Docker exited with status ${result.code}`)\n } catch (error) {\n if (errorHasCode(error, 'ENOENT')) {\n throw new Error('Docker is required but was not found', { cause: error })\n }\n throw error\n }\n}\n\nexport function parseRealtimeDevArguments(arguments_: readonly string[]): RealtimeDevOptions {\n const { values } = parseArgs({\n args: [...arguments_],\n options: {\n config: { type: 'string' },\n name: { type: 'string' },\n port: { type: 'string' },\n 'bind-address': { type: 'string' },\n origin: { type: 'string' },\n secret: { type: 'string' },\n 'connect-proxy-endpoint': { type: 'string' },\n detach: { type: 'boolean' },\n },\n strict: true,\n })\n return {\n configPath: requiredValue(values.config, '--config'),\n containerName: requiredValue(values.name, '--name'),\n port: Number(requiredValue(values.port, '--port')),\n ...(values['bind-address'] ? { bindAddress: values['bind-address'] } : {}),\n origin: requiredValue(values.origin, '--origin'),\n secret: requiredValue(values.secret, '--secret'),\n ...(values.detach ? { detached: true } : {}),\n ...(values['connect-proxy-endpoint'] ? { connectProxyEndpoint: values['connect-proxy-endpoint'] } : {}),\n }\n}\n\nasync function runCommand(command: string, args: readonly string[], stdio: StdioOptions = 'inherit') {\n const [code] = (await once(spawn(command, [...args], { stdio }), 'exit')) as [number | null]\n return { code: code ?? 1 }\n}\n\nfunction dockerName(value: string) {\n const normalized = requiredValue(value, 'containerName')\n if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(normalized)) throw new Error('containerName is invalid')\n return normalized\n}\n\nfunction dockerBindAddress(value: string) {\n if (value !== '127.0.0.1' && value !== '0.0.0.0') throw new Error('bindAddress must be 127.0.0.1 or 0.0.0.0')\n return value\n}\n\nfunction httpUrl(value: string, name: string) {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n throw new Error(`${name} must be an HTTP URL`)\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== '/' ||\n parsed.search ||\n parsed.hash\n ) {\n throw new Error(`${name} must be an HTTP origin`)\n }\n return parsed.origin\n}\n\nfunction httpEndpoint(value: string) {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n throw new Error('connectProxyEndpoint must be an HTTP URL')\n }\n if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) {\n throw new Error('connectProxyEndpoint must be an HTTP URL without credentials, query, or fragment')\n }\n return parsed.toString()\n}\n"]}
@@ -13,7 +13,6 @@ export type SupervisorOptions = {
13
13
  signalSource?: SignalSource;
14
14
  spawn?: SpawnProcess;
15
15
  };
16
- export declare function superviseProcesses(processes: readonly RuntimeProcess[], options?: SupervisorOptions, shutdownOrder?: readonly string[]): Promise<number>;
17
16
  export type CentrifugoEnvironmentOptions = {
18
17
  apiKey: string;
19
18
  clientTokenSecret?: string;
@@ -56,6 +55,8 @@ export type CaddyRealtimeProxyOptions = {
56
55
  encode?: boolean;
57
56
  };
58
57
  export declare function caddyRealtimeProxy(options?: CaddyRealtimeProxyOptions): string;
58
+ export declare function requiredValue(value: string | undefined, name: string): string;
59
+ export declare function port(value: number, name: string): number;
59
60
  export type PersistedRealtimeSecretOptions = {
60
61
  prefix?: string;
61
62
  defaultFile?: string;
@@ -2,18 +2,10 @@ import { spawn } from 'node:child_process';
2
2
  import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { persistedSecret } from '../auth/secret.js';
5
- export async function superviseProcesses(processes, options = {}, shutdownOrder) {
6
- if (processes.length === 0)
7
- throw new Error('at least one runtime process is required');
8
- const names = new Set();
5
+ async function superviseProcesses(processes, options, shutdownOrder) {
9
6
  for (const process of processes) {
10
- if (!process.name.trim())
11
- throw new Error('runtime process names must not be empty');
12
7
  if (!process.command.trim())
13
8
  throw new Error(`runtime process ${process.name} must have a command`);
14
- if (names.has(process.name))
15
- throw new Error(`duplicate runtime process name: ${process.name}`);
16
- names.add(process.name);
17
9
  }
18
10
  const signalSource = options.signalSource ?? process;
19
11
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000;
@@ -41,7 +33,14 @@ export async function superviseProcesses(processes, options = {}, shutdownOrder)
41
33
  settled = true;
42
34
  signalSource.off('SIGINT', onSignal);
43
35
  signalSource.off('SIGTERM', onSignal);
44
- await stopChildren([...children.keys()], shutdownTimeoutMs);
36
+ const active = [...children.keys()].filter(running);
37
+ for (const child of active)
38
+ child.kill('SIGTERM');
39
+ if (!(await beforeDeadline(Promise.all(active.map((child) => exits.get(child))), shutdownTimeoutMs))) {
40
+ for (const child of active)
41
+ if (running(child))
42
+ child.kill('SIGKILL');
43
+ }
45
44
  resolveResult(status);
46
45
  };
47
46
  const finishInPhases = async () => {
@@ -51,7 +50,7 @@ export async function superviseProcesses(processes, options = {}, shutdownOrder)
51
50
  signalSource.off('SIGINT', onSignal);
52
51
  signalSource.off('SIGTERM', onSignal);
53
52
  const deadline = Date.now() + shutdownTimeoutMs;
54
- for (const name of shutdownOrder ?? []) {
53
+ for (const name of shutdownOrder) {
55
54
  if (settled)
56
55
  return;
57
56
  const child = [...children].find(([, childName]) => childName === name)?.[0];
@@ -76,12 +75,7 @@ export async function superviseProcesses(processes, options = {}, shutdownOrder)
76
75
  settled = true;
77
76
  resolveResult(0);
78
77
  };
79
- const onSignal = () => {
80
- if (shutdownOrder)
81
- void finishInPhases();
82
- else
83
- void finishImmediately(0);
84
- };
78
+ const onSignal = () => void finishInPhases();
85
79
  signalSource.once('SIGINT', onSignal);
86
80
  signalSource.once('SIGTERM', onSignal);
87
81
  try {
@@ -119,26 +113,6 @@ async function beforeDeadline(exited, timeoutMs) {
119
113
  function running(child) {
120
114
  return child.exitCode === null && child.signalCode === null;
121
115
  }
122
- async function stopChildren(children, timeoutMs) {
123
- const active = children.filter(running);
124
- if (active.length === 0)
125
- return;
126
- const exited = Promise.all(active.map((child) => new Promise((resolve) => child.once('exit', () => resolve())))).then(() => 'exited');
127
- for (const child of active)
128
- child.kill('SIGTERM');
129
- let timer;
130
- const timeout = new Promise((resolve) => {
131
- timer = setTimeout(() => resolve('timeout'), timeoutMs);
132
- });
133
- const outcome = await Promise.race([exited, timeout]);
134
- if (timer)
135
- clearTimeout(timer);
136
- if (outcome === 'timeout') {
137
- for (const child of active)
138
- if (running(child))
139
- child.kill('SIGKILL');
140
- }
141
- }
142
116
  export async function runRealtimeStack(options) {
143
117
  const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath');
144
118
  const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath');
@@ -219,13 +193,13 @@ ${options.encode === false ? '' : '\tencode zstd gzip\n'}\troute {
219
193
  }
220
194
  `;
221
195
  }
222
- function requiredValue(value, name) {
223
- const normalized = value.trim();
196
+ export function requiredValue(value, name) {
197
+ const normalized = value?.trim();
224
198
  if (!normalized)
225
199
  throw new Error(`${name} is required`);
226
200
  return normalized;
227
201
  }
228
- function port(value, name) {
202
+ export function port(value, name) {
229
203
  if (!Number.isInteger(value) || value < 1 || value > 65_535)
230
204
  throw new Error(`${name} must be a valid TCP port`);
231
205
  return value;
@@ -1 +1 @@
1
- {"version":3,"file":"stack.js","sourceRoot":"","sources":["../../src/runtime/stack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAmBnD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,SAAoC,EACpC,OAAO,GAAsB,EAAE,EAC/B,aAAiC;IAEjC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;IACvF,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;IAC/B,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,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G,CAAC,IAAI,KAAK,GAAG,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,2BAA2B,CAAC,CAAA;IAChH,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAa,EAAE,IAAY;IAC/C,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,2BAA2B,CAAC,CAAA;IAChF,OAAO,KAAK,CAAA;AACd,CAAC;AAID,kHAAkH;AAClH,MAAM,UAAU,uBAAuB,CAAC,WAAW,GAAsB,OAAO,CAAC,GAAG,EAAE,OAAO,GAAmC,EAAE;IAChI,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAA;IACnC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,MAAM,sBAAsB,CAAC,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC,WAAW,IAAI,uBAAuB,CAAA;IACnH,MAAM,MAAM,GAAG,eAAe,CAAC;QAC7B,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAC7B,WAAW;QACX,cAAc,EAAE,GAAG,MAAM,iBAAiB;QAC1C,KAAK,EAAE,EAAE;KACV,CAAC,CAAA;IACF,WAAW,CAAC,GAAG,MAAM,iBAAiB,CAAC,GAAG,MAAM,CAAA;IAChD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { spawn, type ChildProcess } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { persistedSecret } from '../auth/secret.js'\n\nexport type RuntimeProcess = {\n name: string\n command: string\n args?: readonly string[]\n cwd?: string\n env?: NodeJS.ProcessEnv\n}\n\ntype SignalSource = Pick<NodeJS.Process, 'off' | 'once'>\ntype SpawnProcess = (process: RuntimeProcess) => ChildProcess\n\nexport type SupervisorOptions = {\n shutdownTimeoutMs?: number\n signalSource?: SignalSource\n spawn?: SpawnProcess\n}\n\nexport async function superviseProcesses(\n processes: readonly RuntimeProcess[],\n options: SupervisorOptions = {},\n shutdownOrder?: readonly string[],\n) {\n if (processes.length === 0) throw new Error('at least one runtime process is required')\n const names = new Set<string>()\n for (const process of processes) {\n if (!process.name.trim()) throw new Error('runtime process names must not be empty')\n if (!process.command.trim()) throw new Error(`runtime process ${process.name} must have a command`)\n if (names.has(process.name)) throw new Error(`duplicate runtime process name: ${process.name}`)\n names.add(process.name)\n }\n\n const signalSource = options.signalSource ?? process\n const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000\n if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {\n throw new Error('shutdownTimeoutMs must be a non-negative integer')\n }\n const spawnProcess =\n options.spawn ??\n ((specification: RuntimeProcess) =>\n spawn(specification.command, [...(specification.args ?? [])], {\n cwd: specification.cwd,\n env: specification.env ?? process.env,\n stdio: 'inherit',\n }))\n const children = new Map<ChildProcess, string>()\n const exits = new Map<ChildProcess, Promise<void>>()\n let settled = false\n let phasedShutdown = false\n let expectedExit: ChildProcess | undefined\n let resolveResult!: (value: number) => void\n const result = new Promise<number>((resolve) => {\n resolveResult = resolve\n })\n\n const finishImmediately = async (status: number) => {\n if (settled) return\n settled = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n await stopChildren([...children.keys()], shutdownTimeoutMs)\n resolveResult(status)\n }\n const finishInPhases = async () => {\n if (settled || phasedShutdown) return\n phasedShutdown = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n const deadline = Date.now() + shutdownTimeoutMs\n for (const name of shutdownOrder ?? []) {\n if (settled) return\n const child = [...children].find(([, childName]) => childName === name)?.[0]\n if (!child || !running(child)) continue\n expectedExit = child\n child.kill('SIGTERM')\n // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.\n const exited = await beforeDeadline(exits.get(child)!, Math.max(0, deadline - Date.now()))\n expectedExit = undefined\n if (settled) return\n if (!exited) {\n settled = true\n for (const runningChild of children.keys()) if (running(runningChild)) runningChild.kill('SIGKILL')\n resolveResult(0)\n return\n }\n }\n settled = true\n resolveResult(0)\n }\n const onSignal = () => {\n if (shutdownOrder) void finishInPhases()\n else void finishImmediately(0)\n }\n signalSource.once('SIGINT', onSignal)\n signalSource.once('SIGTERM', onSignal)\n\n try {\n for (const specification of processes) {\n const child = spawnProcess(specification)\n children.set(child, specification.name)\n let resolveExit!: () => void\n exits.set(\n child,\n new Promise<void>((resolve) => {\n resolveExit = resolve\n }),\n )\n child.once('error', () => void finishImmediately(1))\n child.once('exit', (code) => {\n resolveExit()\n if (!phasedShutdown || child !== expectedExit) void finishImmediately(code && code > 0 ? code : 1)\n })\n }\n } catch (error) {\n await finishImmediately(1)\n throw error\n }\n return result\n}\n\nasync function beforeDeadline(exited: Promise<void>, timeoutMs: number) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n })\n const result = await Promise.race([exited.then(() => true as const), timeout])\n if (timer) clearTimeout(timer)\n return result\n}\n\nfunction running(child: ChildProcess) {\n return child.exitCode === null && child.signalCode === null\n}\n\nasync function stopChildren(children: ChildProcess[], timeoutMs: number) {\n const active = children.filter(running)\n if (active.length === 0) return\n const exited = Promise.all(active.map((child) => new Promise<void>((resolve) => child.once('exit', () => resolve())))).then(\n () => 'exited' as const,\n )\n for (const child of active) child.kill('SIGTERM')\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n })\n const outcome = await Promise.race([exited, timeout])\n if (timer) clearTimeout(timer)\n if (outcome === 'timeout') {\n for (const child of active) if (running(child)) child.kill('SIGKILL')\n }\n}\n\nexport type CentrifugoEnvironmentOptions = {\n apiKey: string\n clientTokenSecret?: string\n subscriptionTokenSecret?: string\n allowedOrigins?: string\n redisUrl?: string\n}\n\nexport type RealtimeStackOptions = {\n app: Omit<RuntimeProcess, 'name'>\n centrifugo: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n environment: CentrifugoEnvironmentOptions\n }\n caddy: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n proxy?: CaddyRealtimeProxyOptions\n runtime?: CaddyRuntimeEnvironmentOptions\n }\n supervisor?: SupervisorOptions\n}\n\nexport async function runRealtimeStack(options: RealtimeStackOptions) {\n const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath')\n const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath')\n await mkdir(path.dirname(configPath), { recursive: true })\n await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8')\n return superviseProcesses(\n [\n { name: 'app', ...options.app },\n {\n name: 'realtime',\n command: options.centrifugo.command ?? 'centrifugo',\n args: [`--config=${centrifugoConfigPath}`],\n ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),\n env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },\n },\n {\n name: 'proxy',\n command: options.caddy.command ?? 'caddy',\n args: ['run', '--config', configPath, '--adapter', 'caddyfile'],\n ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),\n env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },\n },\n ],\n options.supervisor ?? {},\n ['proxy', 'app', 'realtime'],\n )\n}\n\nexport function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv {\n const apiKey = requiredValue(options.apiKey, 'apiKey')\n const clientTokenSecret = options.clientTokenSecret?.trim()\n const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim()\n return {\n CENTRIFUGO_HTTP_API_KEY: apiKey,\n CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',\n CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',\n CENTRIFUGO_HEALTH_ENABLED: 'true',\n ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),\n ...(subscriptionTokenSecret\n ? {\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,\n }\n : {}),\n ...(options.redisUrl\n ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }\n : {}),\n }\n}\n\nexport type CaddyRuntimeEnvironmentOptions = { configHome?: string; dataHome?: string }\n\nexport function caddyRuntimeEnvironment(options: CaddyRuntimeEnvironmentOptions = {}): NodeJS.ProcessEnv {\n const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome')\n const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome')\n return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome }\n}\n\nexport type CaddyRealtimeProxyOptions = {\n publicPort?: number\n appPort?: number\n realtimePort?: number\n websocketPath?: string\n /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */\n encode?: boolean\n}\n\nexport function caddyRealtimeProxy(options: CaddyRealtimeProxyOptions = {}) {\n const publicPort = port(options.publicPort ?? 3000, 'publicPort')\n const appPort = port(options.appPort ?? 3001, 'appPort')\n const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort')\n const websocketPath = options.websocketPath ?? '/connection/'\n if (!/^\\/[A-Za-z0-9._~/-]+\\/$/.test(websocketPath) || websocketPath.includes('//')) {\n throw new Error('websocketPath must be a normalized absolute directory path')\n }\n return `{\n\\tservers {\n\\t\\ttrusted_proxies static private_ranges\n\\t\\ttrusted_proxies_strict\n\\t}\n}\n\n:${publicPort} {\n${options.encode === false ? '' : '\\tencode zstd gzip\\n'}\\troute {\n\\t\\t@foreignWebSocketOrigin \\`{path}.startsWith('${websocketPath}') && {http.request.header.Origin} != '' && {http.request.header.Origin} != 'http://' + {http.request.hostport} && {http.request.header.Origin} != 'https://' + {http.request.hostport}\\`\n\\t\\trespond @foreignWebSocketOrigin 403\n\n\\t\\thandle ${websocketPath}* {\n\\t\\t\\treverse_proxy 127.0.0.1:${realtimePort}\n\\t\\t}\n\n\\t\\thandle {\n\\t\\t\\treverse_proxy 127.0.0.1:${appPort}\n\\t\\t}\n\\t}\n}\n`\n}\n\nfunction requiredValue(value: string, name: string) {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nfunction port(value: number, name: string) {\n if (!Number.isInteger(value) || value < 1 || value > 65_535) throw new Error(`${name} must be a valid TCP port`)\n return value\n}\n\nfunction absolutePath(value: string, name: string) {\n if (!path.isAbsolute(value)) throw new Error(`${name} must be an absolute path`)\n return value\n}\n\nexport type PersistedRealtimeSecretOptions = { prefix?: string; defaultFile?: string }\n\n// The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.\nexport function persistedRealtimeSecret(environment: NodeJS.ProcessEnv = process.env, options: PersistedRealtimeSecretOptions = {}) {\n const prefix = options.prefix ?? ''\n const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret'\n const secret = persistedSecret({\n directory: path.dirname(file),\n filename: path.basename(file),\n environment,\n environmentKey: `${prefix}REALTIME_SECRET`,\n bytes: 48,\n })\n environment[`${prefix}REALTIME_SECRET`] = secret\n return secret\n}\n"]}
1
+ {"version":3,"file":"stack.js","sourceRoot":"","sources":["../../src/runtime/stack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,IAAI,MAAM,WAAW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CAAC,CAAA;IACF,WAAW,CAAC,GAAG,MAAM,iBAAiB,CAAC,GAAG,MAAM,CAAA;IAChD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { spawn, type ChildProcess } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { persistedSecret } from '../auth/secret.js'\n\nexport type RuntimeProcess = {\n name: string\n command: string\n args?: readonly string[]\n cwd?: string\n env?: NodeJS.ProcessEnv\n}\n\ntype SignalSource = Pick<NodeJS.Process, 'off' | 'once'>\ntype SpawnProcess = (process: RuntimeProcess) => ChildProcess\n\nexport type SupervisorOptions = {\n shutdownTimeoutMs?: number\n signalSource?: SignalSource\n spawn?: SpawnProcess\n}\n\nasync function superviseProcesses(processes: readonly RuntimeProcess[], options: SupervisorOptions, shutdownOrder: readonly string[]) {\n for (const process of processes) {\n if (!process.command.trim()) throw new Error(`runtime process ${process.name} must have a command`)\n }\n\n const signalSource = options.signalSource ?? process\n const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000\n if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {\n throw new Error('shutdownTimeoutMs must be a non-negative integer')\n }\n const spawnProcess =\n options.spawn ??\n ((specification: RuntimeProcess) =>\n spawn(specification.command, [...(specification.args ?? [])], {\n cwd: specification.cwd,\n env: specification.env ?? process.env,\n stdio: 'inherit',\n }))\n const children = new Map<ChildProcess, string>()\n const exits = new Map<ChildProcess, Promise<void>>()\n let settled = false\n let phasedShutdown = false\n let expectedExit: ChildProcess | undefined\n let resolveResult!: (value: number) => void\n const result = new Promise<number>((resolve) => {\n resolveResult = resolve\n })\n\n const finishImmediately = async (status: number) => {\n if (settled) return\n settled = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n const active = [...children.keys()].filter(running)\n for (const child of active) child.kill('SIGTERM')\n if (!(await beforeDeadline(Promise.all(active.map((child) => exits.get(child)!)), shutdownTimeoutMs))) {\n for (const child of active) if (running(child)) child.kill('SIGKILL')\n }\n resolveResult(status)\n }\n const finishInPhases = async () => {\n if (settled || phasedShutdown) return\n phasedShutdown = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n const deadline = Date.now() + shutdownTimeoutMs\n for (const name of shutdownOrder) {\n if (settled) return\n const child = [...children].find(([, childName]) => childName === name)?.[0]\n if (!child || !running(child)) continue\n expectedExit = child\n child.kill('SIGTERM')\n // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.\n const exited = await beforeDeadline(exits.get(child)!, Math.max(0, deadline - Date.now()))\n expectedExit = undefined\n if (settled) return\n if (!exited) {\n settled = true\n for (const runningChild of children.keys()) if (running(runningChild)) runningChild.kill('SIGKILL')\n resolveResult(0)\n return\n }\n }\n settled = true\n resolveResult(0)\n }\n const onSignal = () => void finishInPhases()\n signalSource.once('SIGINT', onSignal)\n signalSource.once('SIGTERM', onSignal)\n\n try {\n for (const specification of processes) {\n const child = spawnProcess(specification)\n children.set(child, specification.name)\n let resolveExit!: () => void\n exits.set(\n child,\n new Promise<void>((resolve) => {\n resolveExit = resolve\n }),\n )\n child.once('error', () => void finishImmediately(1))\n child.once('exit', (code) => {\n resolveExit()\n if (!phasedShutdown || child !== expectedExit) void finishImmediately(code && code > 0 ? code : 1)\n })\n }\n } catch (error) {\n await finishImmediately(1)\n throw error\n }\n return result\n}\n\nasync function beforeDeadline(exited: Promise<unknown>, timeoutMs: number) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n })\n const result = await Promise.race([exited.then(() => true as const), timeout])\n if (timer) clearTimeout(timer)\n return result\n}\n\nfunction running(child: ChildProcess) {\n return child.exitCode === null && child.signalCode === null\n}\n\nexport type CentrifugoEnvironmentOptions = {\n apiKey: string\n clientTokenSecret?: string\n subscriptionTokenSecret?: string\n allowedOrigins?: string\n redisUrl?: string\n}\n\nexport type RealtimeStackOptions = {\n app: Omit<RuntimeProcess, 'name'>\n centrifugo: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n environment: CentrifugoEnvironmentOptions\n }\n caddy: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n proxy?: CaddyRealtimeProxyOptions\n runtime?: CaddyRuntimeEnvironmentOptions\n }\n supervisor?: SupervisorOptions\n}\n\nexport async function runRealtimeStack(options: RealtimeStackOptions) {\n const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath')\n const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath')\n await mkdir(path.dirname(configPath), { recursive: true })\n await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8')\n return superviseProcesses(\n [\n { name: 'app', ...options.app },\n {\n name: 'realtime',\n command: options.centrifugo.command ?? 'centrifugo',\n args: [`--config=${centrifugoConfigPath}`],\n ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),\n env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },\n },\n {\n name: 'proxy',\n command: options.caddy.command ?? 'caddy',\n args: ['run', '--config', configPath, '--adapter', 'caddyfile'],\n ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),\n env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },\n },\n ],\n options.supervisor ?? {},\n ['proxy', 'app', 'realtime'],\n )\n}\n\nexport function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv {\n const apiKey = requiredValue(options.apiKey, 'apiKey')\n const clientTokenSecret = options.clientTokenSecret?.trim()\n const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim()\n return {\n CENTRIFUGO_HTTP_API_KEY: apiKey,\n CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',\n CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',\n CENTRIFUGO_HEALTH_ENABLED: 'true',\n ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),\n ...(subscriptionTokenSecret\n ? {\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,\n }\n : {}),\n ...(options.redisUrl\n ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }\n : {}),\n }\n}\n\nexport type CaddyRuntimeEnvironmentOptions = { configHome?: string; dataHome?: string }\n\nexport function caddyRuntimeEnvironment(options: CaddyRuntimeEnvironmentOptions = {}): NodeJS.ProcessEnv {\n const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome')\n const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome')\n return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome }\n}\n\nexport type CaddyRealtimeProxyOptions = {\n publicPort?: number\n appPort?: number\n realtimePort?: number\n websocketPath?: string\n /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */\n encode?: boolean\n}\n\nexport function caddyRealtimeProxy(options: CaddyRealtimeProxyOptions = {}) {\n const publicPort = port(options.publicPort ?? 3000, 'publicPort')\n const appPort = port(options.appPort ?? 3001, 'appPort')\n const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort')\n const websocketPath = options.websocketPath ?? '/connection/'\n if (!/^\\/[A-Za-z0-9._~/-]+\\/$/.test(websocketPath) || websocketPath.includes('//')) {\n throw new Error('websocketPath must be a normalized absolute directory path')\n }\n return `{\n\\tservers {\n\\t\\ttrusted_proxies static private_ranges\n\\t\\ttrusted_proxies_strict\n\\t}\n}\n\n:${publicPort} {\n${options.encode === false ? '' : '\\tencode zstd gzip\\n'}\\troute {\n\\t\\t@foreignWebSocketOrigin \\`{path}.startsWith('${websocketPath}') && {http.request.header.Origin} != '' && {http.request.header.Origin} != 'http://' + {http.request.hostport} && {http.request.header.Origin} != 'https://' + {http.request.hostport}\\`\n\\t\\trespond @foreignWebSocketOrigin 403\n\n\\t\\thandle ${websocketPath}* {\n\\t\\t\\treverse_proxy 127.0.0.1:${realtimePort}\n\\t\\t}\n\n\\t\\thandle {\n\\t\\t\\treverse_proxy 127.0.0.1:${appPort}\n\\t\\t}\n\\t}\n}\n`\n}\n\nexport function requiredValue(value: string | undefined, name: string) {\n const normalized = value?.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nexport function port(value: number, name: string) {\n if (!Number.isInteger(value) || value < 1 || value > 65_535) throw new Error(`${name} must be a valid TCP port`)\n return value\n}\n\nfunction absolutePath(value: string, name: string) {\n if (!path.isAbsolute(value)) throw new Error(`${name} must be an absolute path`)\n return value\n}\n\nexport type PersistedRealtimeSecretOptions = { prefix?: string; defaultFile?: string }\n\n// The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.\nexport function persistedRealtimeSecret(environment: NodeJS.ProcessEnv = process.env, options: PersistedRealtimeSecretOptions = {}) {\n const prefix = options.prefix ?? ''\n const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret'\n const secret = persistedSecret({\n directory: path.dirname(file),\n filename: path.basename(file),\n environment,\n environmentKey: `${prefix}REALTIME_SECRET`,\n bytes: 48,\n })\n environment[`${prefix}REALTIME_SECRET`] = secret\n return secret\n}\n"]}
@@ -3,3 +3,4 @@ export type CanonicalRedirectOptions = {
3
3
  pathsServedOnAnyHost?: ReadonlySet<string>;
4
4
  };
5
5
  export declare function canonicalRedirect(requestUrl: string, options: CanonicalRedirectOptions): string | null;
6
+ export declare function loopback(hostname: string): boolean;
@@ -17,7 +17,7 @@ export function canonicalRedirect(requestUrl, options) {
17
17
  return null;
18
18
  }
19
19
  }
20
- function loopback(hostname) {
20
+ export function loopback(hostname) {
21
21
  return hostname === 'localhost' || hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
22
22
  }
23
23
  //# sourceMappingURL=canonical-host.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"canonical-host.js","sourceRoot":"","sources":["../../src/server/canonical-host.ts"],"names":[],"mappings":"AAKA,MAAM,UAAU,iBAAiB,CAAC,UAAkB,EAAE,OAAiC;IACrF,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,EAAE;QAAE,OAAO,IAAI,CAAA;IAC9C,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;QAC/C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;QACpC,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,IAAI,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QACzG,uGAAuG;QACvG,qGAAqG;QACrG,+EAA+E;QAC/E,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QAC5C,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAA;IAClG,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,QAAgB;IAChC,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,OAAO,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;AACnG,CAAC","sourcesContent":["export type CanonicalRedirectOptions = {\n canonicalUrl?: string\n pathsServedOnAnyHost?: ReadonlySet<string>\n}\n\nexport function canonicalRedirect(requestUrl: string, options: CanonicalRedirectOptions) {\n if (!options.canonicalUrl?.trim()) return null\n try {\n const canonical = new URL(options.canonicalUrl)\n const incoming = new URL(requestUrl)\n if (incoming.host === canonical.host || options.pathsServedOnAnyHost?.has(incoming.pathname)) return null\n // A sibling process calling over the loopback interface is not a visitor who typed the wrong hostname.\n // Redirecting it sends an internal request out to the public name, and its client may not follow the\n // redirect, may drop the method, or may not be able to reach that name at all.\n if (loopback(incoming.hostname)) return null\n return new URL(incoming.pathname + incoming.search + incoming.hash, canonical.origin).toString()\n } catch {\n return null\n }\n}\n\nfunction loopback(hostname: string) {\n return hostname === 'localhost' || hostname === '[::1]' || /^127(?:\\.\\d{1,3}){3}$/.test(hostname)\n}\n"]}
1
+ {"version":3,"file":"canonical-host.js","sourceRoot":"","sources":["../../src/server/canonical-host.ts"],"names":[],"mappings":"AAKA,MAAM,UAAU,iBAAiB,CAAC,UAAkB,EAAE,OAAiC;IACrF,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,EAAE;QAAE,OAAO,IAAI,CAAA;IAC9C,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;QAC/C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;QACpC,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,IAAI,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QACzG,uGAAuG;QACvG,qGAAqG;QACrG,+EAA+E;QAC/E,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QAC5C,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAA;IAClG,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,QAAgB;IACvC,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,OAAO,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;AACnG,CAAC","sourcesContent":["export type CanonicalRedirectOptions = {\n canonicalUrl?: string\n pathsServedOnAnyHost?: ReadonlySet<string>\n}\n\nexport function canonicalRedirect(requestUrl: string, options: CanonicalRedirectOptions) {\n if (!options.canonicalUrl?.trim()) return null\n try {\n const canonical = new URL(options.canonicalUrl)\n const incoming = new URL(requestUrl)\n if (incoming.host === canonical.host || options.pathsServedOnAnyHost?.has(incoming.pathname)) return null\n // A sibling process calling over the loopback interface is not a visitor who typed the wrong hostname.\n // Redirecting it sends an internal request out to the public name, and its client may not follow the\n // redirect, may drop the method, or may not be able to reach that name at all.\n if (loopback(incoming.hostname)) return null\n return new URL(incoming.pathname + incoming.search + incoming.hash, canonical.origin).toString()\n } catch {\n return null\n }\n}\n\nexport function loopback(hostname: string) {\n return hostname === 'localhost' || hostname === '[::1]' || /^127(?:\\.\\d{1,3}){3}$/.test(hostname)\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { loopback } from '../server/canonical-host.js';
1
2
  export class SpacetimeRequestError extends Error {
2
3
  status;
3
4
  constructor(status, message) {
@@ -9,7 +10,7 @@ export class SpacetimeRequestError extends Error {
9
10
  export function spacetimeDatabaseUrl(connection, path = '') {
10
11
  const base = new URL(connection.url);
11
12
  const internal = /^[a-z][a-z0-9-]{1,63}$/.test(connection.internalHost ?? '') && base.hostname === connection.internalHost;
12
- const local = base.protocol === 'http:' && (['localhost', '127.0.0.1'].includes(base.hostname) || internal);
13
+ const local = base.protocol === 'http:' && (loopback(base.hostname) || internal);
13
14
  if ((!local && base.protocol !== 'https:') || base.username || base.password || base.search || base.hash || base.pathname !== '/') {
14
15
  throw new Error('Invalid SpacetimeDB URL');
15
16
  }