@rocicorp/zero 1.4.0-canary.6 → 1.5.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/out/zero/package.js +1 -1
  2. package/out/zero/package.js.map +1 -1
  3. package/out/zero-cache/src/auth/auth.d.ts +1 -1
  4. package/out/zero-cache/src/auth/auth.d.ts.map +1 -1
  5. package/out/zero-cache/src/auth/auth.js +1 -1
  6. package/out/zero-cache/src/auth/auth.js.map +1 -1
  7. package/out/zero-cache/src/auth/write-authorizer.d.ts +1 -1
  8. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  9. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  10. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  11. package/out/zero-cache/src/config/normalize.js +8 -0
  12. package/out/zero-cache/src/config/normalize.js.map +1 -1
  13. package/out/zero-cache/src/config/zero-config.d.ts +8 -4
  14. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  15. package/out/zero-cache/src/config/zero-config.js +28 -6
  16. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  17. package/out/zero-cache/src/custom/fetch.d.ts +1 -1
  18. package/out/zero-cache/src/custom/fetch.d.ts.map +1 -1
  19. package/out/zero-cache/src/custom/fetch.js +2 -2
  20. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  21. package/out/zero-cache/src/custom-queries/transform-query.d.ts +21 -7
  22. package/out/zero-cache/src/custom-queries/transform-query.d.ts.map +1 -1
  23. package/out/zero-cache/src/custom-queries/transform-query.js +26 -9
  24. package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
  25. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  26. package/out/zero-cache/src/server/change-streamer.js +2 -1
  27. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  28. package/out/zero-cache/src/server/runner/run-worker.d.ts.map +1 -1
  29. package/out/zero-cache/src/server/runner/run-worker.js +5 -2
  30. package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
  31. package/out/zero-cache/src/server/syncer.js +3 -3
  32. package/out/zero-cache/src/server/syncer.js.map +1 -1
  33. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  34. package/out/zero-cache/src/services/change-source/pg/change-source.js +24 -20
  35. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  36. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +258 -45
  37. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  38. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +119 -83
  39. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  40. package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
  41. package/out/zero-cache/src/services/change-source/pg/schema/init.js +1 -1
  42. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  43. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +2 -1
  45. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  46. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +1 -0
  47. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  48. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  49. package/out/zero-cache/src/services/http-service.d.ts +1 -0
  50. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  51. package/out/zero-cache/src/services/http-service.js +5 -4
  52. package/out/zero-cache/src/services/http-service.js.map +1 -1
  53. package/out/zero-cache/src/services/life-cycle.d.ts +1 -1
  54. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  55. package/out/zero-cache/src/services/life-cycle.js +1 -2
  56. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  57. package/out/zero-cache/src/services/mutagen/mutagen.d.ts +1 -1
  58. package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
  59. package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
  60. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  61. package/out/zero-cache/src/services/mutagen/pusher.d.ts +4 -3
  62. package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
  63. package/out/zero-cache/src/services/mutagen/pusher.js +57 -38
  64. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  65. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js +2 -1
  66. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js.map +1 -1
  67. package/out/zero-cache/src/services/view-syncer/client-handler.js +1 -1
  68. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  69. package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts +39 -27
  70. package/out/zero-cache/src/services/view-syncer/connection-context-manager.d.ts.map +1 -1
  71. package/out/zero-cache/src/services/view-syncer/connection-context-manager.js +138 -102
  72. package/out/zero-cache/src/services/view-syncer/connection-context-manager.js.map +1 -1
  73. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +6 -0
  74. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/view-syncer/cvr.js +8 -0
  76. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  77. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +3 -3
  78. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  79. package/out/zero-cache/src/services/view-syncer/view-syncer.js +115 -86
  80. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  81. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts +1 -1
  82. package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
  83. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +7 -7
  84. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  85. package/out/zero-cache/src/workers/syncer.d.ts +1 -1
  86. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  87. package/out/zero-cache/src/workers/syncer.js +11 -10
  88. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  89. package/out/zero-client/src/client/connection.d.ts +15 -7
  90. package/out/zero-client/src/client/connection.d.ts.map +1 -1
  91. package/out/zero-client/src/client/connection.js.map +1 -1
  92. package/out/zero-client/src/client/crud-impl.d.ts +1 -1
  93. package/out/zero-client/src/client/crud-impl.d.ts.map +1 -1
  94. package/out/zero-client/src/client/crud-impl.js +1 -1
  95. package/out/zero-client/src/client/crud-impl.js.map +1 -1
  96. package/out/zero-client/src/client/crud.d.ts +1 -1
  97. package/out/zero-client/src/client/crud.d.ts.map +1 -1
  98. package/out/zero-client/src/client/crud.js +1 -1
  99. package/out/zero-client/src/client/crud.js.map +1 -1
  100. package/out/zero-client/src/client/keys.d.ts +1 -1
  101. package/out/zero-client/src/client/keys.d.ts.map +1 -1
  102. package/out/zero-client/src/client/keys.js.map +1 -1
  103. package/out/zero-client/src/client/make-replicache-mutators.js +1 -1
  104. package/out/zero-client/src/client/make-replicache-mutators.js.map +1 -1
  105. package/out/zero-client/src/client/mutation-tracker.d.ts +2 -1
  106. package/out/zero-client/src/client/mutation-tracker.d.ts.map +1 -1
  107. package/out/zero-client/src/client/mutation-tracker.js +3 -3
  108. package/out/zero-client/src/client/mutation-tracker.js.map +1 -1
  109. package/out/zero-client/src/client/version.js +1 -1
  110. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  111. package/out/zero-client/src/client/zero.js +2 -2
  112. package/out/zero-client/src/client/zero.js.map +1 -1
  113. package/out/zero-client/src/types/client-state.d.ts +1 -1
  114. package/out/zero-client/src/types/client-state.d.ts.map +1 -1
  115. package/out/zero-protocol/src/custom-queries.js +1 -1
  116. package/out/zero-protocol/src/down.js +1 -1
  117. package/out/zero-protocol/src/error-kind-enum.d.ts +1 -2
  118. package/out/zero-protocol/src/error-kind-enum.d.ts.map +1 -1
  119. package/out/zero-protocol/src/error-kind-enum.js.map +1 -1
  120. package/out/zero-protocol/src/mutate-server.d.ts +165 -0
  121. package/out/zero-protocol/src/mutate-server.d.ts.map +1 -0
  122. package/out/zero-protocol/src/mutate-server.js +24 -0
  123. package/out/zero-protocol/src/mutate-server.js.map +1 -0
  124. package/out/zero-protocol/src/mutation.d.ts +229 -0
  125. package/out/zero-protocol/src/mutation.d.ts.map +1 -0
  126. package/out/zero-protocol/src/mutation.js +112 -0
  127. package/out/zero-protocol/src/mutation.js.map +1 -0
  128. package/out/zero-protocol/src/mutations-patch.js +1 -1
  129. package/out/zero-protocol/src/mutations-patch.js.map +1 -1
  130. package/out/zero-protocol/src/push.d.ts +3 -234
  131. package/out/zero-protocol/src/push.d.ts.map +1 -1
  132. package/out/zero-protocol/src/push.js +3 -114
  133. package/out/zero-protocol/src/push.js.map +1 -1
  134. package/out/zero-protocol/src/query-server.d.ts +150 -0
  135. package/out/zero-protocol/src/query-server.d.ts.map +1 -0
  136. package/out/zero-protocol/src/query-server.js +16 -0
  137. package/out/zero-protocol/src/query-server.js.map +1 -0
  138. package/out/zero-protocol/src/up.js +1 -1
  139. package/out/zero-server/src/mod.d.ts +4 -2
  140. package/out/zero-server/src/mod.d.ts.map +1 -1
  141. package/out/zero-server/src/process-mutations.d.ts +41 -4
  142. package/out/zero-server/src/process-mutations.d.ts.map +1 -1
  143. package/out/zero-server/src/process-mutations.js +52 -35
  144. package/out/zero-server/src/process-mutations.js.map +1 -1
  145. package/out/zero-server/src/push-processor.d.ts +3 -3
  146. package/out/zero-server/src/push-processor.d.ts.map +1 -1
  147. package/out/zero-server/src/push-processor.js.map +1 -1
  148. package/out/zero-server/src/queries/process-queries.d.ts +22 -52
  149. package/out/zero-server/src/queries/process-queries.d.ts.map +1 -1
  150. package/out/zero-server/src/queries/process-queries.js +50 -49
  151. package/out/zero-server/src/queries/process-queries.js.map +1 -1
  152. package/out/zero-server/src/zql-database.js.map +1 -1
  153. package/out/zero-types/src/default-types.d.ts +1 -0
  154. package/out/zero-types/src/default-types.d.ts.map +1 -1
  155. package/out/zql/src/builder/builder.d.ts.map +1 -1
  156. package/out/zql/src/builder/builder.js +17 -7
  157. package/out/zql/src/builder/builder.js.map +1 -1
  158. package/out/zql/src/ivm/cap.d.ts +32 -0
  159. package/out/zql/src/ivm/cap.d.ts.map +1 -0
  160. package/out/zql/src/ivm/cap.js +205 -0
  161. package/out/zql/src/ivm/cap.js.map +1 -0
  162. package/out/zql/src/ivm/constraint.js +1 -1
  163. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  164. package/out/zql/src/ivm/flipped-join.js +61 -15
  165. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  166. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  167. package/out/zql/src/ivm/memory-source.js +3 -4
  168. package/out/zql/src/ivm/memory-source.js.map +1 -1
  169. package/out/zql/src/ivm/schema.d.ts +8 -0
  170. package/out/zql/src/ivm/schema.d.ts.map +1 -1
  171. package/out/zql/src/ivm/take.js +2 -2
  172. package/out/zql/src/mutate/mutator-registry.js.map +1 -1
  173. package/out/zql/src/mutate/mutator.d.ts +11 -2
  174. package/out/zql/src/mutate/mutator.d.ts.map +1 -1
  175. package/out/zql/src/mutate/mutator.js.map +1 -1
  176. package/out/zql/src/query/query-registry.d.ts +9 -2
  177. package/out/zql/src/query/query-registry.d.ts.map +1 -1
  178. package/out/zql/src/query/query-registry.js.map +1 -1
  179. package/out/zqlite/src/table-source.d.ts.map +1 -1
  180. package/out/zqlite/src/table-source.js +4 -1
  181. package/out/zqlite/src/table-source.js.map +1 -1
  182. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@rocicorp/zero",
