web.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. /**
  2. * `dsh web` — the browser-surface alias over the profile boot: `--profile web`
  3. * plus the Web flag family (`--host/--port/--dev/--trusted-host`), each flag
  4. * becoming a patch over the composed profile
  5. * tree. All web runtime glue (dist serving, prompt section, URL line) lives
  6. * in the `@deepseek-ai/dsh-web-app` bundle; this launcher only derives
  7. * flag patches and the LAN-trust snapshot.
  8. * @module @deepseek-ai/dsh/web
  9. */
  10. import { networkInterfaces } from 'node:os'
  11. import { fileURLToPath } from 'node:url'
  12. import type { Context } from 'cordis'
  13. import type { PatchOptions } from '@cordisjs/plugin-include'
  14. import { addHarnessSourceSection } from '@deepseek-ai/dsh-app-boot'
  15. import { runProfile, type ProfileRows } from './profile-boot.ts'
  16. const SOURCE_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  17. /** The webserver schema's all-interfaces bind literal: gates LAN-authority derivation. */
  18. const ALL_INTERFACES_HOST = '0.0.0.0'
  19. /**
  20. * Non-internal IPv4 interface addresses of this machine — the IP-literal
  21. * authorities an all-interfaces bind is reachable by on the LAN.
  22. * @returns the addresses in interface order (possibly empty).
  23. */
  24. function lanIPv4Addresses(): string[] {
  25. return Object.values(networkInterfaces()).flat()
  26. .filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
  27. .map(iface => iface.address)
  28. }
  29. /**
  30. * One LAN-trust resolution for one invocation, sampled exactly once: the
  31. * machine's LAN IP literals when the effective bind is all-interfaces, and
  32. * the `trustedHosts` value built from them plus the explicit extras. The
  33. * single sample is deliberate — display must advertise only addresses the
  34. * fence was configured with, so the web-app row receives this same snapshot.
  35. * Derived entries are port-less IP literals: DNS rebinding needs an
  36. * attacker-controlled name, so an IP-literal Host is safe on any port, and
  37. * the bound port may be OS-assigned, unknowable pre-boot.
  38. * @param bindHost - the effective webserver bind host (CLI flag, else the composed row value).
  39. * @param extra - `--trusted-host` values, in argv order.
  40. * @returns the sampled LAN addresses and the connection row's `trustedHosts` value (each possibly empty).
  41. */
  42. export function resolveLanTrust(
  43. bindHost: string | undefined,
  44. extra: readonly string[],
  45. ): { lanAddresses: string[]; trustedHosts: string[] } {
  46. const lanAddresses = bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : []
  47. return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
  48. }
  49. /** The `dsh web` flag family, already parsed by the argument adapter. */
  50. export interface WebFlags {
  51. patches: string[]
  52. host?: string
  53. port?: number
  54. dev: boolean
  55. trustedHosts?: string[]
  56. }
  57. /**
  58. * Derive the web alias's flag patches over an already-composed profile tree.
  59. * Patches replace a row's whole config, so each patched row's composed values
  60. * are re-read and merged under the overrides.
  61. * @param rows - the composed row index from {@link composeProfile}.
  62. * @param flags - the parsed flag family.
  63. * @returns the flag patch list, in application order.
  64. */
  65. function deriveWebFlagPatches(
  66. rows: ProfileRows,
  67. flags: WebFlags,
  68. ): PatchOptions[] {
  69. const overrides = new Map<string, Record<string, unknown>>()
  70. const put = (entryId: string, key: string, value: unknown): void => {
  71. const bag = overrides.get(entryId) ?? {}
  72. bag[key] = value
  73. overrides.set(entryId, bag)
  74. }
  75. if (flags.host !== undefined) put('webserver', 'host', flags.host)
  76. if (flags.port !== undefined) put('webserver', 'port', flags.port)
  77. const composedHost = (rows.get('webserver')?.config as { host?: string } | undefined)?.host
  78. const { lanAddresses, trustedHosts } = resolveLanTrust(flags.host ?? composedHost, flags.trustedHosts ?? [])
  79. if (trustedHosts.length > 0) {
  80. // Additive over the composed value: a cordis.patch.yml-configured fence
  81. // authority must survive the derived LAN literals and flag extras — a
  82. // silent drop of security-relevant fence configuration.
  83. const composedTrusted = (rows.get('connection')?.config as { trustedHosts?: string[] } | undefined)?.trustedHosts ?? []
  84. put('connection', 'trustedHosts', [...composedTrusted, ...trustedHosts])
  85. }
  86. // mode and lanAddresses are launcher-derived on every boot (--dev also
  87. // inserts the client-hmr row), never pass-throughs of composed values.
  88. put('web-runtime', 'mode', flags.dev ? 'development' : 'production')
  89. put('web-runtime', 'lanAddresses', lanAddresses)
  90. const patches = [...overrides.entries()].map(([id, bag]): PatchOptions => {
  91. const composed = rows.get(id)
  92. if (composed === undefined) throw new Error(`dsh: patch target row "${id}" not found in the web profile composition`)
  93. return { id, config: { ...(composed.config ?? {}) as Record<string, unknown>, ...bag } }
  94. })
  95. if (flags.dev) patches.push({ insert: [{ id: 'client-hmr', name: '@deepseek-ai/dsh-client-hmr' }] })
  96. return patches
  97. }
  98. /**
  99. * Whether the composed Web runtime keeps its model- and shell-visible surface
  100. * context. The bundle schema defaults the field to true, so only an explicit
  101. * false suppresses both the bundle contributions and the launcher-owned
  102. * source-checkout section.
  103. * @param rows - the composed Web profile rows before launcher flag patches.
  104. * @returns true unless the web-runtime row explicitly disables surface context.
  105. */
  106. export function webSurfaceContextEnabled(rows: ProfileRows): boolean {
  107. return (rows.get('web-runtime')?.config as { surfaceContext?: boolean } | undefined)?.surfaceContext !== false
  108. }
  109. /**
  110. * Serve the browser UI from the web profile. Host/port flags are passed
  111. * through only when given (absent, the composed profile values
  112. * stand); `web-runtime.mode` and `lanAddresses` are launcher-derived on
  113. * every boot. The URL line is printed by the web-app bundle's runtime row
  114. * after Loader settlement.
  115. * @param flags - the parsed `dsh web` flag family.
  116. */
  117. export async function runWeb(flags: WebFlags): Promise<void> {
  118. await runProfile({
  119. profile: 'web',
  120. patchFiles: flags.patches,
  121. deriveFlagPatches: rows => deriveWebFlagPatches(rows, flags),
  122. prepare: (ctx: Context, rows: ProfileRows) => {
  123. if (!webSurfaceContextEnabled(rows)) return
  124. ctx.inject(['systemPrompt'], (promptCtx) => {
  125. addHarnessSourceSection(promptCtx, SOURCE_ROOT)
  126. })
  127. },
  128. })
  129. }