3
- version: "1.4.0-canary.6",
3
+ version: "1.5.0-canary.0",
4
4
  description: "Zero is a web framework for serverless web development.",
5
5
  homepage: "https://zero.rocicorp.dev",
6
6
  bugs: { "url": "https://bugs.rocicorp.dev" },
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.4.0-canary.6\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.17\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\",\n \"kysely\": \"^0.28.16\"\n },\n \"peerDependenciesMeta\": {\n \"kysely\": {\n \"optional\": true\n },\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=22\"\n }\n}"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.5.0-canary.0\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.17\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\",\n \"kysely\": \"^0.28.16\"\n },\n \"peerDependenciesMeta\": {\n \"kysely\": {\n \"optional\": true\n },\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=22\"\n }\n}"],"mappings":""}
@@ -20,7 +20,7 @@ export declare function authEquals(a: Auth | undefined, b: Auth | undefined): bo
20
20
  /**
21
21
  * Resolves one auth snapshot transition without binding it to a client group.
22
22
  */
23
- export declare function resolveAuth(lc: LogContext, previousAuth: Auth | undefined, userID: string | undefined, wireAuth: string | undefined, validateLegacyJWT: ValidateLegacyJWT | undefined): Promise<Auth | undefined>;
23
+ export declare function resolveAuth(lc: LogContext, previousAuth: Auth | undefined, userID: string | null, wireAuth: string | undefined, validateLegacyJWT: ValidateLegacyJWT | undefined): Promise<Auth | undefined>;
24
24
  /** @deprecated used only in old JWT validation/rotation auth */
25
25
  export declare function pickToken(lc: LogContext, previousToken: Auth | undefined, newToken: Auth | undefined | null): Auth | undefined;
26
26
  export declare function isAuthErrorBody(ex: unknown): ex is ErrorBody | PushError;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/auth/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,MAAM,CAAC;AAIrC,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,oCAAoC,CAAC;AAElE,yCAAyC;AACzC,MAAM,MAAM,OAAO,GAAG;IACpB,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM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28
28
  lc.debug?.(`Cleared auth`);
29
29
  return;
30
30
  }
31
- if (userID === void 0) throw new ProtocolError({
31
+ if (userID === null) throw new ProtocolError({
32
32
  kind: Unauthorized,
33
33
  message: "Authenticated connections require a userID.",
34
34
  origin: ZeroCache
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","names":[],"sources":["../../../../../zero-cache/src/auth/auth.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n isProtocolError,\n ProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport type {PushError} from '../../../zero-protocol/src/push.ts';\n\n/** @deprecated JWT auth is deprecated */\nexport type JWTAuth = {\n readonly type: 'jwt';\n readonly raw: string;\n readonly decoded: JWTPayload;\n};\n\nexport type OpaqueAuth = {\n readonly type: 'opaque';\n readonly raw: string;\n};\n\nexport type Auth = OpaqueAuth | JWTAuth;\n\nexport type ValidateLegacyJWT = (\n token: string,\n ctx: {readonly userID: string | undefined},\n) => Promise<JWTAuth>;\n\nfunction isProvidedAuth(wireAuth: string | undefined): wireAuth is string {\n return wireAuth !== undefined && wireAuth !== '';\n}\n\nexport function authEquals(a: Auth | undefined, b: Auth | undefined) {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n return a.type === b.type && a.raw === b.raw;\n}\n\n/**\n * Resolves one auth snapshot transition without binding it to a client group.\n */\nexport async function resolveAuth(\n lc: LogContext,\n previousAuth: Auth | undefined,\n userID: string | undefined,\n wireAuth: string | undefined,\n validateLegacyJWT: ValidateLegacyJWT | undefined,\n): Promise<Auth | undefined> {\n try {\n const hasProvidedAuth = isProvidedAuth(wireAuth);\n\n if (previousAuth) {\n lc.debug?.(`Attempting to update auth from previous value`);\n } else {\n lc.debug?.(`Attempting to initialize auth`);\n }\n\n if (!hasProvidedAuth && previousAuth) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'No token provided. An unauthenticated client cannot connect to an authenticated client group.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (!hasProvidedAuth) {\n lc.debug?.(`Cleared auth`);\n return undefined;\n }\n\n if (userID === undefined) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message: 'Authenticated connections require a userID.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (validateLegacyJWT !== undefined) {\n const verifiedToken = await validateLegacyJWT(wireAuth, {userID});\n const nextAuth = pickToken(lc, previousAuth, verifiedToken);\n lc.debug?.(`Updated auth with JWT`);\n return nextAuth;\n }\n\n if (previousAuth?.type === 'jwt') {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change from JWT to opaque. Connections are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousAuth?.type === 'opaque' && previousAuth.raw === wireAuth) {\n lc.debug?.(`Opaque auth unchanged, reusing previous snapshot`);\n return previousAuth;\n }\n\n lc.debug?.(`Updated auth with opaque token`);\n return {\n type: 'opaque',\n raw: wireAuth,\n };\n } catch (e) {\n if (isProtocolError(e)) {\n throw e;\n }\n throw new ProtocolError({\n kind: ErrorKind.AuthInvalidated,\n message: `Failed to decode auth token: ${String(e)}`,\n origin: ErrorOrigin.ZeroCache,\n });\n }\n}\n\n/** @deprecated used only in old JWT validation/rotation auth */\nexport function pickToken(\n lc: LogContext,\n previousToken: Auth | undefined,\n newToken: Auth | undefined | null,\n) {\n if (newToken === null) {\n return undefined;\n }\n\n if (\n previousToken?.type &&\n newToken?.type &&\n previousToken?.type !== newToken?.type\n ) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change. Client groups are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousToken === undefined) {\n lc.debug?.(`No previous token, using new token`);\n return newToken;\n }\n\n if (newToken?.type === 'opaque') {\n return newToken;\n }\n\n if (previousToken.type === 'opaque') {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change from opaque to JWT. Client groups are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (newToken) {\n if (previousToken.decoded.sub !== newToken.decoded.sub) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'The user id in the new token does not match the previous token. Client groups are pinned to a single user.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousToken.decoded.iat === undefined) {\n lc.debug?.(`No issued at time for the existing token, using new token`);\n // No issued at time for the existing token? We take the most recently received token.\n return newToken;\n }\n\n if (newToken.decoded.iat === undefined) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'The new token does not have an issued at time but the prior token does. Tokens for a client group must either all have issued at times or all not have issued at times',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n // The new token is newer, so we take it.\n if (previousToken.decoded.iat < newToken.decoded.iat) {\n lc.debug?.(`New token is newer, using it`);\n return newToken;\n }\n\n // if the new token is older or the same, we keep the existing token.\n lc.debug?.(`New token is older or the same, using existing token`);\n return previousToken;\n }\n\n // previousToken !== undefined but newToken is undefined\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'No token provided. An unauthenticated client cannot connect to an authenticated client group.',\n origin: ErrorOrigin.ZeroCache,\n });\n}\n\nexport function isAuthErrorBody(ex: unknown): ex is ErrorBody | PushError {\n if (typeof ex !== 'object' || ex === null) {\n return false;\n }\n\n if ('error' in ex) {\n return (\n ex.error === 'http' &&\n 'status' in ex &&\n (ex.status === 401 || ex.status === 403)\n );\n }\n\n if (!('kind' in ex)) {\n return false;\n }\n\n if (\n ex.kind === ErrorKind.AuthInvalidated ||\n ex.kind === ErrorKind.Unauthorized\n ) {\n return true;\n }\n\n return (\n (ex.kind === ErrorKind.PushFailed ||\n ex.kind === ErrorKind.TransformFailed) &&\n 'reason' in ex &&\n ex.reason === ErrorReason.HTTP &&\n 'status' in ex &&\n (ex.status === 401 || ex.status === 403)\n );\n}\n"],"mappings":";;;;;AA+BA,SAAS,eAAe,UAAkD;AACxE,QAAO,aAAa,KAAA,KAAa,aAAa;;AAGhD,SAAgB,WAAW,GAAqB,GAAqB;AACnE,KAAI,MAAM,EACR,QAAO;AAET,KAAI,CAAC,KAAK,CAAC,EACT,QAAO;AAET,QAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE;;;;;AAM1C,eAAsB,YACpB,IACA,cACA,QACA,UACA,mBAC2B;AAC3B,KAAI;EACF,MAAM,kBAAkB,eAAe,SAAS;AAEhD,MAAI,aACF,IAAG,QAAQ,gDAAgD;MAE3D,IAAG,QAAQ,gCAAgC;AAG7C,MAAI,CAAC,mBAAmB,aACtB,OAAM,IAAI,cAAc;GACtB,MAAM;GACN,SACE;GACF,QAAQ;GACT,CAAC;AAGJ,MAAI,CAAC,iBAAiB;AACpB,MAAG,QAAQ,eAAe;AAC1B;;AAGF,MAAI,WAAW,KAAA,EACb,OAAM,IAAI,cAAc;GACtB,MAAM;GACN,SAAS;GACT,QAAQ;GACT,CAAC;AAGJ,MAAI,sBAAsB,KAAA,GAAW;GAEnC,MAAM,WAAW,UAAU,IAAI,cADT,MAAM,kBAAkB,UAAU,EAAC,QAAO,CAAC,CACN;AAC3D,MAAG,QAAQ,wBAAwB;AACnC,UAAO;;AAGT,MAAI,cAAc,SAAS,MACzB,OAAM,IAAI,cAAc;GACtB,MAAM;GACN,SACE;GACF,QAAQ;GACT,CAAC;AAGJ,MAAI,cAAc,SAAS,YAAY,aAAa,QAAQ,UAAU;AACpE,MAAG,QAAQ,mDAAmD;AAC9D,UAAO;;AAGT,KAAG,QAAQ,iCAAiC;AAC5C,SAAO;GACL,MAAM;GACN,KAAK;GACN;UACM,GAAG;AACV,MAAI,gBAAgB,EAAE,CACpB,OAAM;A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Z,GAAG,SAAS,eAEZ,QAAO;AAGT,SACG,GAAG,SAAS,gBACX,GAAG,SAAS,sBACd,YAAY,MACZ,GAAG,WAAW,UACd,YAAY,OACX,GAAG,WAAW,OAAO,GAAG,WAAW"}
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../../../../../zero-cache/src/auth/auth.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {\n isProtocolError,\n ProtocolError,\n type ErrorBody,\n} from '../../../zero-protocol/src/error.ts';\nimport type {PushError} from '../../../zero-protocol/src/push.ts';\n\n/** @deprecated JWT auth is deprecated */\nexport type JWTAuth = {\n readonly type: 'jwt';\n readonly raw: string;\n readonly decoded: JWTPayload;\n};\n\nexport type OpaqueAuth = {\n readonly type: 'opaque';\n readonly raw: string;\n};\n\nexport type Auth = OpaqueAuth | JWTAuth;\n\nexport type ValidateLegacyJWT = (\n token: string,\n ctx: {readonly userID: string | undefined},\n) => Promise<JWTAuth>;\n\nfunction isProvidedAuth(wireAuth: string | undefined): wireAuth is string {\n return wireAuth !== undefined && wireAuth !== '';\n}\n\nexport function authEquals(a: Auth | undefined, b: Auth | undefined) {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n return a.type === b.type && a.raw === b.raw;\n}\n\n/**\n * Resolves one auth snapshot transition without binding it to a client group.\n */\nexport async function resolveAuth(\n lc: LogContext,\n previousAuth: Auth | undefined,\n userID: string | null,\n wireAuth: string | undefined,\n validateLegacyJWT: ValidateLegacyJWT | undefined,\n): Promise<Auth | undefined> {\n try {\n const hasProvidedAuth = isProvidedAuth(wireAuth);\n\n if (previousAuth) {\n lc.debug?.(`Attempting to update auth from previous value`);\n } else {\n lc.debug?.(`Attempting to initialize auth`);\n }\n\n if (!hasProvidedAuth && previousAuth) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'No token provided. An unauthenticated client cannot connect to an authenticated client group.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (!hasProvidedAuth) {\n lc.debug?.(`Cleared auth`);\n return undefined;\n }\n\n if (userID === null) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message: 'Authenticated connections require a userID.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (validateLegacyJWT !== undefined) {\n const verifiedToken = await validateLegacyJWT(wireAuth, {userID});\n const nextAuth = pickToken(lc, previousAuth, verifiedToken);\n lc.debug?.(`Updated auth with JWT`);\n return nextAuth;\n }\n\n if (previousAuth?.type === 'jwt') {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change from JWT to opaque. Connections are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousAuth?.type === 'opaque' && previousAuth.raw === wireAuth) {\n lc.debug?.(`Opaque auth unchanged, reusing previous snapshot`);\n return previousAuth;\n }\n\n lc.debug?.(`Updated auth with opaque token`);\n return {\n type: 'opaque',\n raw: wireAuth,\n };\n } catch (e) {\n if (isProtocolError(e)) {\n throw e;\n }\n throw new ProtocolError({\n kind: ErrorKind.AuthInvalidated,\n message: `Failed to decode auth token: ${String(e)}`,\n origin: ErrorOrigin.ZeroCache,\n });\n }\n}\n\n/** @deprecated used only in old JWT validation/rotation auth */\nexport function pickToken(\n lc: LogContext,\n previousToken: Auth | undefined,\n newToken: Auth | undefined | null,\n) {\n if (newToken === null) {\n return undefined;\n }\n\n if (\n previousToken?.type &&\n newToken?.type &&\n previousToken?.type !== newToken?.type\n ) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change. Client groups are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousToken === undefined) {\n lc.debug?.(`No previous token, using new token`);\n return newToken;\n }\n\n if (newToken?.type === 'opaque') {\n return newToken;\n }\n\n if (previousToken.type === 'opaque') {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'Token type cannot change from opaque to JWT. Client groups are pinned to a single token type.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (newToken) {\n if (previousToken.decoded.sub !== newToken.decoded.sub) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'The user id in the new token does not match the previous token. Client groups are pinned to a single user.',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n if (previousToken.decoded.iat === undefined) {\n lc.debug?.(`No issued at time for the existing token, using new token`);\n // No issued at time for the existing token? We take the most recently received token.\n return newToken;\n }\n\n if (newToken.decoded.iat === undefined) {\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'The new token does not have an issued at time but the prior token does. Tokens for a client group must either all have issued at times or all not have issued at times',\n origin: ErrorOrigin.ZeroCache,\n });\n }\n\n // The new token is newer, so we take it.\n if (previousToken.decoded.iat < newToken.decoded.iat) {\n lc.debug?.(`New token is newer, using it`);\n return newToken;\n }\n\n // if the new token is older or the same, we keep the existing token.\n lc.debug?.(`New token is older or the same, using existing token`);\n return previousToken;\n }\n\n // previousToken !== undefined but newToken is undefined\n throw new ProtocolError({\n kind: ErrorKind.Unauthorized,\n message:\n 'No token provided. An unauthenticated client cannot connect to an authenticated client group.',\n origin: ErrorOrigin.ZeroCache,\n });\n}\n\nexport function isAuthErrorBody(ex: unknown): ex is ErrorBody | PushError {\n if (typeof ex !== 'object' || ex === null) {\n return false;\n }\n\n if ('error' in ex) {\n return (\n ex.error === 'http' &&\n 'status' in ex &&\n (ex.status === 401 || ex.status === 403)\n );\n }\n\n if (!('kind' in ex)) {\n return false;\n }\n\n if (\n ex.kind === ErrorKind.AuthInvalidated ||\n ex.kind === ErrorKind.Unauthorized\n ) {\n return true;\n }\n\n return (\n (ex.kind === ErrorKind.PushFailed ||\n ex.kind === ErrorKind.TransformFailed) &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GAAG,SAAS,gBACX,GAAG,SAAS,sBACd,YAAY,MACZ,GAAG,WAAW,UACd,YAAY,OACX,GAAG,WAAW,OAAO,GAAG,WAAW"}
@@ -1,6 +1,6 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { JWTPayload } from 'jose';
3
- import type { CRUDOp, UpsertOp } from '../../../zero-protocol/src/push.ts';
3
+ import type { CRUDOp, UpsertOp } from '../../../zero-protocol/src/mutation.ts';
4
4
  import type { DatabaseStorage } from '../../../zqlite/src/database-storage.ts';
5
5
  import type { Database } from '../../../zqlite/src/db.ts';
6
6
  import type { ZeroConfig } from '../config/zero-config.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"write-authorizer.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/auth/write-authorizer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,MAAM,CAAC;AAUrC,OAAO,KAAK,EACV,MAAM,EAIN,QAAQ,EACT,MAAM,oCAAoC,CAAC;AAkB5C,OAAO,KAAK,EAEV,eAAe,EAChB,MAAM,yCAAyC,CAAC;AACjD,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,2BAA2B,CAAC;AAMxD,OAAO,KAAK,EAAY,UAAU,EAAC,MAAM,0BAA0B,CAAC;AAapE,MAAM,WAAW,eAAe;IAC9B,cAAc,CACZ,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,GAC/B,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,eAAe,CACb,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,GAC/B,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,iBAAiB,IAAI,IAAI,CAAC;IAC1B,YAAY,CAAC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;IAC9B,cAAc,CACZ,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,GAC/B,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,eAAe,CACb,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,GAC/B,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,iBAAiB,IAAI,IAAI,CAAC;IAC1B,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,CAAC;IAEzD;;;OAGG;IACH,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;CACzC;AAED,qBAAa,mBAAoB,YAAW,eAAe;;gBAgBvD,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,OAAO,EAAE,QAAQ,EACjB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,iBAAiB,EAAE,eAAe;IAwBpC,iBAAiB;IAUjB,OAAO;IAID,cAAc,CAClB,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE;IAsB5B,eAAe,CACnB,QAAQ,EAAE,UAAU,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE;IA0ElC,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE;IAuBxD,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI;CAgUxC"}
@@ -1 +1 @@
1
- {"version":3,"file":"write-authorizer.js","names":["#schema","#replica","#builderDelegate","#tableSpecs","#tables","#statementRunner","#lc","#appID","#logConfig","#cgStorage","#config","#getSource","#loadedPermissions","#canUpdate","#canDelete","#requirePreMutationRow","#canInsert","#getPreMutationRow","#timedCanDo","#canDo","#getPrimaryKey","#passesPolicyGroup","#passesPolicy"],"sources":["../../../../../zero-cache/src/auth/write-authorizer.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {MaybePromise} from '@opentelemetry/resources';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {Condition} from '../../../zero-protocol/src/ast.ts';\nimport {\n primaryKeyValueSchema,\n type PrimaryKeyValue,\n} from '../../../zero-protocol/src/primary-key.ts';\nimport type {\n CRUDOp,\n DeleteOp,\n InsertOp,\n UpdateOp,\n UpsertOp,\n} from '../../../zero-protocol/src/push.ts';\nimport type {Policy} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {BuilderDelegate} from '../../../zql/src/builder/builder.ts';\nimport {\n bindStaticParameters,\n buildPipeline,\n} from '../../../zql/src/builder/builder.ts';\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {Query} from '../../../zql/src/query/query.ts';\nimport {newStaticQuery} from '../../../zql/src/query/static-query.ts';\nimport type {\n ClientGroupStorage,\n DatabaseStorage,\n} from '../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {compile, sql} from '../../../zqlite/src/internal/sql.ts';\nimport {\n fromSQLiteTypes,\n TableSource,\n} from '../../../zqlite/src/table-source.ts';\nimport type {LogConfig, ZeroConfig} from '../config/zero-config.ts';\nimport {computeZqlSpecs} from '../db/lite-tables.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {mapLiteDataTypeToZqlSchemaValue} from '../types/lite.ts';\nimport {\n getSchema,\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from './load-permissions.ts';\n\ntype Phase = 'preMutation' | 'postMutation';\n\nexport interface WriteAuthorizer {\n canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n reloadPermissions(): void;\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[];\n\n /**\n * Validates that all table names in the operations exist in the schema.\n * @throws Error if any table name is invalid\n */\n validateTableNames(ops: CRUDOp[]): void;\n}\n\nexport class WriteAuthorizerImpl implements WriteAuthorizer {\n readonly #schema: Schema;\n readonly #replica: Database;\n readonly #builderDelegate: BuilderDelegate;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #tables = new Map<string, TableSource>();\n readonly #statementRunner: StatementRunner;\n readonly #lc: LogContext;\n readonly #appID: string;\n readonly #logConfig: LogConfig;\n readonly #cgStorage: ClientGroupStorage;\n readonly #config: ZeroConfig;\n\n #loadedPermissions: LoadedPermissions | null = null;\n\n constructor(\n lc: LogContext,\n config: ZeroConfig,\n replica: Database,\n appID: string,\n cgID: string,\n writeAuthzStorage: DatabaseStorage,\n ) {\n this.#appID = appID;\n this.#config = config;\n this.#lc = lc.withContext('class', 'WriteAuthorizerImpl');\n this.#logConfig = config.log;\n this.#schema = getSchema(this.#lc, replica);\n this.#replica = replica;\n this.#cgStorage = writeAuthzStorage.createClientGroupStorage(cgID);\n this.#builderDelegate = {\n getSource: name => this.#getSource(name),\n createStorage: () => this.#cgStorage.createStorage(),\n decorateSourceInput: input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n };\n this.#tableSpecs = computeZqlSpecs(this.#lc, replica, {\n includeBackfillingColumns: false,\n });\n this.#statementRunner = new StatementRunner(replica);\n this.reloadPermissions();\n }\n\n reloadPermissions() {\n this.#loadedPermissions = reloadPermissionsIfChanged(\n this.#lc,\n this.#statementRunner,\n this.#appID,\n this.#loadedPermissions,\n this.#config,\n ).permissions;\n }\n\n destroy() {\n this.#cgStorage.destroy();\n }\n\n async canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n // insert does not run pre-mutation checks\n break;\n case 'update':\n if (!(await this.#canUpdate('preMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n if (!(await this.#canDelete('preMutation', authData, op))) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n\n async canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n this.#statementRunner.beginConcurrent();\n let opError: unknown;\n try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(source.push(makeSourceChangeAdd(op.value)));\n break;\n }\n // TODO(mlaw): what if someone updates the same thing twice?\n // TODO(aa): It seems like it will just work? source.push()\n // is going to push the row into the table source, and then the\n // next requirePreMutationRow will just return the row that was\n // pushed in.\n case 'update': {\n consume(\n source.push(\n makeSourceChangeEdit(op.value, this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push(\n makeSourceChangeRemove(this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n }\n }\n\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n if (!(await this.#canInsert('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'update':\n if (!(await this.#canUpdate('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n // delete does not run post-mutation checks.\n break;\n }\n }\n } catch (e) {\n opError = e;\n throw e;\n } finally {\n try {\n this.#statementRunner.rollback();\n } catch (rollbackError) {\n if (opError !== undefined) {\n const combinedError = new Error(\n `canPostMutation failed and rollback also failed: operation error = ${String(opError)}; rollback error = ${String(rollbackError)}`,\n );\n combinedError.cause = opError;\n throw combinedError;\n }\n throw rollbackError;\n }\n }\n\n return true;\n }\n\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[] {\n return ops.map(op => {\n if (op.op === 'upsert') {\n const preMutationRow = this.#getPreMutationRow(op);\n if (preMutationRow) {\n return {\n op: 'update',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return {\n op: 'insert',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return op;\n });\n }\n\n validateTableNames(ops: CRUDOp[]): void {\n for (const op of ops) {\n if (!this.#tableSpecs.has(op.tableName)) {\n throw new Error(`Table '${op.tableName}' is not a valid table.`);\n }\n }\n }\n\n #canInsert(phase: Phase, authData: JWTPayload | undefined, op: InsertOp) {\n return this.#timedCanDo(phase, 'insert', authData, op);\n }\n\n #canUpdate(phase: Phase, authData: JWTPayload | undefined, op: UpdateOp) {\n return this.#timedCanDo(phase, 'update', authData, op);\n }\n\n #canDelete(phase: Phase, authData: JWTPayload | undefined, op: DeleteOp) {\n return this.#timedCanDo(phase, 'delete', authData, op);\n }\n\n /**\n * Gets schema-defined primary key and validates that operation contains required PK values.\n *\n * @returns Record where keys are column names and values are client-provided values\n * @throws Error if operation value is missing required primary key columns\n */\n #getPrimaryKey(\n tableName: string,\n opValue: Record<string, ReadonlyJSONValue | undefined>,\n ): Record<string, ReadonlyJSONValue> {\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const columns = tableSpec.tableSpec.primaryKey;\n\n // Extract primary key values from operation value and validate they exist\n const values: Record<string, ReadonlyJSONValue> = {};\n for (const col of columns) {\n const val = opValue[col];\n if (val === undefined) {\n throw new Error(\n `Primary key column '${col}' is missing from operation value for table ${tableName}`,\n );\n }\n values[col] = val;\n }\n\n return values;\n }\n\n #getSource(tableName: string) {\n let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const {columns, primaryKey} = tableSpec.tableSpec;\n assert(\n primaryKey.length,\n () => `Table ${tableName} must have a primary key`,\n );\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n this.#replica,\n tableName,\n Object.fromEntries(\n Object.entries(columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n [primaryKey[0], ...primaryKey.slice(1)],\n );\n this.#tables.set(tableName, source);\n\n return source;\n }\n\n async #timedCanDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const start = performance.now();\n try {\n const ret = await this.#canDo(phase, action, authData, op);\n return ret;\n } finally {\n this.#lc.info?.(\n 'action:',\n action,\n 'duration:',\n performance.now() - start,\n 'tableName:',\n op.tableName,\n 'primaryKey:',\n op.primaryKey,\n );\n }\n }\n\n /**\n * Evaluation order is from static to dynamic, broad to specific.\n * table -> column -> row -> cell.\n *\n * If any step fails, the entire operation is denied.\n *\n * That is, table rules supersede column rules, which supersede row rules,\n *\n * All steps must allow for the operation to be allowed.\n */\n async #canDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const rules = must(this.#loadedPermissions)?.permissions?.tables?.[\n op.tableName\n ];\n const rowPolicies = rules?.row;\n let rowQuery = newStaticQuery(this.#schema, op.tableName);\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, op.value);\n\n for (const pk in primaryKeyValues) {\n rowQuery = rowQuery.where(pk, '=', primaryKeyValues[pk]);\n }\n\n let applicableRowPolicy: Policy | undefined;\n switch (action) {\n case 'insert':\n if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.insert;\n }\n break;\n case 'update':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.update?.preMutation;\n } else if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.update?.postMutation;\n }\n break;\n case 'delete':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.delete;\n }\n break;\n }\n\n const cellPolicies = rules?.cell;\n const applicableCellPolicies: Policy[] = [];\n if (cellPolicies) {\n for (const [column, policy] of Object.entries(cellPolicies)) {\n if (action === 'update' && op.value[column] === undefined) {\n // If the cell is not being updated, we do not need to check\n // the cell rules.\n continue;\n }\n switch (action) {\n case 'insert':\n if (policy.insert && phase === 'postMutation') {\n applicableCellPolicies.push(policy.insert);\n }\n break;\n case 'update':\n if (phase === 'preMutation' && policy.update?.preMutation) {\n applicableCellPolicies.push(policy.update.preMutation);\n }\n if (phase === 'postMutation' && policy.update?.postMutation) {\n applicableCellPolicies.push(policy.update.postMutation);\n }\n break;\n case 'delete':\n if (policy.delete && phase === 'preMutation') {\n applicableCellPolicies.push(policy.delete);\n }\n break;\n }\n }\n }\n\n if (\n !(await this.#passesPolicyGroup(\n applicableRowPolicy,\n applicableCellPolicies,\n authData,\n rowQuery,\n ))\n ) {\n this.#lc.warn?.(\n `Permission check failed for ${JSON.stringify(\n op,\n )}, action ${action}, phase ${phase}, authData: ${JSON.stringify(\n authData,\n )}, rowPolicies: ${JSON.stringify(\n applicableRowPolicy,\n )}, cellPolicies: ${JSON.stringify(applicableCellPolicies)}`,\n );\n return false;\n }\n\n return true;\n }\n\n #getPreMutationRow(op: UpsertOp | UpdateOp | DeleteOp) {\n const {value} = op;\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, value);\n\n const spec = this.#tableSpecs.get(op.tableName);\n if (!spec) {\n throw new Error(`Table ${op.tableName} not found`);\n }\n\n const conditions: SQLQuery[] = [];\n const values: PrimaryKeyValue[] = [];\n for (const pk in primaryKeyValues) {\n conditions.push(sql`${sql.ident(pk)}=?`);\n values.push(v.parse(primaryKeyValues[pk], primaryKeyValueSchema));\n }\n\n const ret = this.#statementRunner.get(\n compile(\n sql`SELECT ${sql.join(\n Object.keys(spec.zqlSpec).map(c => sql.ident(c)),\n sql`,`,\n )} FROM ${sql.ident(op.tableName)} WHERE ${sql.join(\n conditions,\n sql` AND `,\n )}`,\n ),\n ...values,\n );\n if (ret === undefined) {\n return ret;\n }\n return fromSQLiteTypes(spec.zqlSpec, ret, op.tableName);\n }\n\n #requirePreMutationRow(op: UpdateOp | DeleteOp) {\n const ret = this.#getPreMutationRow(op);\n assert(\n ret !== undefined,\n () => `Pre-mutation row not found for ${JSON.stringify(op.value)}`,\n );\n return ret;\n }\n\n async #passesPolicyGroup(\n applicableRowPolicy: Policy | undefined,\n applicableCellPolicies: Policy[],\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ) {\n if (!(await this.#passesPolicy(applicableRowPolicy, authData, rowQuery))) {\n return false;\n }\n\n for (const policy of applicableCellPolicies) {\n if (!(await this.#passesPolicy(policy, authData, rowQuery))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Defaults to *false* if the policy is empty. At least one rule has to pass\n * for the policy to pass.\n */\n #passesPolicy(\n policy: Policy | undefined,\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ): MaybePromise<boolean> {\n if (policy === undefined) {\n return false;\n }\n if (policy.length === 0) {\n return false;\n }\n let rowQueryAst = asQueryInternals(rowQuery).ast;\n rowQueryAst = bindStaticParameters(\n {\n ...rowQueryAst,\n where: updateWhere(rowQueryAst.where, policy),\n },\n {\n authData: authData as Record<string, JSONValue>,\n preMutationRow: undefined,\n },\n );\n\n // call the compiler directly\n // run the sql against upstream.\n // remove the collecting into json? just need to know if a row comes back.\n\n const input = buildPipeline(rowQueryAst, this.#builderDelegate, 'query-id');\n try {\n const res = input.fetch({});\n for (const _ of res) {\n // if any row is returned at all, the\n // rule passes.\n return true;\n }\n } finally {\n input.destroy();\n }\n\n // no rows returned by any rules? The policy fails.\n return false;\n }\n}\n\nfunction updateWhere(where: Condition | undefined, policy: Policy) {\n assert(where, 'A where condition must exist for RowQuery');\n\n return simplifyCondition({\n type: 'and',\n conditions: [\n where,\n {\n type: 'or',\n conditions: policy.map(([action, rule]) => {\n assert(action, 'action must be defined in policy');\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA+EA,IAAa,sBAAb,MAA4D;CAC1D;CACA;CACA;CACA;CACA,0BAAmB,IAAI,KAA0B;CACjD;CACA;CACA;CACA;CACA;CACA;CAEA,qBAA+C;CAE/C,YACE,IACA,QACA,SACA,OACA,MACA,mBACA;AACA,QAAA,QAAc;AACd,QAAA,SAAe;AACf,QAAA,KAAW,GAAG,YAAY,SAAS,sBAAsB;AACzD,QAAA,YAAkB,OAAO;AACzB,QAAA,SAAe,UAAU,MAAA,IAAU,QAAQ;AAC3C,QAAA,UAAgB;AAChB,QAAA,YAAkB,kBAAkB,yBAAyB,KAAK;AAClE,QAAA,kBAAwB;GACtB,YAAW,SAAQ,MAAA,UAAgB,KAAK;GACxC,qBAAqB,MAAA,UAAgB,eAAe;GACpD,sBAAqB,UAAS;GAC9B,gBAAe,UAAS;GACxB,UAAU;GACV,sBAAqB,UAAS;GAC/B;AACD,QAAA,aAAmB,gBAAgB,MAAA,IAAU,SAAS,EACpD,2BAA2B,OAC5B,CAAC;AACF,QAAA,kBAAwB,IAAI,gBAAgB,QAAQ;AACpD,OAAK,mBAAmB;;CAG1B,oBAAoB;AAClB,QAAA,oBAA0B,2BACxB,MAAA,IACA,MAAA,iBACA,MAAA,OACA,MAAA,mBACA,MAAA,OACD,CAAC;;CAGJ,UAAU;AACR,QAAA,UAAgB,SAAS;;CAG3B,MAAM,eACJ,UACA,KACA;AACA,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.js","names":["#schema","#replica","#builderDelegate","#tableSpecs","#tables","#statementRunner","#lc","#appID","#logConfig","#cgStorage","#config","#getSource","#loadedPermissions","#canUpdate","#canDelete","#requirePreMutationRow","#canInsert","#getPreMutationRow","#timedCanDo","#canDo","#getPrimaryKey","#passesPolicyGroup","#passesPolicy"],"sources":["../../../../../zero-cache/src/auth/write-authorizer.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport type {MaybePromise} from '@opentelemetry/resources';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport * as v from '../../../shared/src/valita.ts';\nimport type {Condition} from '../../../zero-protocol/src/ast.ts';\nimport type {\n CRUDOp,\n DeleteOp,\n InsertOp,\n UpdateOp,\n UpsertOp,\n} from '../../../zero-protocol/src/mutation.ts';\nimport {\n primaryKeyValueSchema,\n type PrimaryKeyValue,\n} from '../../../zero-protocol/src/primary-key.ts';\nimport type {Policy} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {BuilderDelegate} from '../../../zql/src/builder/builder.ts';\nimport {\n bindStaticParameters,\n buildPipeline,\n} from '../../../zql/src/builder/builder.ts';\nimport {\n makeSourceChangeAdd,\n makeSourceChangeEdit,\n makeSourceChangeRemove,\n} from '../../../zql/src/ivm/source.ts';\nimport {consume} from '../../../zql/src/ivm/stream.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\nimport {asQueryInternals} from '../../../zql/src/query/query-internals.ts';\nimport type {Query} from '../../../zql/src/query/query.ts';\nimport {newStaticQuery} from '../../../zql/src/query/static-query.ts';\nimport type {\n ClientGroupStorage,\n DatabaseStorage,\n} from '../../../zqlite/src/database-storage.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {compile, sql} from '../../../zqlite/src/internal/sql.ts';\nimport {\n fromSQLiteTypes,\n TableSource,\n} from '../../../zqlite/src/table-source.ts';\nimport type {LogConfig, ZeroConfig} from '../config/zero-config.ts';\nimport {computeZqlSpecs} from '../db/lite-tables.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {mapLiteDataTypeToZqlSchemaValue} from '../types/lite.ts';\nimport {\n getSchema,\n reloadPermissionsIfChanged,\n type LoadedPermissions,\n} from './load-permissions.ts';\n\ntype Phase = 'preMutation' | 'postMutation';\n\nexport interface WriteAuthorizer {\n canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ): Promise<boolean>;\n reloadPermissions(): void;\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[];\n\n /**\n * Validates that all table names in the operations exist in the schema.\n * @throws Error if any table name is invalid\n */\n validateTableNames(ops: CRUDOp[]): void;\n}\n\nexport class WriteAuthorizerImpl implements WriteAuthorizer {\n readonly #schema: Schema;\n readonly #replica: Database;\n readonly #builderDelegate: BuilderDelegate;\n readonly #tableSpecs: Map<string, LiteAndZqlSpec>;\n readonly #tables = new Map<string, TableSource>();\n readonly #statementRunner: StatementRunner;\n readonly #lc: LogContext;\n readonly #appID: string;\n readonly #logConfig: LogConfig;\n readonly #cgStorage: ClientGroupStorage;\n readonly #config: ZeroConfig;\n\n #loadedPermissions: LoadedPermissions | null = null;\n\n constructor(\n lc: LogContext,\n config: ZeroConfig,\n replica: Database,\n appID: string,\n cgID: string,\n writeAuthzStorage: DatabaseStorage,\n ) {\n this.#appID = appID;\n this.#config = config;\n this.#lc = lc.withContext('class', 'WriteAuthorizerImpl');\n this.#logConfig = config.log;\n this.#schema = getSchema(this.#lc, replica);\n this.#replica = replica;\n this.#cgStorage = writeAuthzStorage.createClientGroupStorage(cgID);\n this.#builderDelegate = {\n getSource: name => this.#getSource(name),\n createStorage: () => this.#cgStorage.createStorage(),\n decorateSourceInput: input => input,\n decorateInput: input => input,\n addEdge() {},\n decorateFilterInput: input => input,\n };\n this.#tableSpecs = computeZqlSpecs(this.#lc, replica, {\n includeBackfillingColumns: false,\n });\n this.#statementRunner = new StatementRunner(replica);\n this.reloadPermissions();\n }\n\n reloadPermissions() {\n this.#loadedPermissions = reloadPermissionsIfChanged(\n this.#lc,\n this.#statementRunner,\n this.#appID,\n this.#loadedPermissions,\n this.#config,\n ).permissions;\n }\n\n destroy() {\n this.#cgStorage.destroy();\n }\n\n async canPreMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n // insert does not run pre-mutation checks\n break;\n case 'update':\n if (!(await this.#canUpdate('preMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n if (!(await this.#canDelete('preMutation', authData, op))) {\n return false;\n }\n break;\n }\n }\n return true;\n }\n\n async canPostMutation(\n authData: JWTPayload | undefined,\n ops: Exclude<CRUDOp, UpsertOp>[],\n ) {\n this.#statementRunner.beginConcurrent();\n let opError: unknown;\n try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(source.push(makeSourceChangeAdd(op.value)));\n break;\n }\n // TODO(mlaw): what if someone updates the same thing twice?\n // TODO(aa): It seems like it will just work? source.push()\n // is going to push the row into the table source, and then the\n // next requirePreMutationRow will just return the row that was\n // pushed in.\n case 'update': {\n consume(\n source.push(\n makeSourceChangeEdit(op.value, this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push(\n makeSourceChangeRemove(this.#requirePreMutationRow(op)),\n ),\n );\n break;\n }\n }\n }\n\n for (const op of ops) {\n switch (op.op) {\n case 'insert':\n if (!(await this.#canInsert('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'update':\n if (!(await this.#canUpdate('postMutation', authData, op))) {\n return false;\n }\n break;\n case 'delete':\n // delete does not run post-mutation checks.\n break;\n }\n }\n } catch (e) {\n opError = e;\n throw e;\n } finally {\n try {\n this.#statementRunner.rollback();\n } catch (rollbackError) {\n if (opError !== undefined) {\n const combinedError = new Error(\n `canPostMutation failed and rollback also failed: operation error = ${String(opError)}; rollback error = ${String(rollbackError)}`,\n );\n combinedError.cause = opError;\n throw combinedError;\n }\n throw rollbackError;\n }\n }\n\n return true;\n }\n\n normalizeOps(ops: CRUDOp[]): Exclude<CRUDOp, UpsertOp>[] {\n return ops.map(op => {\n if (op.op === 'upsert') {\n const preMutationRow = this.#getPreMutationRow(op);\n if (preMutationRow) {\n return {\n op: 'update',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return {\n op: 'insert',\n tableName: op.tableName,\n primaryKey: op.primaryKey,\n value: op.value,\n };\n }\n return op;\n });\n }\n\n validateTableNames(ops: CRUDOp[]): void {\n for (const op of ops) {\n if (!this.#tableSpecs.has(op.tableName)) {\n throw new Error(`Table '${op.tableName}' is not a valid table.`);\n }\n }\n }\n\n #canInsert(phase: Phase, authData: JWTPayload | undefined, op: InsertOp) {\n return this.#timedCanDo(phase, 'insert', authData, op);\n }\n\n #canUpdate(phase: Phase, authData: JWTPayload | undefined, op: UpdateOp) {\n return this.#timedCanDo(phase, 'update', authData, op);\n }\n\n #canDelete(phase: Phase, authData: JWTPayload | undefined, op: DeleteOp) {\n return this.#timedCanDo(phase, 'delete', authData, op);\n }\n\n /**\n * Gets schema-defined primary key and validates that operation contains required PK values.\n *\n * @returns Record where keys are column names and values are client-provided values\n * @throws Error if operation value is missing required primary key columns\n */\n #getPrimaryKey(\n tableName: string,\n opValue: Record<string, ReadonlyJSONValue | undefined>,\n ): Record<string, ReadonlyJSONValue> {\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const columns = tableSpec.tableSpec.primaryKey;\n\n // Extract primary key values from operation value and validate they exist\n const values: Record<string, ReadonlyJSONValue> = {};\n for (const col of columns) {\n const val = opValue[col];\n if (val === undefined) {\n throw new Error(\n `Primary key column '${col}' is missing from operation value for table ${tableName}`,\n );\n }\n values[col] = val;\n }\n\n return values;\n }\n\n #getSource(tableName: string) {\n let source = this.#tables.get(tableName);\n if (source) {\n return source;\n }\n const tableSpec = this.#tableSpecs.get(tableName);\n if (!tableSpec) {\n throw new Error(`Table ${tableName} not found`);\n }\n const {columns, primaryKey} = tableSpec.tableSpec;\n assert(\n primaryKey.length,\n () => `Table ${tableName} must have a primary key`,\n );\n source = new TableSource(\n this.#lc,\n this.#logConfig,\n this.#replica,\n tableName,\n Object.fromEntries(\n Object.entries(columns).map(([name, {dataType}]) => [\n name,\n mapLiteDataTypeToZqlSchemaValue(dataType),\n ]),\n ),\n [primaryKey[0], ...primaryKey.slice(1)],\n );\n this.#tables.set(tableName, source);\n\n return source;\n }\n\n async #timedCanDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const start = performance.now();\n try {\n const ret = await this.#canDo(phase, action, authData, op);\n return ret;\n } finally {\n this.#lc.info?.(\n 'action:',\n action,\n 'duration:',\n performance.now() - start,\n 'tableName:',\n op.tableName,\n 'primaryKey:',\n op.primaryKey,\n );\n }\n }\n\n /**\n * Evaluation order is from static to dynamic, broad to specific.\n * table -> column -> row -> cell.\n *\n * If any step fails, the entire operation is denied.\n *\n * That is, table rules supersede column rules, which supersede row rules,\n *\n * All steps must allow for the operation to be allowed.\n */\n async #canDo<A extends keyof ActionOpMap>(\n phase: Phase,\n action: A,\n authData: JWTPayload | undefined,\n op: ActionOpMap[A],\n ) {\n const rules = must(this.#loadedPermissions)?.permissions?.tables?.[\n op.tableName\n ];\n const rowPolicies = rules?.row;\n let rowQuery = newStaticQuery(this.#schema, op.tableName);\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, op.value);\n\n for (const pk in primaryKeyValues) {\n rowQuery = rowQuery.where(pk, '=', primaryKeyValues[pk]);\n }\n\n let applicableRowPolicy: Policy | undefined;\n switch (action) {\n case 'insert':\n if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.insert;\n }\n break;\n case 'update':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.update?.preMutation;\n } else if (phase === 'postMutation') {\n applicableRowPolicy = rowPolicies?.update?.postMutation;\n }\n break;\n case 'delete':\n if (phase === 'preMutation') {\n applicableRowPolicy = rowPolicies?.delete;\n }\n break;\n }\n\n const cellPolicies = rules?.cell;\n const applicableCellPolicies: Policy[] = [];\n if (cellPolicies) {\n for (const [column, policy] of Object.entries(cellPolicies)) {\n if (action === 'update' && op.value[column] === undefined) {\n // If the cell is not being updated, we do not need to check\n // the cell rules.\n continue;\n }\n switch (action) {\n case 'insert':\n if (policy.insert && phase === 'postMutation') {\n applicableCellPolicies.push(policy.insert);\n }\n break;\n case 'update':\n if (phase === 'preMutation' && policy.update?.preMutation) {\n applicableCellPolicies.push(policy.update.preMutation);\n }\n if (phase === 'postMutation' && policy.update?.postMutation) {\n applicableCellPolicies.push(policy.update.postMutation);\n }\n break;\n case 'delete':\n if (policy.delete && phase === 'preMutation') {\n applicableCellPolicies.push(policy.delete);\n }\n break;\n }\n }\n }\n\n if (\n !(await this.#passesPolicyGroup(\n applicableRowPolicy,\n applicableCellPolicies,\n authData,\n rowQuery,\n ))\n ) {\n this.#lc.warn?.(\n `Permission check failed for ${JSON.stringify(\n op,\n )}, action ${action}, phase ${phase}, authData: ${JSON.stringify(\n authData,\n )}, rowPolicies: ${JSON.stringify(\n applicableRowPolicy,\n )}, cellPolicies: ${JSON.stringify(applicableCellPolicies)}`,\n );\n return false;\n }\n\n return true;\n }\n\n #getPreMutationRow(op: UpsertOp | UpdateOp | DeleteOp) {\n const {value} = op;\n\n const primaryKeyValues = this.#getPrimaryKey(op.tableName, value);\n\n const spec = this.#tableSpecs.get(op.tableName);\n if (!spec) {\n throw new Error(`Table ${op.tableName} not found`);\n }\n\n const conditions: SQLQuery[] = [];\n const values: PrimaryKeyValue[] = [];\n for (const pk in primaryKeyValues) {\n conditions.push(sql`${sql.ident(pk)}=?`);\n values.push(v.parse(primaryKeyValues[pk], primaryKeyValueSchema));\n }\n\n const ret = this.#statementRunner.get(\n compile(\n sql`SELECT ${sql.join(\n Object.keys(spec.zqlSpec).map(c => sql.ident(c)),\n sql`,`,\n )} FROM ${sql.ident(op.tableName)} WHERE ${sql.join(\n conditions,\n sql` AND `,\n )}`,\n ),\n ...values,\n );\n if (ret === undefined) {\n return ret;\n }\n return fromSQLiteTypes(spec.zqlSpec, ret, op.tableName);\n }\n\n #requirePreMutationRow(op: UpdateOp | DeleteOp) {\n const ret = this.#getPreMutationRow(op);\n assert(\n ret !== undefined,\n () => `Pre-mutation row not found for ${JSON.stringify(op.value)}`,\n );\n return ret;\n }\n\n async #passesPolicyGroup(\n applicableRowPolicy: Policy | undefined,\n applicableCellPolicies: Policy[],\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ) {\n if (!(await this.#passesPolicy(applicableRowPolicy, authData, rowQuery))) {\n return false;\n }\n\n for (const policy of applicableCellPolicies) {\n if (!(await this.#passesPolicy(policy, authData, rowQuery))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Defaults to *false* if the policy is empty. At least one rule has to pass\n * for the policy to pass.\n */\n #passesPolicy(\n policy: Policy | undefined,\n authData: JWTPayload | undefined,\n rowQuery: Query<string, Schema>,\n ): MaybePromise<boolean> {\n if (policy === undefined) {\n return false;\n }\n if (policy.length === 0) {\n return false;\n }\n let rowQueryAst = asQueryInternals(rowQuery).ast;\n rowQueryAst = bindStaticParameters(\n {\n ...rowQueryAst,\n where: updateWhere(rowQueryAst.where, policy),\n },\n {\n authData: authData as Record<string, JSONValue>,\n preMutationRow: undefined,\n },\n );\n\n // call the compiler directly\n // run the sql against upstream.\n // remove the collecting into json? just need to know if a row comes back.\n\n const input = buildPipeline(rowQueryAst, this.#builderDelegate, 'query-id');\n try {\n const res = input.fetch({});\n for (const _ of res) {\n // if any row is returned at all, the\n // rule passes.\n return true;\n }\n } finally {\n input.destroy();\n }\n\n // no rows returned by any rules? The policy fails.\n return false;\n }\n}\n\nfunction updateWhere(where: Condition | undefined, policy: Policy) {\n assert(where, 'A where condition must exist for RowQuery');\n\n return simplifyCondition({\n type: 'and',\n conditions: [\n where,\n {\n type: 'or',\n conditions: policy.map(([action, rule]) => {\n assert(action, 'action must be defined in policy');\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA+EA,IAAa,sBAAb,MAA4D;CAC1D;CACA;CACA;CACA;CACA,0BAAmB,IAAI,KAA0B;CACjD;CACA;CACA;CACA;CACA;CACA;CAEA,qBAA+C;CAE/C,YACE,IACA,QACA,SACA,OACA,MACA,mBACA;AACA,QAAA,QAAc;AACd,QAAA,SAAe;AACf,QAAA,KAAW,GAAG,YAAY,SAAS,sBAAsB;AACzD,QAAA,YAAkB,OAAO;AACzB,QAAA,SAAe,UAAU,MAAA,IAAU,QAAQ;AAC3C,QAAA,UAAgB;AAChB,QAAA,YAAkB,kBAAkB,yBAAyB,KAAK;AAClE,QAAA,kBAAwB;GACtB,YAAW,SAAQ,MAAA,UAAgB,KAAK;GACxC,qBAAqB,MAAA,UAAgB,eAAe;GACpD,sBAAqB,UAAS;GAC9B,gBAAe,UAAS;GACxB,UAAU;GACV,sBAAqB,UAAS;GAC/B;AACD,QAAA,aAAmB,gBAAgB,MAAA,IAAU,SAAS,EACpD,2BAA2B,OAC5B,CAAC;AACF,QAAA,kBAAwB,IAAI,gBAAgB,QAAQ;AACpD,OAAK,mBAAmB;;CAG1B,oBAAoB;AAClB,QAAA,oBAA0B,2BACxB,MAAA,IACA,MAAA,iBACA,MAAA,OACA,MAAA,mBACA,MAA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,WAAO,QAAQ,mCAAmC;AAClD,WAAO;KACP;GACH,CACF;EACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/normalize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE;QACd,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,GAAG,EAAE;QACH,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,UAAU,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;IACF,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,MAAM,IAAI,oBAAoB,CAexC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,MAAM,CAAC,UAAU,EACtB,aAAa,CAAC,EAAE,MAAM,GACrB,oBAAoB,CAyEtB"}
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/normalize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE;QACd,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,GAAG,EAAE;QACH,EAAE,EAAE,MAAM,CAAC;KACZ,CAAC;IACF,UAAU,EAAE;QACV,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;IACF,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AASD,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,UAAU,GACjB,OAAO,CAAC,MAAM,IAAI,oBAAoB,CAexC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,MAAM,CAAC,UAAU,EACtB,aAAa,CAAC,EAAE,MAAM,GACrB,oBAAoB,CA8EtB"}
@@ -6,6 +6,10 @@ import { nanoid } from "nanoid";
6
6
  function isDevelopmentMode() {
7
7
  return process.env.NODE_ENV === "development";
8
8
  }
9
+ function isRunningInECS() {
10
+ return process.env.ECS_CONTAINER_METADATA_URI_V4 !== void 0;
11
+ }
12
+ var DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS = 2e4;
9
13
  function assertNormalized(config) {
10
14
  assert(config.taskID, "missing --task-id");
11
15
  assert(config.changeStreamer.port, "missing --change-streamer-port");
@@ -59,6 +63,10 @@ function normalizeZeroConfig(lc, config, env, defaultTaskID) {
59
63
  config.cvr.db = config.upstream.db;
60
64
  env["ZERO_CVR_DB"] = config.upstream.db;
61
65
  }
66
+ if (!config.keepaliveTimeoutMs && isRunningInECS()) {
67
+ config.keepaliveTimeoutMs = DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS;
68
+ env["ZERO_KEEPALIVE_TIMEOUT_MS"] = String(DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS);
69
+ }
62
70
  lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);
63
71
  return {
64
72
  ...config,
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.js","names":[],"sources":["../../../../../zero-cache/src/config/normalize.ts"],"sourcesContent":["import {availableParallelism} from 'node:os';\nimport type {LogContext} from '@rocicorp/logger';\nimport {nanoid} from 'nanoid';\nimport {assert, assertNotUndefined} from '../../../shared/src/asserts.ts';\nimport {getHostIp} from './network.ts';\nimport type {ZeroConfig} from './zero-config.ts';\n\n/** {@link ZeroConfig} with defaults set per option documentation. */\nexport type NormalizedZeroConfig = ZeroConfig & {\n taskID: string;\n changeStreamer: {\n port: number;\n address: string;\n };\n change: {\n db: string;\n };\n cvr: {\n db: string;\n };\n litestream: {\n port: number;\n };\n numSyncWorkers: number;\n};\n\nexport function isDevelopmentMode(): boolean {\n return process.env.NODE_ENV === 'development';\n}\n\nexport function assertNormalized(\n config: ZeroConfig,\n): asserts config is NormalizedZeroConfig {\n assert(config.taskID, 'missing --task-id');\n assert(config.changeStreamer.port, 'missing --change-streamer-port');\n assert(config.changeStreamer.address, 'missing --change-streamer-address');\n assert(config.litestream.port, 'missing --litestream-port');\n assert(config.change.db, 'missing --change-db');\n assert(config.cvr.db, 'missing --cvr-db');\n assertNotUndefined(config.numSyncWorkers, 'missing --num-sync-workers');\n\n if (!isDevelopmentMode()) {\n assert(\n config.adminPassword,\n 'missing --admin-password: required in production mode',\n );\n }\n}\n\n/**\n * Normalizes the parsed `config` by setting defaults from the environment\n * or from other options as documented. When defaults are applied, the\n * corresponding `env` variable is updated so that the settings are propagated\n * to spawned child workers. Child workers can then call\n * {@link assertNormalized} to verify that the expected defaults have been set.\n */\nexport function normalizeZeroConfig(\n lc: LogContext,\n config: ZeroConfig,\n env: NodeJS.ProcessEnv,\n defaultTaskID?: string,\n): NormalizedZeroConfig {\n if (!config.taskID) {\n const taskID = defaultTaskID ?? nanoid();\n config.taskID = taskID;\n env['ZERO_TASK_ID'] = taskID;\n }\n if (!config.changeStreamer.port) {\n const port = config.port + 1;\n config.changeStreamer.port = port;\n env['ZERO_CHANGE_STREAMER_PORT'] = String(port);\n }\n if (!config.litestream.port) {\n const port = config.port + 2;\n config.litestream.port = port;\n env['ZERO_LITESTREAM_PORT'] = String(port);\n }\n if (config.numSyncWorkers === undefined) {\n // Reserve 1 core for the replicator. The change-streamer is not CPU heavy.\n const numSyncers = Math.max(1, availableParallelism() - 1);\n config.numSyncWorkers = numSyncers;\n env['ZERO_NUM_SYNC_WORKERS'] = String(numSyncers);\n }\n\n const hostIP = getHostIp(\n lc,\n config.changeStreamer.discoveryInterfacePreferences,\n );\n if (!config.changeStreamer.address) {\n const {port} = config.changeStreamer;\n const address = `${hostIP}:${port}`;\n config.changeStreamer.address = address;\n env['ZERO_CHANGE_STREAMER_ADDRESS'] = address;\n }\n\n if (!config.change.db) {\n config.change.db = config.upstream.db;\n env['ZERO_CHANGE_DB'] = config.upstream.db;\n }\n\n if (!config.cvr.db) {\n config.cvr.db = config.upstream.db;\n env['ZERO_CVR_DB'] = config.upstream.db;\n }\n\n lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);\n\n return {\n ...config,\n taskID: config.taskID,\n\n changeStreamer: {\n ...config.changeStreamer,\n port: config.changeStreamer.port,\n address: config.changeStreamer.address,\n },\n\n litestream: {\n ...config.litestream,\n port: config.litestream.port,\n },\n\n change: {\n ...config.change,\n db: config.change.db,\n },\n\n cvr: {\n ...config.cvr,\n db: config.cvr.db,\n },\n\n numSyncWorkers: config.numSyncWorkers,\n };\n}\n"],"mappings":";;;;;AA0BA,SAAgB,oBAA6B;AAC3C,QAAA,QAAA,IAAA,aAAgC;;AAGlC,SAAgB,iBACd,QACwC;AACxC,QAAO,OAAO,QAAQ,oBAAoB;AAC1C,QAAO,OAAO,eAAe,MAAM,iCAAiC;AACpE,QAAO,OAAO,eAAe,SAAS,oCAAoC;AAC1E,QAAO,OAAO,WAAW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AAG;EACH,QAAQ,OAAO;EAEf,gBAAgB;GACd,GAAG,OAAO;GACV,MAAM,OAAO,eAAe;GAC5B,SAAS,OAAO,eAAe;GAChC;EAED,YAAY;GACV,GAAG,OAAO;GACV,MAAM,OAAO,WAAW;GACzB;EAED,QAAQ;GACN,GAAG,OAAO;GACV,IAAI,OAAO,OAAO;GACnB;EAED,KAAK;GACH,GAAG,OAAO;GACV,IAAI,OAAO,IAAI;GAChB;EAED,gBAAgB,OAAO;EACxB"}
1
+ {"version":3,"file":"normalize.js","names":[],"sources":["../../../../../zero-cache/src/config/normalize.ts"],"sourcesContent":["import {availableParallelism} from 'node:os';\nimport type {LogContext} from '@rocicorp/logger';\nimport {nanoid} from 'nanoid';\nimport {assert, assertNotUndefined} from '../../../shared/src/asserts.ts';\nimport {getHostIp} from './network.ts';\nimport type {ZeroConfig} from './zero-config.ts';\n\n/** {@link ZeroConfig} with defaults set per option documentation. */\nexport type NormalizedZeroConfig = ZeroConfig & {\n taskID: string;\n changeStreamer: {\n port: number;\n address: string;\n };\n change: {\n db: string;\n };\n cvr: {\n db: string;\n };\n litestream: {\n port: number;\n };\n numSyncWorkers: number;\n};\n\nexport function isDevelopmentMode(): boolean {\n return process.env.NODE_ENV === 'development';\n}\n\nfunction isRunningInECS(): boolean {\n // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-environment-variables.html\n return process.env.ECS_CONTAINER_METADATA_URI_V4 !== undefined;\n}\n\nconst DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS = 20_000;\n\nexport function assertNormalized(\n config: ZeroConfig,\n): asserts config is NormalizedZeroConfig {\n assert(config.taskID, 'missing --task-id');\n assert(config.changeStreamer.port, 'missing --change-streamer-port');\n assert(config.changeStreamer.address, 'missing --change-streamer-address');\n assert(config.litestream.port, 'missing --litestream-port');\n assert(config.change.db, 'missing --change-db');\n assert(config.cvr.db, 'missing --cvr-db');\n assertNotUndefined(config.numSyncWorkers, 'missing --num-sync-workers');\n\n if (!isDevelopmentMode()) {\n assert(\n config.adminPassword,\n 'missing --admin-password: required in production mode',\n );\n }\n}\n\n/**\n * Normalizes the parsed `config` by setting defaults from the environment\n * or from other options as documented. When defaults are applied, the\n * corresponding `env` variable is updated so that the settings are propagated\n * to spawned child workers. Child workers can then call\n * {@link assertNormalized} to verify that the expected defaults have been set.\n */\nexport function normalizeZeroConfig(\n lc: LogContext,\n config: ZeroConfig,\n env: NodeJS.ProcessEnv,\n defaultTaskID?: string,\n): NormalizedZeroConfig {\n if (!config.taskID) {\n const taskID = defaultTaskID ?? nanoid();\n config.taskID = taskID;\n env['ZERO_TASK_ID'] = taskID;\n }\n if (!config.changeStreamer.port) {\n const port = config.port + 1;\n config.changeStreamer.port = port;\n env['ZERO_CHANGE_STREAMER_PORT'] = String(port);\n }\n if (!config.litestream.port) {\n const port = config.port + 2;\n config.litestream.port = port;\n env['ZERO_LITESTREAM_PORT'] = String(port);\n }\n if (config.numSyncWorkers === undefined) {\n // Reserve 1 core for the replicator. The change-streamer is not CPU heavy.\n const numSyncers = Math.max(1, availableParallelism() - 1);\n config.numSyncWorkers = numSyncers;\n env['ZERO_NUM_SYNC_WORKERS'] = String(numSyncers);\n }\n\n const hostIP = getHostIp(\n lc,\n config.changeStreamer.discoveryInterfacePreferences,\n );\n if (!config.changeStreamer.address) {\n const {port} = config.changeStreamer;\n const address = `${hostIP}:${port}`;\n config.changeStreamer.address = address;\n env['ZERO_CHANGE_STREAMER_ADDRESS'] = address;\n }\n\n if (!config.change.db) {\n config.change.db = config.upstream.db;\n env['ZERO_CHANGE_DB'] = config.upstream.db;\n }\n\n if (!config.cvr.db) {\n config.cvr.db = config.upstream.db;\n env['ZERO_CVR_DB'] = config.upstream.db;\n }\n\n if (!config.keepaliveTimeoutMs && isRunningInECS()) {\n config.keepaliveTimeoutMs = DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS;\n env['ZERO_KEEPALIVE_TIMEOUT_MS'] = String(DEFAULT_ECS_KEEPALIVE_TIMEOUT_MS);\n }\n\n lc.info?.(`runtime env: taskID=${config.taskID}, hostIP=${hostIP}`);\n\n return {\n ...config,\n taskID: config.taskID,\n\n changeStreamer: {\n ...config.changeStreamer,\n port: config.changeStreamer.port,\n address: config.changeStreamer.address,\n },\n\n litestream: {\n ...config.litestream,\n port: config.litestream.port,\n },\n\n change: {\n ...config.change,\n db: config.change.db,\n },\n\n cvr: {\n ...config.cvr,\n db: config.cvr.db,\n },\n\n numSyncWorkers: config.numSyncWorkers,\n };\n}\n"],"mappings":";;;;;AA0BA,SAAgB,oBAA6B;AAC3C,QAAA,QAAA,IAAA,aAAgC;;AAGlC,SAAS,iBAA0B;AAEjC,QAAO,QAAQ,IAAI,kCAAkC,KAAA;;AAGvD,IAAM,mCAAmC;AAEzC,SAAgB,iBACd,QACwC;AACxC,QAAO,OAAO,QAAQ,oBAAoB;AAC1C,QAAO,OAAO,eAAe,MAAM,iCAAiC;AACpE,QAAO,OAAO,eAAe,SAAS,oCAAoC;AAC1E,QAAO,OAAO,WAAW,MAAM,4BAA4B;AAC3D,QAAO,OAAO,OAAO,IAAI,sBAAsB;AAC/C,QAAO,OAAO,IAAI,IAAI,mBAAmB;AACzC,oBAAmB,OAAO,gBAAgB,6BAA6B;AAEvE,KAAI,CAAC,mBAAmB,CACtB,QACE,OAAO,eACP,wDACD;;;;;;;;;AAWL,SAAgB,oBACd,IACA,QACA,KACA,eACsB;AACtB,KAAI,CAAC,OAAO,QAAQ;EAClB,MAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,SAAS;AAChB,MAAI,kBAAkB;;AAExB,KAAI,CAAC,OAAO,eAAe,MAAM;EAC/B,MAAM,OAAO,OAAO,OAAO;AAC3B,SAAO,eAAe,OAAO;AAC7B,MAAI,+BAA+B,OAAO,KAAK;;AAEjD,KAAI,CAAC,OAAO,WAAW,MAAM;EAC3B,MAAM,OAAO,OAAO,OAAO;AAC3B,SAAO,WAAW,OAAO;AACzB,MAAI,0BAA0B,OAAO,KAAK;;AAE5C,KAAI,OAAO,mBAAmB,KAAA,GAAW;EAEvC,MAAM,aAAa,KAAK,IAAI,GAAG,sBAAsB,GAAG,EAAE;AAC1D,SAAO,iBAAiB;AACxB,MAAI,2BAA2B,OAAO,WAAW;;CAGnD,MAAM,SAAS,UACb,IACA,OAAO,eAAe,8BACvB;AACD,KAAI,CAAC,OAAO,eAAe,SAAS;EAClC,MAAM,EAAC,SAAQ,OAAO;EACtB,MAAM,UAAU,GAAG,OAAO,GAAG;AAC7B,SAAO,eAAe,UAAU;AAChC,MAAI,kCAAkC;;AAGxC,KAAI,CAAC,OAAO,OAAO,IAAI;AACrB,SAAO,OAAO,KAAK,OAAO,SAAS;AACnC,MAAI,oBAAoB,OAAO,SAAS;;AAG1C,KAAI,CAAC,OAAO,IAAI,IAAI;AAClB,SAAO,IAAI,KAAK,OAAO,SAAS;AAChC,MAAI,iBAAiB,OAAO,SAAS;;AAGvC,KAAI,CAAC,OAAO,sBAAsB,gBAAgB,EAAE;AAClD,SAAO,qBAAqB;AAC5B,MAAI,+BAA+B,OAAO,iCAAiC;;AAG7E,IAAG,OAAO,uBAAuB,OAAO,OAAO,WAAW,SAAS;AAEnE,QAAO;EACL,GAAG;EACH,QAAQ,OAAO;EAEf,gBAAgB;GACd,GAAG,OAAO;GACV,MAAM,OAAO,eAAe;GAC5B,SAAS,OAAO,eAAe;GAChC;EAED,YAAY;GACV,GAAG,OAAO;GACV,MAAM,OAAO,WAAW;GACzB;EAED,QAAQ;GACN,GAAG,OAAO;GACV,IAAI,OAAO,OAAO;GACnB;EAED,KAAK;GACH,GAAG,OAAO;GACV,IAAI,OAAO,IAAI;GAChB;EAED,gBAAgB,OAAO;EACxB"}
@@ -77,11 +77,11 @@ declare const authOptions: {
77
77
  deprecated: string[];
78
78
  };
79
79
  revalidateIntervalSeconds: {
80
- type: v.Optional<number>;
80
+ type: v.Type<number>;
81
81
  desc: string[];
82
82
  };
83
83
  retransformIntervalSeconds: {
84
- type: v.Optional<number>;
84
+ type: v.Type<number>;
85
85
  desc: string[];
86
86
  };
87
87
  };
@@ -336,11 +336,11 @@ export declare const zeroOptions: {
336
336
  deprecated: string[];
337
337
  };
338
338
  revalidateIntervalSeconds: {
339
- type: v.Optional<number>;
339
+ type: v.Type<number>;
340
340
  desc: string[];
341
341
  };
342
342
  retransformIntervalSeconds: {
343
- type: v.Optional<number>;
343
+ type: v.Type<number>;
344
344
  desc: string[];
345
345
  };
346
346
  };
@@ -348,6 +348,10 @@ export declare const zeroOptions: {
348
348
  type: v.Type<number>;
349
349
  desc: string[];
350
350
  };
351
+ keepaliveTimeoutMs: {
352
+ type: v.Optional<number>;
353
+ desc: string[];
354
+ };
351
355
  changeStreamer: {
352
356
  uri: {
353
357
  type: v.Optional<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"zero-config.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/zero-config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAGL,KAAK,MAAM,EACX,KAAK,YAAY,EAClB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AAUnD,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAC,SAAS,EAAC,MAAM,kCAAkC,CAAC;AAEhE,eAAO,MAAM,mBAAmB,UAAU,CAAC;AAE3C,eAAO,MAAM,UAAU;;;;;;;;;CA+CtB,CAAC;AAEF,eAAO,MAAM,YAAY;;;;;;;;;;CAwBxB,CAAC;AAEF,QAAA,MAAM,cAAc;;;;;;;;;CAmBnB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE3D,QAAA,MAAM,oBAAoB;;;;;;;;;CAczB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;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,CAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,eAAe,CAAC,EACnD,QAAQ,EAAE,MAAM,GAAG,SAAS,WAwC7B;AAYD,wBAAgB,kBAAkB,SAEjC"}
@@ -131,11 +131,11 @@ var authOptions = {
131
131
  deprecated: [`Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`]
132
132
  },
133
133
  revalidateIntervalSeconds: {
134
- type: valita_exports.number().optional(),
134
+ type: valita_exports.number().default(300),
135
135
  desc: [`The interval in seconds between periodic /query auth revalidation for validated connections.`, `If unset, periodic auth revalidation is disabled.`]
136
136
  },
137
137
  retransformIntervalSeconds: {
138
- type: valita_exports.number().optional(),
138
+ type: valita_exports.number().default(300),
139
139
  desc: [`The interval in seconds between periodic shared /query retransform work for a client group.`, `If unset, periodic shared retransform is disabled.`]
140
140
  }
141
141
  };
@@ -389,6 +389,26 @@ var zeroOptions = {
389
389
  type: valita_exports.number().default(4848),
390
390
  desc: [`The port for sync connections.`]
391
391
  },
392
+ keepaliveTimeoutMs: {
393
+ type: valita_exports.number().optional(),
394
+ desc: [
395
+ `The timeout since the last /keepalive request after which the server will initiate`,
396
+ `a graceful shutdown. This is a workaround for AWS Elastic Container Service, which`,
397
+ `otherwise provides no signal that a target has been deregistered (and should thus begin`,
398
+ `shutdown); the cessation of health checks at /keepalive is instead used as the signal to`,
399
+ `drain. (ECS later sends a SIGTERM before killing the server but only allows a 30-second`,
400
+ `timeout before sending SIGKILL).`,
401
+ ``,
402
+ `Other container runners explicitly send a SIGTERM followed by a configurable drain interval,`,
403
+ `in which case /keepalive logic is not necessary.`,
404
+ ``,
405
+ `When running the server in ECS, this timeout should be set to some multiple of the health`,
406
+ `check interval. If the option is unset, the keepalive timeout is disabled in non-ECS environments,`,
407
+ `and defaults to 20 seconds when run in ECS (determined by the presence of the`,
408
+ `{bold ECS_CONTAINER_METADATA_URI_V4} environment variable as per`,
409
+ `https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-environment-variables.html).`
410
+ ]
411
+ },
392
412
  changeStreamer: {
393
413
  uri: {
394
414
  type: valita_exports.string().optional(),
@@ -743,11 +763,13 @@ var zeroOptions = {
743
763
  ]
744
764
  },
745
765
  intervalHours: {
746
- type: valita_exports.number().default(24),
766
+ type: valita_exports.number().default(12),
747
767
  desc: [
748
- `The interval between shadow initial-sync runs, in hours. The first run`,
749
- `is additionally staggered by a random fraction of this interval so that`,
750
- `a fleet restart does not cause all tasks to canary simultaneously.`
768
+ `The interval between shadow initial-sync runs, in hours. The first`,
769
+ `run fires within [2/3, 1) of this interval after startup, so the`,
770
+ `canary completes at least once per task lifetime (the replication`,
771
+ `manager is restarted every ~24h) while still jittering so a fleet`,
772
+ `restart does not cause all tasks to canary simultaneously.`
751
773
  ]
752
774
  },
753
775
  sampleRate: {