@rocicorp/zero 0.25.0-canary.23 → 0.25.0-canary.24

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 (78) hide show
  1. package/out/analyze-query/src/run-ast.d.ts +1 -1
  2. package/out/analyze-query/src/run-ast.d.ts.map +1 -1
  3. package/out/analyze-query/src/run-ast.js +7 -1
  4. package/out/analyze-query/src/run-ast.js.map +1 -1
  5. package/out/otel/src/log-options.d.ts +1 -1
  6. package/out/otel/src/log-options.d.ts.map +1 -1
  7. package/out/otel/src/log-options.js +0 -1
  8. package/out/otel/src/log-options.js.map +1 -1
  9. package/out/shared/src/options-types.d.ts +113 -0
  10. package/out/shared/src/options-types.d.ts.map +1 -0
  11. package/out/shared/src/options.d.ts +2 -111
  12. package/out/shared/src/options.d.ts.map +1 -1
  13. package/out/shared/src/options.js.map +1 -1
  14. package/out/zero/package.json.js +1 -1
  15. package/out/zero/src/pg.js +1 -2
  16. package/out/zero/src/server.js +1 -2
  17. package/out/zero/src/zero-cache-dev.js +11 -5
  18. package/out/zero/src/zero-cache-dev.js.map +1 -1
  19. package/out/zero/src/zero.js +0 -2
  20. package/out/zero/src/zero.js.map +1 -1
  21. package/out/zero-cache/src/auth/read-authorizer.js +1 -1
  22. package/out/zero-cache/src/auth/read-authorizer.js.map +1 -1
  23. package/out/zero-cache/src/auth/write-authorizer.js +1 -1
  24. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  25. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  26. package/out/zero-cache/src/config/zero-config.js +5 -3
  27. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  28. package/out/zero-cache/src/scripts/deploy-permissions.js +6 -3
  29. package/out/zero-cache/src/scripts/deploy-permissions.js.map +1 -1
  30. package/out/zero-cache/src/scripts/permissions.d.ts.map +1 -1
  31. package/out/zero-cache/src/scripts/permissions.js +11 -13
  32. package/out/zero-cache/src/scripts/permissions.js.map +1 -1
  33. package/out/zero-client/src/client/crud.d.ts +3 -2
  34. package/out/zero-client/src/client/crud.d.ts.map +1 -1
  35. package/out/zero-client/src/client/crud.js +7 -3
  36. package/out/zero-client/src/client/crud.js.map +1 -1
  37. package/out/zero-client/src/client/custom.d.ts +3 -2
  38. package/out/zero-client/src/client/custom.d.ts.map +1 -1
  39. package/out/zero-client/src/client/custom.js +2 -2
  40. package/out/zero-client/src/client/custom.js.map +1 -1
  41. package/out/zero-client/src/client/make-mutate-property.d.ts +1 -1
  42. package/out/zero-client/src/client/make-mutate-property.d.ts.map +1 -1
  43. package/out/zero-client/src/client/make-mutate-property.js +2 -2
  44. package/out/zero-client/src/client/make-mutate-property.js.map +1 -1
  45. package/out/zero-client/src/client/mutator-proxy.js +6 -7
  46. package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
  47. package/out/zero-client/src/client/version.js +1 -1
  48. package/out/zero-client/src/client/zero.d.ts +14 -3
  49. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  50. package/out/zero-client/src/client/zero.js +19 -6
  51. package/out/zero-client/src/client/zero.js.map +1 -1
  52. package/out/zero-client/src/mod.d.ts +3 -4
  53. package/out/zero-client/src/mod.d.ts.map +1 -1
  54. package/out/zero-schema/src/compiled-permissions.d.ts +22 -2
  55. package/out/zero-schema/src/compiled-permissions.d.ts.map +1 -1
  56. package/out/zero-schema/src/compiled-permissions.js +7 -6
  57. package/out/zero-schema/src/compiled-permissions.js.map +1 -1
  58. package/out/zero-schema/src/permissions.d.ts.map +1 -1
  59. package/out/zero-schema/src/permissions.js.map +1 -1
  60. package/out/zero-schema/src/schema-config.d.ts +0 -5
  61. package/out/zero-schema/src/schema-config.d.ts.map +1 -1
  62. package/out/zero-schema/src/schema-config.js +1 -1
  63. package/out/zero-schema/src/schema-config.js.map +1 -1
  64. package/out/zero-server/src/custom.d.ts +5 -14
  65. package/out/zero-server/src/custom.d.ts.map +1 -1
  66. package/out/zero-server/src/custom.js +8 -18
  67. package/out/zero-server/src/custom.js.map +1 -1
  68. package/out/zql/src/mutate/crud.d.ts +3 -26
  69. package/out/zql/src/mutate/crud.d.ts.map +1 -1
  70. package/out/zql/src/mutate/crud.js +14 -26
  71. package/out/zql/src/mutate/crud.js.map +1 -1
  72. package/out/zql/src/mutate/custom.d.ts +7 -8
  73. package/out/zql/src/mutate/custom.d.ts.map +1 -1
  74. package/out/zql/src/mutate/custom.js.map +1 -1
  75. package/out/zql/src/planner/planner-join.d.ts.map +1 -1
  76. package/out/zql/src/planner/planner-join.js +3 -1
  77. package/out/zql/src/planner/planner-join.js.map +1 -1
  78. package/package.json +4 -4
@@ -9,7 +9,6 @@ import { relationships } from "../../zero-schema/src/builder/relationship-builde
9
9
  import { createSchema } from "../../zero-schema/src/builder/schema-builder.js";
10
10
  import { boolean, enumeration, json, number, string, table } from "../../zero-schema/src/builder/table-builder.js";
11
11
  import { ANYONE_CAN, ANYONE_CAN_DO_ANYTHING, NOBODY_CAN, definePermissions } from "../../zero-schema/src/permissions.js";
12
- import { createCRUDBuilder } from "../../zql/src/mutate/crud.js";
13
12
  import { defineMutators, defineMutatorsWithType, getMutator, isMutatorRegistry, mustGetMutator } from "../../zql/src/mutate/mutator-registry.js";
14
13
  import { defineMutator, defineMutatorWithType, isMutator, isMutatorDefinition } from "../../zql/src/mutate/mutator.js";
15
14
  import { createBuilder } from "../../zql/src/query/create-builder.js";
@@ -32,7 +31,6 @@ export {
32
31
  Zero,
33
32
  boolean,
34
33
  createBuilder,
35
- createCRUDBuilder,
36
34
  createSchema,
37
35
  defineMutator,
38
36
  defineMutatorWithType,
@@ -1 +1 @@
1
- {"version":3,"file":"zero.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"zero.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;"}
@@ -20,7 +20,7 @@ function transformQuery(lc, query, permissionRules, authData) {
20
20
  });
21
21
  }
22
22
  function transformQueryInternal(lc, query, permissionRules) {
23
- let rowSelectRules = permissionRules.tables[query.table]?.row?.select;
23
+ let rowSelectRules = permissionRules?.tables?.[query.table]?.row?.select;
24
24
  if (!rowSelectRules || rowSelectRules.length === 0) {
25
25
  lc.warn?.(
26
26
  "No permission rules found for table '" + query.table + "'. No rows will be returned. Use ANYONE_CAN to allow all users to access all rows."
@@ -1 +1 @@
1
- {"version":3,"file":"read-authorizer.js","sources":["../../../../../zero-cache/src/auth/read-authorizer.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport type {AST, Condition} from '../../../zero-protocol/src/ast.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/query-hash.ts';\nimport type {PermissionsConfig} from '../../../zero-schema/src/compiled-permissions.ts';\nimport {bindStaticParameters} from '../../../zql/src/builder/builder.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\n\nexport type TransformedAndHashed = {\n id: string;\n transformedAst: AST;\n transformationHash: string;\n};\n/**\n * Adds permission rules to the given query so it only returns rows that the\n * user is allowed to read.\n *\n * If the returned query is `undefined` that means that user cannot run\n * the query at all. This is only the case if we can infer that all rows\n * would be excluded without running the query.\n * E.g., the user is trying to query a table that is not readable.\n */\nexport function transformAndHashQuery(\n lc: LogContext,\n id: string,\n query: AST,\n permissionRules: PermissionsConfig,\n authData: JWTPayload | undefined,\n internalQuery: boolean | null | undefined,\n): TransformedAndHashed {\n const transformed = internalQuery\n ? query // application permissions do not apply to internal queries\n : transformQuery(lc, query, permissionRules, authData);\n return {\n id,\n transformedAst: transformed,\n transformationHash: hashOfAST(transformed),\n };\n}\n\n/**\n * For a given AST, apply the read-auth rules and bind static auth data.\n */\nexport function transformQuery(\n lc: LogContext,\n query: AST,\n permissionRules: PermissionsConfig,\n authData: JWTPayload | undefined,\n): AST {\n const queryWithPermissions = transformQueryInternal(\n lc,\n query,\n permissionRules,\n );\n return bindStaticParameters(queryWithPermissions, {\n authData: authData as Record<string, JSONValue>,\n });\n}\n\nfunction transformQueryInternal(\n lc: LogContext,\n query: AST,\n permissionRules: PermissionsConfig,\n): AST {\n let rowSelectRules = permissionRules.tables[query.table]?.row?.select;\n\n if (!rowSelectRules || rowSelectRules.length === 0) {\n // If there are no rules, we default to not allowing any rows to be selected.\n lc.warn?.(\n \"No permission rules found for table '\" +\n query.table +\n \"'. No rows will be returned. Use ANYONE_CAN to allow all users to access all rows.\",\n );\n rowSelectRules = [\n [\n 'allow',\n {\n type: 'or',\n conditions: [],\n },\n ],\n ];\n }\n\n const updatedWhere = addRulesToWhere(\n query.where\n ? transformCondition(lc, query.where, permissionRules)\n : undefined,\n rowSelectRules,\n );\n return {\n ...query,\n where: simplifyCondition(updatedWhere),\n related: query.related?.map(sq => {\n const subquery = transformQueryInternal(lc, sq.subquery, permissionRules);\n return {\n ...sq,\n subquery,\n };\n }),\n };\n}\n\nfunction addRulesToWhere(\n where: Condition | undefined,\n rowSelectRules: ['allow', Condition][],\n): Condition {\n return {\n type: 'and',\n conditions: [\n ...(where ? [where] : []),\n {\n type: 'or',\n conditions: rowSelectRules.map(([_, condition]) => condition),\n },\n ],\n };\n}\n\n// We must augment conditions so we do not provide an oracle to users.\n// E.g.,\n// `issue.whereExists('secret', s => s.where('value', 'sdf'))`\n// Not applying read policies to subqueries in the where position\n// would allow users to infer the existence of rows, and their contents,\n// that they cannot read.\nfunction transformCondition(\n lc: LogContext,\n cond: Condition,\n auth: PermissionsConfig,\n): Condition {\n switch (cond.type) {\n case 'simple':\n return cond;\n case 'and':\n case 'or':\n return {\n ...cond,\n conditions: cond.conditions.map(c => transformCondition(lc, c, auth)),\n };\n case 'correlatedSubquery': {\n const query = transformQueryInternal(lc, cond.related.subquery, auth);\n return {\n ...cond,\n related: {\n ...cond.related,\n subquery: query,\n },\n };\n }\n }\n}\n"],"names":[],"mappings":";;;AAuBO,SAAS,sBACd,IACA,IACA,OACA,iBACA,UACA,eACsB;AACtB,QA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AAA,EACF;AAEJ;AAQA,SAAS,mBACP,IACA,MACA,MACW;AACX,UAAQ,KAAK,MAAA;AAAA,IACX,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,KAAK,WAAW,IAAI,OAAK,mBAAmB,IAAI,GAAG,IAAI,CAAC;AAAA,MAAA;AAAA,IAExE,KAAK,sBAAsB;AACzB,YAAM,QAAQ,uBAAuB,IAAI,KAAK,QAAQ,UAAU,IAAI;AACpE,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,KAAK;AAAA,UACR,UAAU;AAAA,QAAA;AAAA,MACZ;AAAA,IAEJ;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"read-authorizer.js","sources":["../../../../../zero-cache/src/auth/read-authorizer.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {JWTPayload} from 'jose';\nimport type {JSONValue} from '../../../shared/src/json.ts';\nimport type {AST, Condition} from '../../../zero-protocol/src/ast.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/query-hash.ts';\nimport type {PermissionsConfig} from '../../../zero-schema/src/compiled-permissions.ts';\nimport {bindStaticParameters} from '../../../zql/src/builder/builder.ts';\nimport {simplifyCondition} from '../../../zql/src/query/expression.ts';\n\nexport type TransformedAndHashed = {\n id: string;\n transformedAst: AST;\n transformationHash: string;\n};\n/**\n * Adds permission rules to the given query so it only returns rows that the\n * user is allowed to read.\n *\n * If the returned query is `undefined` that means that user cannot run\n * the query at all. This is only the case if we can infer that all rows\n * would be excluded without running the query.\n * E.g., the user is trying to query a table that is not readable.\n */\nexport function transformAndHashQuery(\n lc: LogContext,\n id: string,\n query: AST,\n permissionRules: PermissionsConfig,\n authData: JWTPayload | undefined,\n internalQuery: boolean | null | undefined,\n): TransformedAndHashed {\n const transformed = internalQuery\n ? query // application permissions do not apply to internal queries\n : transformQuery(lc, query, permissionRules, authData);\n return {\n id,\n transformedAst: transformed,\n transformationHash: hashOfAST(transformed),\n };\n}\n\n/**\n * For a given AST, apply the read-auth rules and bind static auth data.\n */\nexport function transformQuery(\n lc: LogContext,\n query: AST,\n permissionRules: PermissionsConfig,\n authData: JWTPayload | undefined,\n): AST {\n const queryWithPermissions = transformQueryInternal(\n lc,\n query,\n permissionRules,\n );\n return bindStaticParameters(queryWithPermissions, {\n authData: authData as Record<string, JSONValue>,\n });\n}\n\nfunction transformQueryInternal(\n lc: LogContext,\n query: AST,\n permissionRules: PermissionsConfig,\n): AST {\n let rowSelectRules = permissionRules?.tables?.[query.table]?.row?.select;\n\n if (!rowSelectRules || rowSelectRules.length === 0) {\n // If there are no rules, we default to not allowing any rows to be selected.\n lc.warn?.(\n \"No permission rules found for table '\" +\n query.table +\n \"'. No rows will be returned. Use ANYONE_CAN to allow all users to access all rows.\",\n );\n rowSelectRules = [\n [\n 'allow',\n {\n type: 'or',\n conditions: [],\n },\n ],\n ];\n }\n\n const updatedWhere = addRulesToWhere(\n query.where\n ? transformCondition(lc, query.where, permissionRules)\n : undefined,\n rowSelectRules,\n );\n return {\n ...query,\n where: simplifyCondition(updatedWhere),\n related: query.related?.map(sq => {\n const subquery = transformQueryInternal(lc, sq.subquery, permissionRules);\n return {\n ...sq,\n subquery,\n };\n }),\n };\n}\n\nfunction addRulesToWhere(\n where: Condition | undefined,\n rowSelectRules: ['allow', Condition][],\n): Condition {\n return {\n type: 'and',\n conditions: [\n ...(where ? [where] : []),\n {\n type: 'or',\n conditions: rowSelectRules.map(([_, condition]) => condition),\n },\n ],\n };\n}\n\n// We must augment conditions so we do not provide an oracle to users.\n// E.g.,\n// `issue.whereExists('secret', s => s.where('value', 'sdf'))`\n// Not applying read policies to subqueries in the where position\n// would allow users to infer the existence of rows, and their contents,\n// that they cannot read.\nfunction transformCondition(\n lc: LogContext,\n cond: Condition,\n auth: PermissionsConfig,\n): Condition {\n switch (cond.type) {\n case 'simple':\n return cond;\n case 'and':\n case 'or':\n return {\n ...cond,\n conditions: cond.conditions.map(c => transformCondition(lc, c, auth)),\n };\n case 'correlatedSubquery': {\n const query = transformQueryInternal(lc, cond.related.subquery, auth);\n return {\n ...cond,\n related: {\n ...cond.related,\n subquery: query,\n },\n };\n }\n }\n}\n"],"names":[],"mappings":";;;AAuBO,SAAS,sBACd,IACA,IACA,OACA,iBACA,UACA,eACsB;AACtB,QAAM,cAAc,gBAChB,QACA,eAAe,IAAI,OAAO,iBAAiB,QAAQ;AACvD,SAAO;AAAA,IACL;AAAA,IACA,gBAAgB;AAAA,IAChB,oBAAoB,UAAU,WAAW;AAAA,EAAA;AAE7C;AAKO,SAAS,eACd,IACA,OACA,iBACA,UACK;AACL,QAAM,uBAAuB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEF,SAAO,qBAAqB,sBAAsB;AAAA,IAChD;AAAA,EAAA,CACD;AACH;AAEA,SAAS,uBACP,IACA,OACA,iBACK;AACL,MAAI,iBAAiB,iBAAiB,SAAS,MAAM,KAAK,GAAG,KAAK;AAElE,MAAI,CAAC,kBAAkB,eAAe,WAAW,GAAG;AAElD,OAAG;AAAA,MACD,0CACE,MAAM,QACN;AAAA,IAAA;AAEJ,qBAAiB;AAAA,MACf;AAAA,QACE;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,YAAY,CAAA;AAAA,QAAC;AAAA,MACf;AAAA,IACF;AAAA,EAEJ;AAEA,QAAM,eAAe;AAAA,IACnB,MAAM,QACF,mBAAmB,IAAI,MAAM,OAAO,eAAe,IACnD;AAAA,IACJ;AAAA,EAAA;AAEF,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,kBAAkB,YAAY;AAAA,IACrC,SAAS,MAAM,SAAS,IAAI,CAAA,OAAM;AAChC,YAAM,WAAW,uBAAuB,IAAI,GAAG,UAAU,eAAe;AACxE,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,MAAA;AAAA,IAEJ,CAAC;AAAA,EAAA;AAEL;AAEA,SAAS,gBACP,OACA,gBACW;AACX,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,MACV,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAA;AAAA,MACtB;AAAA,QACE,MAAM;AAAA,QACN,YAAY,eAAe,IAAI,CAAC,CAAC,GAAG,SAAS,MAAM,SAAS;AAAA,MAAA;AAAA,IAC9D;AAAA,EACF;AAEJ;AAQA,SAAS,mBACP,IACA,MACA,MACW;AACX,UAAQ,KAAK,MAAA;AAAA,IACX,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,YAAY,KAAK,WAAW,IAAI,OAAK,mBAAmB,IAAI,GAAG,IAAI,CAAC;AAAA,MAAA;AAAA,IAExE,KAAK,sBAAsB;AACzB,YAAM,QAAQ,uBAAuB,IAAI,KAAK,QAAQ,UAAU,IAAI;AACpE,aAAO;AAAA,QACL,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,KAAK;AAAA,UACR,UAAU;AAAA,QAAA;AAAA,MACZ;AAAA,IAEJ;AAAA,EAAA;AAEJ;"}
@@ -248,7 +248,7 @@ class WriteAuthorizerImpl {
248
248
  * All steps must allow for the operation to be allowed.
249
249
  */
250
250
  async #canDo(phase, action, authData, op) {
251
- const rules = must(this.#loadedPermissions).permissions?.tables[op.tableName];
251
+ const rules = must(this.#loadedPermissions)?.permissions?.tables?.[op.tableName];
252
252
  const rowPolicies = rules?.row;
253
253
  let rowQuery = newStaticQuery(this.#schema, op.tableName);
254
254
  const primaryKeyValues = this.#getPrimaryKey(op.tableName, op.value);
@@ -1 +1 @@
1
- {"version":3,"file":"write-authorizer.js","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 {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\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\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.#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 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 ).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 try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(\n source.push({\n type: 'add',\n row: op.value,\n }),\n );\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 type: 'edit',\n oldRow: this.#requirePreMutationRow(op),\n row: op.value,\n }),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push({\n type: 'remove',\n row: 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 } finally {\n this.#statementRunner.rollback();\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 #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(primaryKey.length);\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);\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"names":["v.parse"],"mappings":";;;;;;;;;;;;;;;AAoEO,MAAM,oBAA+C;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,8BAAc,IAAA;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,qBAA+C;AAAA,EAE/C,YACE,IACA,QACA,SACA,OACA,MACA,mBACA;AACA,SAAK,SAAS;AACd,SAAK,MAAM,GAAG,YAAY,SAAS,qBAAqB;AACxD,SAAK,aAAa,OAAO;AACzB,SAAK,UAAU,UAAU,KAAK,KAAK,OAAO;AAC1C,SAAK,WAAW;AAChB,SAAK,aAAa,kBAAkB,yBAAyB,IAAI;AACjE,SAAK,mBAAmB;AAAA,MACtB,WAAW,CAAA,SAAQ,KAAK,WAAW,IAAI;AAAA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AW,GAAG;AACvB,aAAO;AAAA,IACT;AACA,QAAI,cAAc,iBAAiB,QAAQ,EAAE;AAC7C,kBAAc;AAAA,MACZ;AAAA,QACE,GAAG;AAAA,QACH,OAAO,YAAY,YAAY,OAAO,MAAM;AAAA,MAAA;AAAA,MAE9C;AAAA,QACE;AAAA,QACA,gBAAgB;AAAA,MAAA;AAAA,IAClB;AAOF,UAAM,QAAQ,cAAc,aAAa,KAAK,kBAAkB,UAAU;AAC1E,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,EAAE;AAC1B,iBAAW,KAAK,KAAK;AAGnB,eAAO;AAAA,MACT;AAAA,IACF,UAAA;AACE,YAAM,QAAA;AAAA,IACR;AAGA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,YAAY,OAA8B,QAAgB;AACjE,SAAO,OAAO,2CAA2C;AAEzD,SAAO,kBAAkB;AAAA,IACvB,MAAM;AAAA,IACN,YAAY;AAAA,MACV;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,YAAY,OAAO,IAAI,CAAC,CAAC,QAAQ,IAAI,MAAM;AACzC,iBAAO,MAAM;AACb,iBAAO;AAAA,QACT,CAAC;AAAA,MAAA;AAAA,IACH;AAAA,EACF,CACD;AACH;"}
1
+ {"version":3,"file":"write-authorizer.js","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 {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\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\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.#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 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 ).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 try {\n for (const op of ops) {\n const source = this.#getSource(op.tableName);\n switch (op.op) {\n case 'insert': {\n consume(\n source.push({\n type: 'add',\n row: op.value,\n }),\n );\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 type: 'edit',\n oldRow: this.#requirePreMutationRow(op),\n row: op.value,\n }),\n );\n break;\n }\n case 'delete': {\n consume(\n source.push({\n type: 'remove',\n row: 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 } finally {\n this.#statementRunner.rollback();\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 #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(primaryKey.length);\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);\n return rule;\n }),\n },\n ],\n });\n}\n\ntype ActionOpMap = {\n insert: InsertOp;\n update: UpdateOp;\n delete: DeleteOp;\n};\n"],"names":["v.parse"],"mappings":";;;;;;;;;;;;;;;AAoEO,MAAM,oBAA+C;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,8BAAc,IAAA;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,qBAA+C;AAAA,EAE/C,YACE,IACA,QACA,SACA,OACA,MACA,mBACA;AACA,SAAK,SAAS;AACd,SAAK,MAAM,GAAG,YAAY,SAAS,qBAAqB;AACxD,SAAK,aAAa,OAAO;AACzB,SAAK,UAAU,UAAU,KAAK,KAAK,OAAO;AAC1C,SAAK,WAAW;AAChB,SAAK,aAAa,kBAAkB,yBAAyB,IAAI;AACjE,SAAK,mBAAmB;AAAA,MACtB,WAAW,CAAA,SAAQ,KAAK,WAAW,IAAI;AAAA,MACvC,eAAe,MAAM,KAAK,WAAW,cAAA;AAAA,MACrC,qBAAqB,CAAA,UAAS;AAAA,MAC9B,eAAe,CAAA,UAAS;AAAA,MACxB,UAAU;AAAA,MAAC;AAAA,MACX,qBAAqB,CAAA,UAAS;AAAA,IAAA;AAEhC,SAAK,cAAc,gBAAgB,KAAK,KAAK,OAAO;AACpD,SAAK,mBAAmB,IAAI,gBAAgB,OAAO;AACnD,S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AK,kBAAkB,UAAU;AAC1E,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,EAAE;AAC1B,iBAAW,KAAK,KAAK;AAGnB,eAAO;AAAA,MACT;AAAA,IACF,UAAA;AACE,YAAM,QAAA;AAAA,IACR;AAGA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,YAAY,OAA8B,QAAgB;AACjE,SAAO,OAAO,2CAA2C;AAEzD,SAAO,kBAAkB;AAAA,IACvB,MAAM;AAAA,IACN,YAAY;AAAA,MACV;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,YAAY,OAAO,IAAI,CAAC,CAAC,QAAQ,IAAI,MAAM;AACzC,iBAAO,MAAM;AACb,iBAAO;AAAA,QACT,CAAC;AAAA,MAAA;AAAA,IACH;AAAA,EACF,CACD;AACH;"}
@@ -1 +1 @@
1
- {"version":3,"file":"zero-config.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/zero-config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,YAAY,EAClB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AASnD,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAC,SAAS,EAAC,MAAM,kCAAkC,CAAC;AAEhE,eAAO,MAAM,UAAU;;;;;;;;;CA+CtB,CAAC;AAEF,eAAO,MAAM,YAAY;;;;;;;;;;CAwBxB,CAAC;AAEF,QAAA,MAAM,cAAc;;;;;;;;;;;;;CAgCnB,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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;;;;;;;;;;;;;;;;;IAuHlB,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QA6ChB,kBAAkB;;;;;;QASlB,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoQpB,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgEnB,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAEpD,eAAO,MAAM,mBAAmB,UAAU,CAAC;AAI3C,wBAAgB,aAAa,CAC3B,IAAI,GAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAM,GAC7C,UAAU,CAaZ;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,GAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAM,GAC7C,oBAAoB,CAItB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,eAAe,CAAC,GAAG,SAAS,GACpD,MAAM,CAER;AAED,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,eAAe,CAAC,EACnD,QAAQ,EAAE,MAAM,GAAG,SAAS,WA4B7B;AAYD,wBAAgB,kBAAkB,SAEjC"}
@@ -333,10 +333,12 @@ const zeroOptions = {
333
333
  ]
334
334
  },
335
335
  yieldThresholdMs: {
336
- type: number().default(200),
336
+ type: number().default(10),
337
337
  desc: [
338
- `The ammount of time in milliseconds that a single client's view hydration
339
- or advancement can take before yielding to the event loop.`
338
+ `The maximum amount of time in milliseconds that a sync worker will`,
339
+ `spend in IVM (processing query hydration and advancement) before yielding`,
340
+ `to the event loop. Lower values increase responsiveness and fairness at`,
341
+ `the cost of reduced throughput.`
340
342
  ]
341
343
  },
342
344
  change: {
@@ -1 +1 @@
1
- {"version":3,"file":"zero-config.js","sources":["../../../../../zero-cache/src/config/zero-config.ts"],"sourcesContent":["/**\n * These types represent the _compiled_ config whereas `define-config` types represent the _source_ config.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {logOptions} from '../../../otel/src/log-options.ts';\nimport {\n parseOptions,\n type Config,\n type ParseOptions,\n} from '../../../shared/src/options.ts';\nimport * as v from '../../../shared/src/valita.ts';\n// @circular-dep-ignore - importing package.json for version info only\nimport packageJson from '../../../zero/package.json' with {type: 'json'};\nimport {runtimeDebugFlags} from '../../../zql/src/builder/debug-delegate.ts';\nimport {singleProcessMode} from '../types/processes.ts';\nimport {\n ALLOWED_APP_ID_CHARACTERS,\n INVALID_APP_ID_MESSAGE,\n} from '../types/shards.ts';\nimport {\n assertNormalized,\n isDevelopmentMode,\n type NormalizedZeroConfig,\n} from './normalize.ts';\nexport type {LogConfig} from '../../../otel/src/log-options.ts';\n\nexport const appOptions = {\n id: {\n type: v\n .string()\n .default('zero')\n .assert(id => ALLOWED_APP_ID_CHARACTERS.test(id), INVALID_APP_ID_MESSAGE),\n desc: [\n 'Unique identifier for the app.',\n '',\n 'Multiple zero-cache apps can run on a single upstream database, each of which',\n 'is isolated from the others, with its own permissions, sharding (future feature),',\n 'and change/cvr databases.',\n '',\n 'The metadata of an app is stored in an upstream schema with the same name,',\n 'e.g. \"zero\", and the metadata for each app shard, e.g. client and mutation',\n 'ids, is stored in the \"\\\\{app-id\\\\}_\\\\{#\\\\}\" schema. (Currently there is only a single',\n '\"0\" shard, but this will change with sharding).',\n '',\n 'The CVR and Change data are managed in schemas named \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cvr\"',\n 'and \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cdc\", respectively, allowing multiple apps and shards',\n 'to share the same database instance (e.g. a Postgres \"cluster\") for CVR and Change management.',\n '',\n 'Due to constraints on replication slot names, an App ID may only consist of',\n 'lower-case letters, numbers, and the underscore character.',\n '',\n 'Note that this option is used by both {bold zero-cache} and {bold zero-deploy-permissions}.',\n ],\n },\n\n publications: {\n type: v.array(v.string()).optional(() => []),\n desc: [\n `Postgres {bold PUBLICATION}s that define the tables and columns to`,\n `replicate. Publication names may not begin with an underscore,`,\n `as zero reserves that prefix for internal use.`,\n ``,\n `If unspecified, zero-cache will create and use an internal publication that`,\n `publishes all tables in the {bold public} schema, i.e.:`,\n ``,\n `CREATE PUBLICATION _\\\\{app-id\\\\}_public_0 FOR TABLES IN SCHEMA public;`,\n ``,\n `Note that changing the set of publications will result in resyncing the replica,`,\n `which may involve downtime (replication lag) while the new replica is initializing.`,\n `To change the set of publications without disrupting an existing app, a new app`,\n `should be created.`,\n ],\n },\n};\n\nexport const shardOptions = {\n id: {\n type: v\n .string()\n .assert(() => {\n throw new Error(\n `ZERO_SHARD_ID is no longer an option. Please use ZERO_APP_ID instead.`,\n // TODO: Link to release / migration notes?\n );\n })\n .optional(),\n hidden: true,\n },\n\n num: {\n type: v.number().default(0),\n desc: [\n `The shard number (from 0 to NUM_SHARDS) of the App. zero will eventually`,\n `support data sharding as a first-class primitive; until then, deploying`,\n `multiple shard-nums creates functionally identical shards. Until sharding is`,\n `actually meaningful, this flag is hidden but available for testing.`,\n ],\n hidden: true,\n },\n};\n\nconst replicaOptions = {\n file: {\n type: v.string().default('zero.db'),\n desc: [\n `File path to the SQLite replica that zero-cache maintains.`,\n `This can be lost, but if it is, zero-cache will have to re-replicate next`,\n `time it starts up.`,\n ],\n },\n\n vacuumIntervalHours: {\n type: v.number().optional(),\n desc: [\n `Performs a VACUUM at server startup if the specified number of hours has elapsed`,\n `since the last VACUUM (or initial-sync). The VACUUM operation is heavyweight`,\n `and requires double the size of the db in disk space. If unspecified, VACUUM`,\n `operations are not performed.`,\n ],\n },\n\n pageCacheSizeKib: {\n type: v.number().optional(),\n desc: [\n `The SQLite page cache size in kibibytes (KiB) for view-syncer connections.`,\n `The page cache stores recently accessed database pages in memory to reduce disk I/O.`,\n `Larger cache sizes improve performance for workloads that fit in cache.`,\n `If unspecified, SQLite's default (~2 MB) is used.`,\n `Note that the effective memory use of this setting will be:`,\n `2 * cache_size * num_cores as each connection to the replica gets its own cache`,\n `and each core maintains 2 connections.`,\n ],\n },\n};\n\nexport type ReplicaOptions = Config<typeof replicaOptions>;\n\nconst perUserMutationLimit = {\n max: {\n type: v.number().optional(),\n desc: [\n `The maximum mutations per user within the specified {bold windowMs}.`,\n `If unset, no rate limiting is enforced.`,\n ],\n },\n windowMs: {\n type: v.number().default(60_000),\n desc: [\n `The sliding window over which the {bold perUserMutationLimitMax} is enforced.`,\n ],\n },\n};\n\nexport type RateLimit = Config<typeof perUserMutationLimit>;\n\nconst authOptions = {\n jwk: {\n type: v.string().optional(),\n desc: [\n `A public key in JWK format used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n jwksUrl: {\n type: v.string().optional(),\n desc: [\n `A URL that returns a JWK set used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n secret: {\n type: v.string().optional(),\n desc: [\n `A symmetric key used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n};\n\nconst makeMutatorQueryOptions = (\n replacement: 'mutate-url' | 'query-url' | undefined,\n suffix: string,\n) => ({\n url: {\n type: v.array(v.string()).optional(), // optional until we remove CRUD mutations\n desc: [\n `The URL of the API server to which zero-cache will ${suffix}.`,\n ``,\n `{bold IMPORTANT:} URLs are matched using {bold URLPattern}, a standard Web API.`,\n ``,\n `{bold Pattern Syntax:}`,\n ` URLPattern uses a simple and intuitive syntax similar to Express routes.`,\n ` Wildcards and named parameters make it easy to match multiple URLs.`,\n ``,\n `{bold Basic Examples:}`,\n ` Exact URL match:`,\n ` \"https://api.example.com/mutate\"`,\n ` `,\n ` Any subdomain using wildcard:`,\n ` \"https://*.example.com/mutate\"`,\n ` `,\n ` Multiple subdomain levels:`,\n ` \"https://*.*.example.com/mutate\"`,\n ` `,\n ` Any path under a domain:`,\n ` \"https://api.example.com/*\"`,\n ` `,\n ` Named path parameters:`,\n ` \"https://api.example.com/:version/mutate\"`,\n ` ↳ Matches \"https://api.example.com/v1/mutate\", \"https://api.example.com/v2/mutate\", etc.`,\n ``,\n `{bold Advanced Patterns:}`,\n ` Optional path segments:`,\n ` \"https://api.example.com/:path?\"`,\n ` `,\n ` Regex in segments (for specific patterns):`,\n ` \"https://api.example.com/:version(v\\\\\\\\d+)/mutate\"`,\n ` ↳ Matches only \"v\" followed by digits`,\n ``,\n `{bold Multiple patterns:}`,\n ` [\"https://api1.example.com/mutate\", \"https://api2.example.com/mutate\"]`,\n ``,\n `{bold Note:} Query parameters and URL fragments (#) are automatically ignored during matching.`,\n ``,\n `For full URLPattern syntax, see: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}} instead.`]}\n : {}),\n },\n apiKey: {\n type: v.string().optional(),\n desc: [\n `An optional secret used to authorize zero-cache to call the API server handling writes.`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}-api-key} instead.`]}\n : {}),\n },\n forwardCookies: {\n type: v.boolean().default(false),\n desc: [\n `If true, zero-cache will forward cookies from the request.`,\n `This is useful for passing authentication cookies to the API server.`,\n `If false, cookies are not forwarded.`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}-forward-cookies} instead.`]}\n : {}),\n },\n});\n\nconst mutateOptions = makeMutatorQueryOptions(undefined, 'push mutations');\nconst pushOptions = makeMutatorQueryOptions('mutate-url', 'push mutations');\nconst queryOptions = makeMutatorQueryOptions(undefined, 'send synced queries');\nconst getQueriesOptions = makeMutatorQueryOptions(\n 'query-url',\n 'send synced queries',\n);\n\n/** @deprecated */\nexport type AuthConfig = Config<typeof authOptions>;\n\n// Note: --help will list flags in the order in which they are defined here,\n// so order the fields such that the important (e.g. required) ones are first.\n// (Exported for testing)\nexport const zeroOptions = {\n upstream: {\n db: {\n type: v.string(),\n desc: [\n `The \"upstream\" authoritative postgres database.`,\n `In the future we will support other types of upstream besides PG.`,\n ],\n },\n\n type: {\n type: v.literalUnion('pg', 'custom').default('pg'),\n desc: [\n `The meaning of the {bold upstream-db} depends on the upstream type:`,\n `* {bold pg}: The connection database string, e.g. \"postgres://...\"`,\n `* {bold custom}: The base URI of the change source \"endpoint, e.g.`,\n ` \"https://my-change-source.dev/changes/v0/stream?apiKey=...\"`,\n ],\n hidden: true, // TODO: Unhide when ready to officially support.\n },\n\n maxConns: {\n type: v.number().default(20),\n desc: [\n `The maximum number of connections to open to the upstream database`,\n `for committing mutations. This is divided evenly amongst sync workers.`,\n `In addition to this number, zero-cache uses one connection for the`,\n `replication stream.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n },\n\n /** @deprecated */\n push: pushOptions,\n mutate: mutateOptions,\n /** @deprecated */\n getQueries: getQueriesOptions,\n query: queryOptions,\n\n cvr: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store CVRs. CVRs (client view records) keep track`,\n `of the data synced to clients in order to determine the diff to send on reconnect.`,\n `If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(30),\n desc: [\n `The maximum number of connections to open to the CVR database.`,\n `This is divided evenly amongst sync workers.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n garbageCollectionInactivityThresholdHours: {\n type: v.number().default(48),\n desc: [\n `The duration after which an inactive CVR is eligible for garbage collection.`,\n `Note that garbage collection is an incremental, periodic process which does not`,\n `necessarily purge all eligible CVRs immediately.`,\n ],\n },\n\n garbageCollectionInitialIntervalSeconds: {\n type: v.number().default(60),\n desc: [\n `The initial interval at which to check and garbage collect inactive CVRs.`,\n `This interval is increased exponentially (up to 16 minutes) when there is`,\n `nothing to purge.`,\n ],\n },\n\n garbageCollectionInitialBatchSize: {\n type: v.number().default(25),\n desc: [\n `The initial number of CVRs to purge per garbage collection interval.`,\n `This number is increased linearly if the rate of new CVRs exceeds the rate of`,\n `purged CVRs, in order to reach a steady state.`,\n ``,\n `Setting this to 0 effectively disables CVR garbage collection.`,\n ],\n },\n },\n\n queryHydrationStats: {\n type: v.boolean().optional(),\n desc: [\n `Track and log the number of rows considered by query hydrations which`,\n `take longer than {bold log-slow-hydrate-threshold} milliseconds.`,\n `This is useful for debugging and performance tuning.`,\n ],\n },\n\n enableQueryPlanner: {\n type: v.boolean().default(true),\n desc: [\n `Enable the query planner for optimizing ZQL queries.`,\n ``,\n `The query planner analyzes and optimizes query execution by determining`,\n `the most efficient join strategies.`,\n ``,\n `You can disable the planner if it is picking bad strategies.`,\n ],\n },\n\n yieldThresholdMs: {\n type: v.number().default(200),\n desc: [\n `The ammount of time in milliseconds that a single client's view hydration\n or advancement can take before yielding to the event loop.`,\n ],\n },\n\n change: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store recent replication log entries, in order`,\n `to sync multiple view-syncers without requiring multiple replication slots on`,\n `the upstream database. If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(5),\n desc: [\n `The maximum number of connections to open to the change database.`,\n `This is used by the {bold change-streamer} for catching up`,\n `{bold zero-cache} replication subscriptions.`,\n ],\n },\n },\n\n replica: replicaOptions,\n\n log: logOptions,\n\n app: appOptions,\n\n shard: shardOptions,\n\n /** @deprecated */\n auth: authOptions,\n\n port: {\n type: v.number().default(4848),\n desc: [`The port for sync connections.`],\n },\n\n changeStreamer: {\n uri: {\n type: v.string().optional(),\n desc: [\n `When set, connects to the {bold change-streamer} at the given URI.`,\n `In a multi-node setup, this should be specified in {bold view-syncer} options,`,\n `pointing to the {bold replication-manager} URI, which runs a {bold change-streamer}`,\n `on port 4849.`,\n ],\n },\n\n mode: {\n type: v.literalUnion('dedicated', 'discover').default('dedicated'),\n desc: [\n `As an alternative to {bold ZERO_CHANGE_STREAMER_URI}, the {bold ZERO_CHANGE_STREAMER_MODE}`,\n `can be set to \"{bold discover}\" to instruct the {bold view-syncer} to connect to the `,\n `ip address registered by the {bold replication-manager} upon startup.`,\n ``,\n `This may not work in all networking configurations, e.g. certain private `,\n `networking or port forwarding configurations. Using the {bold ZERO_CHANGE_STREAMER_URI}`,\n `with an explicit routable hostname is recommended instead.`,\n ``,\n `Note: This option is ignored if the {bold ZERO_CHANGE_STREAMER_URI} is set.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `The port on which the {bold change-streamer} runs. This is an internal`,\n `protocol between the {bold replication-manager} and {bold view-syncers}, which`,\n `runs in the same process tree in local development or a single-node configuration.`,\n ``,\n `If unspecified, defaults to {bold --port} + 1.`,\n ],\n },\n\n /** @deprecated */\n address: {\n type: v.string().optional(),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n /** @deprecated */\n protocol: {\n type: v.literalUnion('ws', 'wss').default('ws'),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n discoveryInterfacePreferences: {\n type: v.array(v.string()).default([\n 'eth', // linux\n 'en', // macbooks\n ]),\n desc: [\n `The name prefixes to prefer when introspecting the network interfaces to determine`,\n `the externally reachable IP address for change-streamer discovery. This defaults`,\n `to commonly used names for standard ethernet interfaces in order to prevent selecting`,\n `special interfaces such as those for VPNs.`,\n ],\n // More confusing than it's worth to advertise this. The default list should be\n // adjusted to make things work for all environments; it is controlled as a\n // hidden flag as an emergency to unblock people with outlier network configs.\n hidden: true,\n },\n\n startupDelayMs: {\n type: v.number().default(15000),\n desc: [\n `The delay to wait before the change-streamer takes over the replication stream`,\n `(i.e. the handoff during replication-manager updates), to allow loadbalancers to register`,\n `the task as healthy based on healthcheck parameters. Note that if a change stream request`,\n `is received during this interval, the delay will be canceled and the takeover will happen`,\n `immediately, since the incoming request indicates that the task is registered as a target.`,\n ],\n },\n },\n\n taskID: {\n type: v.string().optional(),\n desc: [\n `Globally unique identifier for the zero-cache instance.`,\n ``,\n `Setting this to a platform specific task identifier can be useful for debugging.`,\n `If unspecified, zero-cache will attempt to extract the TaskARN if run from within`,\n `an AWS ECS container, and otherwise use a random string.`,\n ],\n },\n\n perUserMutationLimit,\n\n numSyncWorkers: {\n type: v.number().optional(),\n desc: [\n `The number of processes to use for view syncing.`,\n `Leave this unset to use the maximum available parallelism.`,\n `If set to 0, the server runs without sync workers, which is the`,\n `configuration for running the {bold replication-manager}.`,\n ],\n },\n\n autoReset: {\n type: v.boolean().default(true),\n desc: [\n `Automatically wipe and resync the replica when replication is halted.`,\n `This situation can occur for configurations in which the upstream database`,\n `provider prohibits event trigger creation, preventing the zero-cache from`,\n `being able to correctly replicate schema changes. For such configurations,`,\n `an upstream schema change will instead result in halting replication with an`,\n `error indicating that the replica needs to be reset.`,\n ``,\n `When {bold auto-reset} is enabled, zero-cache will respond to such situations`,\n `by shutting down, and when restarted, resetting the replica and all synced `,\n `clients. This is a heavy-weight operation and can result in user-visible`,\n `slowness or downtime if compute resources are scarce.`,\n ],\n },\n\n adminPassword: {\n type: v.string().optional(),\n desc: [\n `A password used to administer zero-cache server, for example to access the`,\n `/statz endpoint.`,\n '',\n 'A password is optional in development mode but {bold required in production} mode.',\n ],\n },\n\n websocketCompression: {\n type: v.boolean().default(false),\n desc: [\n 'Enable WebSocket per-message deflate compression.',\n '',\n 'Compression can reduce bandwidth usage for sync traffic but',\n 'increases CPU usage on both client and server. Disabled by default.',\n '',\n 'See: https://github.com/websockets/ws#websocket-compression',\n ],\n },\n\n websocketCompressionOptions: {\n type: v.string().optional(),\n desc: [\n 'JSON string containing WebSocket compression options.',\n '',\n 'Only used if websocketCompression is enabled.',\n '',\n 'Example: \\\\{\"zlibDeflateOptions\":\\\\{\"level\":3\\\\},\"threshold\":1024\\\\}',\n '',\n 'See https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback for available options.',\n ],\n },\n\n litestream: {\n executable: {\n type: v.string().optional(),\n desc: [`Path to the {bold litestream} executable.`],\n },\n\n configPath: {\n type: v.string().default('./src/services/litestream/config.yml'),\n desc: [\n `Path to the litestream yaml config file. zero-cache will run this with its`,\n `environment variables, which can be referenced in the file via $\\\\{ENV\\\\}`,\n `substitution, for example:`,\n `* {bold ZERO_REPLICA_FILE} for the db path`,\n `* {bold ZERO_LITESTREAM_BACKUP_LOCATION} for the db replica url`,\n `* {bold ZERO_LITESTREAM_LOG_LEVEL} for the log level`,\n `* {bold ZERO_LOG_FORMAT} for the log type`,\n ],\n },\n\n logLevel: {\n type: v.literalUnion('debug', 'info', 'warn', 'error').default('warn'),\n },\n\n backupURL: {\n type: v.string().optional(),\n desc: [\n `The location of the litestream backup, usually an {bold s3://} URL.`,\n `This is only consulted by the {bold replication-manager}.`,\n `{bold view-syncers} receive this information from the {bold replication-manager}.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `Port on which litestream exports metrics, used to determine the replication`,\n `watermark up to which it is safe to purge change log records.`,\n ``,\n `If unspecified, defaults to {bold --port} + 2.`,\n ],\n },\n\n checkpointThresholdMB: {\n type: v.number().default(40),\n desc: [\n `The size of the WAL file at which to perform an SQlite checkpoint to apply`,\n `the writes in the WAL to the main database file. Each checkpoint creates`,\n `a new WAL segment file that will be backed up by litestream. Smaller thresholds`,\n `may improve read performance, at the expense of creating more files to download`,\n `when restoring the replica from the backup.`,\n ],\n },\n\n minCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite attempts a PASSIVE checkpoint, which`,\n `transfers pages to the main database file without blocking writers.`,\n `Defaults to {bold checkpointThresholdMB * 250} (since SQLite page size is 4KB).`,\n ],\n },\n\n maxCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite performs a RESTART checkpoint, which`,\n `blocks writers until complete. Defaults to {bold minCheckpointPageCount * 10}.`,\n `Set to {bold 0} to disable RESTART checkpoints entirely.`,\n ],\n },\n\n incrementalBackupIntervalMinutes: {\n type: v.number().default(15),\n desc: [\n `The interval between incremental backups of the replica. Shorter intervals`,\n `reduce the amount of change history that needs to be replayed when catching`,\n `up a new view-syncer, at the expense of increasing the number of files needed`,\n `to download for the initial litestream restore.`,\n ],\n },\n\n snapshotBackupIntervalHours: {\n type: v.number().default(12),\n desc: [\n `The interval between snapshot backups of the replica. Snapshot backups`,\n `make a full copy of the database to a new litestream generation. This`,\n `improves restore time at the expense of bandwidth. Applications with a`,\n `large database and low write rate can increase this interval to reduce`,\n `network usage for backups (litestream defaults to 24 hours).`,\n ],\n },\n\n restoreParallelism: {\n type: v.number().default(48),\n desc: [\n `The number of WAL files to download in parallel when performing the`,\n `initial restore of the replica from the backup.`,\n ],\n },\n\n multipartConcurrency: {\n type: v.number().default(48),\n desc: [\n `The number of parts (of size {bold --litestream-multipart-size} bytes)`,\n `to upload or download in parallel when backing up or restoring the snapshot.`,\n ],\n },\n\n multipartSize: {\n type: v.number().default(16 * 1024 * 1024),\n desc: [\n `The size of each part when uploading or downloading the snapshot with`,\n `{bold --multipart-concurrency}. Note that up to {bold concurrency * size}`,\n `bytes of memory are used when backing up or restoring the snapshot.`,\n ],\n },\n },\n\n storageDBTmpDir: {\n type: v.string().optional(),\n desc: [\n `tmp directory for IVM operator storage. Leave unset to use os.tmpdir()`,\n ],\n },\n\n initialSync: {\n tableCopyWorkers: {\n type: v.number().default(5),\n desc: [\n `The number of parallel workers used to copy tables during initial sync.`,\n `Each worker uses a database connection and will buffer up to (approximately)`,\n `10 MB of table data in memory during initial sync. Increasing the number of`,\n `workers may improve initial sync speed; however, note that local disk throughput`,\n `(i.e. IOPS), upstream CPU, and network bandwidth may also be bottlenecks.`,\n ],\n },\n\n profileCopy: {\n type: v.boolean().optional(),\n hidden: true,\n desc: [\n `Takes a cpu profile during the copy phase initial-sync, storing it as a JSON file`,\n `initial-copy.cpuprofile in the tmp directory.`,\n ],\n },\n },\n\n /** @deprecated */\n targetClientRowCount: {\n type: v.number().default(20_000),\n deprecated: [\n 'This option is no longer used and will be removed in a future version.',\n 'The client-side cache no longer enforces a row limit. Instead, TTL-based expiration',\n 'automatically manages cache size to prevent unbounded growth.',\n ],\n hidden: true,\n },\n\n lazyStartup: {\n type: v.boolean().default(false),\n desc: [\n 'Delay starting the majority of zero-cache until first request.',\n '',\n 'This is mainly intended to avoid connecting to Postgres replication stream',\n 'until the first request is received, which can be useful i.e., for preview instances.',\n '',\n 'Currently only supported in single-node mode.',\n ],\n },\n\n serverVersion: {\n type: v.string().optional(),\n desc: [`The version string outputted to logs when the server starts up.`],\n },\n\n enableTelemetry: {\n type: v.boolean().default(true),\n desc: [\n `Set to false to opt out of telemetry collection.`,\n ``,\n `This helps us improve Zero by collecting anonymous usage data.`,\n `Setting the DO_NOT_TRACK environment variable also disables telemetry.`,\n ],\n },\n\n cloudEvent: {\n sinkEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a URI to a CloudEvents sink. When set, ZeroEvents`,\n `will be published to the sink as the {bold data} field of CloudEvents.`,\n `The {bold source} field of the CloudEvents will be set to the {bold ZERO_TASK_ID},`,\n `along with any extension attributes specified by the {bold ZERO_CLOUD_EVENT_EXTENSION_OVERRIDES_ENV}.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_SINK binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n `However, any CloudEvents sink can be used.`,\n ],\n },\n\n extensionOverridesEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a JSON stringified object with an {bold extensions} field`,\n `containing attributes that should be added or overridden on outbound CloudEvents.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_CE_OVERRIDES binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n ],\n },\n },\n};\n\nexport type ZeroConfig = Config<typeof zeroOptions>;\n\nexport const ZERO_ENV_VAR_PREFIX = 'ZERO_';\n\nlet loadedConfig: Config<typeof zeroOptions> | undefined;\n\nexport function getZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): ZeroConfig {\n if (!loadedConfig || singleProcessMode()) {\n loadedConfig = parseOptions(zeroOptions, {\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n emitDeprecationWarnings: false, // overridden at the top level parse\n ...opts,\n });\n\n if (loadedConfig.queryHydrationStats) {\n runtimeDebugFlags.trackRowCountsVended = true;\n }\n }\n return loadedConfig;\n}\n\n/**\n * Same as {@link getZeroConfig}, with an additional check that the\n * config has already been normalized (i.e. by the top level server/runner).\n */\nexport function getNormalizedZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): NormalizedZeroConfig {\n const config = getZeroConfig(opts);\n assertNormalized(config);\n return config;\n}\n\n/**\n * Gets the server version from the config if provided. Otherwise it gets it\n * from the Zero package.json.\n */\nexport function getServerVersion(\n config: Pick<ZeroConfig, 'serverVersion'> | undefined,\n): string {\n return config?.serverVersion ?? packageJson.version;\n}\n\nexport function isAdminPasswordValid(\n lc: LogContext,\n config: Pick<NormalizedZeroConfig, 'adminPassword'>,\n password: string | undefined,\n) {\n // If development mode, password is optional\n // We use process.env.NODE_ENV === 'development' as a sign that we're in\n // development mode, rather than a custom env var like ZERO_DEVELOPMENT_MODE,\n // because NODE_ENV is more standard and is already used by many tools.\n // Note that if NODE_ENV is not set, we assume production mode.\n\n if (!password && !config.adminPassword && isDevelopmentMode()) {\n warnOnce(\n lc,\n 'No admin password set; allowing access in development mode only',\n );\n return true;\n }\n\n if (!config.adminPassword) {\n lc.warn?.('No admin password set; denying access');\n return false;\n }\n\n if (password !== config.adminPassword) {\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n lc.debug?.('Admin password accepted');\n return true;\n}\n\nlet hasWarned = false;\n\nfunction warnOnce(lc: LogContext, msg: string) {\n if (!hasWarned) {\n lc.warn?.(msg);\n hasWarned = true;\n }\n}\n\n// For testing purposes - reset the warning state\nexport function resetWarnOnceState() {\n hasWarned = false;\n}\n"],"names":["v.string","v.array","v.number","v.boolean","v.literalUnion"],"mappings":";;;;;;;;;AA2BO,MAAM,aAAa;AAAA,EACxB,IAAI;AAAA,IACF,MAAMA,OACH,EACA,QAAQ,MAAM,EACd,OAAO,CAAA,OAAM,0BAA0B,KAAK,EAAE,GAAG,sBAAsB;AAAA,IAC1E,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAAA,EAGF,cAAc;AAAA,IACZ,MAAMC,MAAQD,OAAE,CAAQ,EAAE,SAAS,MAAM,CAAA,CAAE;AAAA,IAC3C,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EACF;AAEJ;AAEO,MAAM,eAAe;AAAA,EAC1B,IAAI;AAAA,IACF,MAAMA,SAEH,OAAO,MAAM;AACZ,YAAM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,QACQ;AACR,SAAO,QAAQ,iBAAiB,YAAY;AAC9C;AAEO,SAAS,qBACd,IACA,QACA,UACA;AAOA,MAAI,CAAC,YAAY,CAAC,OAAO,iBAAiB,qBAAqB;AAC7D;AAAA,MACE;AAAA,MACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,OAAO,eAAe;AACzB,OAAG,OAAO,uCAAuC;AACjD,WAAO;AAAA,EACT;AAEA,MAAI,aAAa,OAAO,eAAe;AACrC,OAAG,OAAO,wBAAwB;AAClC,WAAO;AAAA,EACT;AAEA,KAAG,QAAQ,yBAAyB;AACpC,SAAO;AACT;AAEA,IAAI,YAAY;AAEhB,SAAS,SAAS,IAAgB,KAAa;AAC7C,MAAI,CAAC,WAAW;AACd,OAAG,OAAO,GAAG;AACb,gBAAY;AAAA,EACd;AACF;"}
1
+ {"version":3,"file":"zero-config.js","sources":["../../../../../zero-cache/src/config/zero-config.ts"],"sourcesContent":["/**\n * These types represent the _compiled_ config whereas `define-config` types represent the _source_ config.\n */\n\nimport type {LogContext} from '@rocicorp/logger';\nimport {logOptions} from '../../../otel/src/log-options.ts';\nimport {\n parseOptions,\n type Config,\n type ParseOptions,\n} from '../../../shared/src/options.ts';\nimport * as v from '../../../shared/src/valita.ts';\n// @circular-dep-ignore - importing package.json for version info only\nimport packageJson from '../../../zero/package.json' with {type: 'json'};\nimport {runtimeDebugFlags} from '../../../zql/src/builder/debug-delegate.ts';\nimport {singleProcessMode} from '../types/processes.ts';\nimport {\n ALLOWED_APP_ID_CHARACTERS,\n INVALID_APP_ID_MESSAGE,\n} from '../types/shards.ts';\nimport {\n assertNormalized,\n isDevelopmentMode,\n type NormalizedZeroConfig,\n} from './normalize.ts';\nexport type {LogConfig} from '../../../otel/src/log-options.ts';\n\nexport const appOptions = {\n id: {\n type: v\n .string()\n .default('zero')\n .assert(id => ALLOWED_APP_ID_CHARACTERS.test(id), INVALID_APP_ID_MESSAGE),\n desc: [\n 'Unique identifier for the app.',\n '',\n 'Multiple zero-cache apps can run on a single upstream database, each of which',\n 'is isolated from the others, with its own permissions, sharding (future feature),',\n 'and change/cvr databases.',\n '',\n 'The metadata of an app is stored in an upstream schema with the same name,',\n 'e.g. \"zero\", and the metadata for each app shard, e.g. client and mutation',\n 'ids, is stored in the \"\\\\{app-id\\\\}_\\\\{#\\\\}\" schema. (Currently there is only a single',\n '\"0\" shard, but this will change with sharding).',\n '',\n 'The CVR and Change data are managed in schemas named \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cvr\"',\n 'and \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cdc\", respectively, allowing multiple apps and shards',\n 'to share the same database instance (e.g. a Postgres \"cluster\") for CVR and Change management.',\n '',\n 'Due to constraints on replication slot names, an App ID may only consist of',\n 'lower-case letters, numbers, and the underscore character.',\n '',\n 'Note that this option is used by both {bold zero-cache} and {bold zero-deploy-permissions}.',\n ],\n },\n\n publications: {\n type: v.array(v.string()).optional(() => []),\n desc: [\n `Postgres {bold PUBLICATION}s that define the tables and columns to`,\n `replicate. Publication names may not begin with an underscore,`,\n `as zero reserves that prefix for internal use.`,\n ``,\n `If unspecified, zero-cache will create and use an internal publication that`,\n `publishes all tables in the {bold public} schema, i.e.:`,\n ``,\n `CREATE PUBLICATION _\\\\{app-id\\\\}_public_0 FOR TABLES IN SCHEMA public;`,\n ``,\n `Note that changing the set of publications will result in resyncing the replica,`,\n `which may involve downtime (replication lag) while the new replica is initializing.`,\n `To change the set of publications without disrupting an existing app, a new app`,\n `should be created.`,\n ],\n },\n};\n\nexport const shardOptions = {\n id: {\n type: v\n .string()\n .assert(() => {\n throw new Error(\n `ZERO_SHARD_ID is no longer an option. Please use ZERO_APP_ID instead.`,\n // TODO: Link to release / migration notes?\n );\n })\n .optional(),\n hidden: true,\n },\n\n num: {\n type: v.number().default(0),\n desc: [\n `The shard number (from 0 to NUM_SHARDS) of the App. zero will eventually`,\n `support data sharding as a first-class primitive; until then, deploying`,\n `multiple shard-nums creates functionally identical shards. Until sharding is`,\n `actually meaningful, this flag is hidden but available for testing.`,\n ],\n hidden: true,\n },\n};\n\nconst replicaOptions = {\n file: {\n type: v.string().default('zero.db'),\n desc: [\n `File path to the SQLite replica that zero-cache maintains.`,\n `This can be lost, but if it is, zero-cache will have to re-replicate next`,\n `time it starts up.`,\n ],\n },\n\n vacuumIntervalHours: {\n type: v.number().optional(),\n desc: [\n `Performs a VACUUM at server startup if the specified number of hours has elapsed`,\n `since the last VACUUM (or initial-sync). The VACUUM operation is heavyweight`,\n `and requires double the size of the db in disk space. If unspecified, VACUUM`,\n `operations are not performed.`,\n ],\n },\n\n pageCacheSizeKib: {\n type: v.number().optional(),\n desc: [\n `The SQLite page cache size in kibibytes (KiB) for view-syncer connections.`,\n `The page cache stores recently accessed database pages in memory to reduce disk I/O.`,\n `Larger cache sizes improve performance for workloads that fit in cache.`,\n `If unspecified, SQLite's default (~2 MB) is used.`,\n `Note that the effective memory use of this setting will be:`,\n `2 * cache_size * num_cores as each connection to the replica gets its own cache`,\n `and each core maintains 2 connections.`,\n ],\n },\n};\n\nexport type ReplicaOptions = Config<typeof replicaOptions>;\n\nconst perUserMutationLimit = {\n max: {\n type: v.number().optional(),\n desc: [\n `The maximum mutations per user within the specified {bold windowMs}.`,\n `If unset, no rate limiting is enforced.`,\n ],\n },\n windowMs: {\n type: v.number().default(60_000),\n desc: [\n `The sliding window over which the {bold perUserMutationLimitMax} is enforced.`,\n ],\n },\n};\n\nexport type RateLimit = Config<typeof perUserMutationLimit>;\n\nconst authOptions = {\n jwk: {\n type: v.string().optional(),\n desc: [\n `A public key in JWK format used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n jwksUrl: {\n type: v.string().optional(),\n desc: [\n `A URL that returns a JWK set used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n secret: {\n type: v.string().optional(),\n desc: [\n `A symmetric key used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n};\n\nconst makeMutatorQueryOptions = (\n replacement: 'mutate-url' | 'query-url' | undefined,\n suffix: string,\n) => ({\n url: {\n type: v.array(v.string()).optional(), // optional until we remove CRUD mutations\n desc: [\n `The URL of the API server to which zero-cache will ${suffix}.`,\n ``,\n `{bold IMPORTANT:} URLs are matched using {bold URLPattern}, a standard Web API.`,\n ``,\n `{bold Pattern Syntax:}`,\n ` URLPattern uses a simple and intuitive syntax similar to Express routes.`,\n ` Wildcards and named parameters make it easy to match multiple URLs.`,\n ``,\n `{bold Basic Examples:}`,\n ` Exact URL match:`,\n ` \"https://api.example.com/mutate\"`,\n ` `,\n ` Any subdomain using wildcard:`,\n ` \"https://*.example.com/mutate\"`,\n ` `,\n ` Multiple subdomain levels:`,\n ` \"https://*.*.example.com/mutate\"`,\n ` `,\n ` Any path under a domain:`,\n ` \"https://api.example.com/*\"`,\n ` `,\n ` Named path parameters:`,\n ` \"https://api.example.com/:version/mutate\"`,\n ` ↳ Matches \"https://api.example.com/v1/mutate\", \"https://api.example.com/v2/mutate\", etc.`,\n ``,\n `{bold Advanced Patterns:}`,\n ` Optional path segments:`,\n ` \"https://api.example.com/:path?\"`,\n ` `,\n ` Regex in segments (for specific patterns):`,\n ` \"https://api.example.com/:version(v\\\\\\\\d+)/mutate\"`,\n ` ↳ Matches only \"v\" followed by digits`,\n ``,\n `{bold Multiple patterns:}`,\n ` [\"https://api1.example.com/mutate\", \"https://api2.example.com/mutate\"]`,\n ``,\n `{bold Note:} Query parameters and URL fragments (#) are automatically ignored during matching.`,\n ``,\n `For full URLPattern syntax, see: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}} instead.`]}\n : {}),\n },\n apiKey: {\n type: v.string().optional(),\n desc: [\n `An optional secret used to authorize zero-cache to call the API server handling writes.`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}-api-key} instead.`]}\n : {}),\n },\n forwardCookies: {\n type: v.boolean().default(false),\n desc: [\n `If true, zero-cache will forward cookies from the request.`,\n `This is useful for passing authentication cookies to the API server.`,\n `If false, cookies are not forwarded.`,\n ],\n ...(replacement\n ? {deprecated: [`Use {bold ${replacement}-forward-cookies} instead.`]}\n : {}),\n },\n});\n\nconst mutateOptions = makeMutatorQueryOptions(undefined, 'push mutations');\nconst pushOptions = makeMutatorQueryOptions('mutate-url', 'push mutations');\nconst queryOptions = makeMutatorQueryOptions(undefined, 'send synced queries');\nconst getQueriesOptions = makeMutatorQueryOptions(\n 'query-url',\n 'send synced queries',\n);\n\n/** @deprecated */\nexport type AuthConfig = Config<typeof authOptions>;\n\n// Note: --help will list flags in the order in which they are defined here,\n// so order the fields such that the important (e.g. required) ones are first.\n// (Exported for testing)\nexport const zeroOptions = {\n upstream: {\n db: {\n type: v.string(),\n desc: [\n `The \"upstream\" authoritative postgres database.`,\n `In the future we will support other types of upstream besides PG.`,\n ],\n },\n\n type: {\n type: v.literalUnion('pg', 'custom').default('pg'),\n desc: [\n `The meaning of the {bold upstream-db} depends on the upstream type:`,\n `* {bold pg}: The connection database string, e.g. \"postgres://...\"`,\n `* {bold custom}: The base URI of the change source \"endpoint, e.g.`,\n ` \"https://my-change-source.dev/changes/v0/stream?apiKey=...\"`,\n ],\n hidden: true, // TODO: Unhide when ready to officially support.\n },\n\n maxConns: {\n type: v.number().default(20),\n desc: [\n `The maximum number of connections to open to the upstream database`,\n `for committing mutations. This is divided evenly amongst sync workers.`,\n `In addition to this number, zero-cache uses one connection for the`,\n `replication stream.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n },\n\n /** @deprecated */\n push: pushOptions,\n mutate: mutateOptions,\n /** @deprecated */\n getQueries: getQueriesOptions,\n query: queryOptions,\n\n cvr: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store CVRs. CVRs (client view records) keep track`,\n `of the data synced to clients in order to determine the diff to send on reconnect.`,\n `If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(30),\n desc: [\n `The maximum number of connections to open to the CVR database.`,\n `This is divided evenly amongst sync workers.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n garbageCollectionInactivityThresholdHours: {\n type: v.number().default(48),\n desc: [\n `The duration after which an inactive CVR is eligible for garbage collection.`,\n `Note that garbage collection is an incremental, periodic process which does not`,\n `necessarily purge all eligible CVRs immediately.`,\n ],\n },\n\n garbageCollectionInitialIntervalSeconds: {\n type: v.number().default(60),\n desc: [\n `The initial interval at which to check and garbage collect inactive CVRs.`,\n `This interval is increased exponentially (up to 16 minutes) when there is`,\n `nothing to purge.`,\n ],\n },\n\n garbageCollectionInitialBatchSize: {\n type: v.number().default(25),\n desc: [\n `The initial number of CVRs to purge per garbage collection interval.`,\n `This number is increased linearly if the rate of new CVRs exceeds the rate of`,\n `purged CVRs, in order to reach a steady state.`,\n ``,\n `Setting this to 0 effectively disables CVR garbage collection.`,\n ],\n },\n },\n\n queryHydrationStats: {\n type: v.boolean().optional(),\n desc: [\n `Track and log the number of rows considered by query hydrations which`,\n `take longer than {bold log-slow-hydrate-threshold} milliseconds.`,\n `This is useful for debugging and performance tuning.`,\n ],\n },\n\n enableQueryPlanner: {\n type: v.boolean().default(true),\n desc: [\n `Enable the query planner for optimizing ZQL queries.`,\n ``,\n `The query planner analyzes and optimizes query execution by determining`,\n `the most efficient join strategies.`,\n ``,\n `You can disable the planner if it is picking bad strategies.`,\n ],\n },\n\n yieldThresholdMs: {\n type: v.number().default(10),\n desc: [\n `The maximum amount of time in milliseconds that a sync worker will`,\n `spend in IVM (processing query hydration and advancement) before yielding`,\n `to the event loop. Lower values increase responsiveness and fairness at`,\n `the cost of reduced throughput.`,\n ],\n },\n\n change: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store recent replication log entries, in order`,\n `to sync multiple view-syncers without requiring multiple replication slots on`,\n `the upstream database. If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(5),\n desc: [\n `The maximum number of connections to open to the change database.`,\n `This is used by the {bold change-streamer} for catching up`,\n `{bold zero-cache} replication subscriptions.`,\n ],\n },\n },\n\n replica: replicaOptions,\n\n log: logOptions,\n\n app: appOptions,\n\n shard: shardOptions,\n\n /** @deprecated */\n auth: authOptions,\n\n port: {\n type: v.number().default(4848),\n desc: [`The port for sync connections.`],\n },\n\n changeStreamer: {\n uri: {\n type: v.string().optional(),\n desc: [\n `When set, connects to the {bold change-streamer} at the given URI.`,\n `In a multi-node setup, this should be specified in {bold view-syncer} options,`,\n `pointing to the {bold replication-manager} URI, which runs a {bold change-streamer}`,\n `on port 4849.`,\n ],\n },\n\n mode: {\n type: v.literalUnion('dedicated', 'discover').default('dedicated'),\n desc: [\n `As an alternative to {bold ZERO_CHANGE_STREAMER_URI}, the {bold ZERO_CHANGE_STREAMER_MODE}`,\n `can be set to \"{bold discover}\" to instruct the {bold view-syncer} to connect to the `,\n `ip address registered by the {bold replication-manager} upon startup.`,\n ``,\n `This may not work in all networking configurations, e.g. certain private `,\n `networking or port forwarding configurations. Using the {bold ZERO_CHANGE_STREAMER_URI}`,\n `with an explicit routable hostname is recommended instead.`,\n ``,\n `Note: This option is ignored if the {bold ZERO_CHANGE_STREAMER_URI} is set.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `The port on which the {bold change-streamer} runs. This is an internal`,\n `protocol between the {bold replication-manager} and {bold view-syncers}, which`,\n `runs in the same process tree in local development or a single-node configuration.`,\n ``,\n `If unspecified, defaults to {bold --port} + 1.`,\n ],\n },\n\n /** @deprecated */\n address: {\n type: v.string().optional(),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n /** @deprecated */\n protocol: {\n type: v.literalUnion('ws', 'wss').default('ws'),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n discoveryInterfacePreferences: {\n type: v.array(v.string()).default([\n 'eth', // linux\n 'en', // macbooks\n ]),\n desc: [\n `The name prefixes to prefer when introspecting the network interfaces to determine`,\n `the externally reachable IP address for change-streamer discovery. This defaults`,\n `to commonly used names for standard ethernet interfaces in order to prevent selecting`,\n `special interfaces such as those for VPNs.`,\n ],\n // More confusing than it's worth to advertise this. The default list should be\n // adjusted to make things work for all environments; it is controlled as a\n // hidden flag as an emergency to unblock people with outlier network configs.\n hidden: true,\n },\n\n startupDelayMs: {\n type: v.number().default(15000),\n desc: [\n `The delay to wait before the change-streamer takes over the replication stream`,\n `(i.e. the handoff during replication-manager updates), to allow loadbalancers to register`,\n `the task as healthy based on healthcheck parameters. Note that if a change stream request`,\n `is received during this interval, the delay will be canceled and the takeover will happen`,\n `immediately, since the incoming request indicates that the task is registered as a target.`,\n ],\n },\n },\n\n taskID: {\n type: v.string().optional(),\n desc: [\n `Globally unique identifier for the zero-cache instance.`,\n ``,\n `Setting this to a platform specific task identifier can be useful for debugging.`,\n `If unspecified, zero-cache will attempt to extract the TaskARN if run from within`,\n `an AWS ECS container, and otherwise use a random string.`,\n ],\n },\n\n perUserMutationLimit,\n\n numSyncWorkers: {\n type: v.number().optional(),\n desc: [\n `The number of processes to use for view syncing.`,\n `Leave this unset to use the maximum available parallelism.`,\n `If set to 0, the server runs without sync workers, which is the`,\n `configuration for running the {bold replication-manager}.`,\n ],\n },\n\n autoReset: {\n type: v.boolean().default(true),\n desc: [\n `Automatically wipe and resync the replica when replication is halted.`,\n `This situation can occur for configurations in which the upstream database`,\n `provider prohibits event trigger creation, preventing the zero-cache from`,\n `being able to correctly replicate schema changes. For such configurations,`,\n `an upstream schema change will instead result in halting replication with an`,\n `error indicating that the replica needs to be reset.`,\n ``,\n `When {bold auto-reset} is enabled, zero-cache will respond to such situations`,\n `by shutting down, and when restarted, resetting the replica and all synced `,\n `clients. This is a heavy-weight operation and can result in user-visible`,\n `slowness or downtime if compute resources are scarce.`,\n ],\n },\n\n adminPassword: {\n type: v.string().optional(),\n desc: [\n `A password used to administer zero-cache server, for example to access the`,\n `/statz endpoint.`,\n '',\n 'A password is optional in development mode but {bold required in production} mode.',\n ],\n },\n\n websocketCompression: {\n type: v.boolean().default(false),\n desc: [\n 'Enable WebSocket per-message deflate compression.',\n '',\n 'Compression can reduce bandwidth usage for sync traffic but',\n 'increases CPU usage on both client and server. Disabled by default.',\n '',\n 'See: https://github.com/websockets/ws#websocket-compression',\n ],\n },\n\n websocketCompressionOptions: {\n type: v.string().optional(),\n desc: [\n 'JSON string containing WebSocket compression options.',\n '',\n 'Only used if websocketCompression is enabled.',\n '',\n 'Example: \\\\{\"zlibDeflateOptions\":\\\\{\"level\":3\\\\},\"threshold\":1024\\\\}',\n '',\n 'See https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback for available options.',\n ],\n },\n\n litestream: {\n executable: {\n type: v.string().optional(),\n desc: [`Path to the {bold litestream} executable.`],\n },\n\n configPath: {\n type: v.string().default('./src/services/litestream/config.yml'),\n desc: [\n `Path to the litestream yaml config file. zero-cache will run this with its`,\n `environment variables, which can be referenced in the file via $\\\\{ENV\\\\}`,\n `substitution, for example:`,\n `* {bold ZERO_REPLICA_FILE} for the db path`,\n `* {bold ZERO_LITESTREAM_BACKUP_LOCATION} for the db replica url`,\n `* {bold ZERO_LITESTREAM_LOG_LEVEL} for the log level`,\n `* {bold ZERO_LOG_FORMAT} for the log type`,\n ],\n },\n\n logLevel: {\n type: v.literalUnion('debug', 'info', 'warn', 'error').default('warn'),\n },\n\n backupURL: {\n type: v.string().optional(),\n desc: [\n `The location of the litestream backup, usually an {bold s3://} URL.`,\n `This is only consulted by the {bold replication-manager}.`,\n `{bold view-syncers} receive this information from the {bold replication-manager}.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `Port on which litestream exports metrics, used to determine the replication`,\n `watermark up to which it is safe to purge change log records.`,\n ``,\n `If unspecified, defaults to {bold --port} + 2.`,\n ],\n },\n\n checkpointThresholdMB: {\n type: v.number().default(40),\n desc: [\n `The size of the WAL file at which to perform an SQlite checkpoint to apply`,\n `the writes in the WAL to the main database file. Each checkpoint creates`,\n `a new WAL segment file that will be backed up by litestream. Smaller thresholds`,\n `may improve read performance, at the expense of creating more files to download`,\n `when restoring the replica from the backup.`,\n ],\n },\n\n minCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite attempts a PASSIVE checkpoint, which`,\n `transfers pages to the main database file without blocking writers.`,\n `Defaults to {bold checkpointThresholdMB * 250} (since SQLite page size is 4KB).`,\n ],\n },\n\n maxCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite performs a RESTART checkpoint, which`,\n `blocks writers until complete. Defaults to {bold minCheckpointPageCount * 10}.`,\n `Set to {bold 0} to disable RESTART checkpoints entirely.`,\n ],\n },\n\n incrementalBackupIntervalMinutes: {\n type: v.number().default(15),\n desc: [\n `The interval between incremental backups of the replica. Shorter intervals`,\n `reduce the amount of change history that needs to be replayed when catching`,\n `up a new view-syncer, at the expense of increasing the number of files needed`,\n `to download for the initial litestream restore.`,\n ],\n },\n\n snapshotBackupIntervalHours: {\n type: v.number().default(12),\n desc: [\n `The interval between snapshot backups of the replica. Snapshot backups`,\n `make a full copy of the database to a new litestream generation. This`,\n `improves restore time at the expense of bandwidth. Applications with a`,\n `large database and low write rate can increase this interval to reduce`,\n `network usage for backups (litestream defaults to 24 hours).`,\n ],\n },\n\n restoreParallelism: {\n type: v.number().default(48),\n desc: [\n `The number of WAL files to download in parallel when performing the`,\n `initial restore of the replica from the backup.`,\n ],\n },\n\n multipartConcurrency: {\n type: v.number().default(48),\n desc: [\n `The number of parts (of size {bold --litestream-multipart-size} bytes)`,\n `to upload or download in parallel when backing up or restoring the snapshot.`,\n ],\n },\n\n multipartSize: {\n type: v.number().default(16 * 1024 * 1024),\n desc: [\n `The size of each part when uploading or downloading the snapshot with`,\n `{bold --multipart-concurrency}. Note that up to {bold concurrency * size}`,\n `bytes of memory are used when backing up or restoring the snapshot.`,\n ],\n },\n },\n\n storageDBTmpDir: {\n type: v.string().optional(),\n desc: [\n `tmp directory for IVM operator storage. Leave unset to use os.tmpdir()`,\n ],\n },\n\n initialSync: {\n tableCopyWorkers: {\n type: v.number().default(5),\n desc: [\n `The number of parallel workers used to copy tables during initial sync.`,\n `Each worker uses a database connection and will buffer up to (approximately)`,\n `10 MB of table data in memory during initial sync. Increasing the number of`,\n `workers may improve initial sync speed; however, note that local disk throughput`,\n `(i.e. IOPS), upstream CPU, and network bandwidth may also be bottlenecks.`,\n ],\n },\n\n profileCopy: {\n type: v.boolean().optional(),\n hidden: true,\n desc: [\n `Takes a cpu profile during the copy phase initial-sync, storing it as a JSON file`,\n `initial-copy.cpuprofile in the tmp directory.`,\n ],\n },\n },\n\n /** @deprecated */\n targetClientRowCount: {\n type: v.number().default(20_000),\n deprecated: [\n 'This option is no longer used and will be removed in a future version.',\n 'The client-side cache no longer enforces a row limit. Instead, TTL-based expiration',\n 'automatically manages cache size to prevent unbounded growth.',\n ],\n hidden: true,\n },\n\n lazyStartup: {\n type: v.boolean().default(false),\n desc: [\n 'Delay starting the majority of zero-cache until first request.',\n '',\n 'This is mainly intended to avoid connecting to Postgres replication stream',\n 'until the first request is received, which can be useful i.e., for preview instances.',\n '',\n 'Currently only supported in single-node mode.',\n ],\n },\n\n serverVersion: {\n type: v.string().optional(),\n desc: [`The version string outputted to logs when the server starts up.`],\n },\n\n enableTelemetry: {\n type: v.boolean().default(true),\n desc: [\n `Set to false to opt out of telemetry collection.`,\n ``,\n `This helps us improve Zero by collecting anonymous usage data.`,\n `Setting the DO_NOT_TRACK environment variable also disables telemetry.`,\n ],\n },\n\n cloudEvent: {\n sinkEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a URI to a CloudEvents sink. When set, ZeroEvents`,\n `will be published to the sink as the {bold data} field of CloudEvents.`,\n `The {bold source} field of the CloudEvents will be set to the {bold ZERO_TASK_ID},`,\n `along with any extension attributes specified by the {bold ZERO_CLOUD_EVENT_EXTENSION_OVERRIDES_ENV}.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_SINK binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n `However, any CloudEvents sink can be used.`,\n ],\n },\n\n extensionOverridesEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a JSON stringified object with an {bold extensions} field`,\n `containing attributes that should be added or overridden on outbound CloudEvents.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_CE_OVERRIDES binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n ],\n },\n },\n};\n\nexport type ZeroConfig = Config<typeof zeroOptions>;\n\nexport const ZERO_ENV_VAR_PREFIX = 'ZERO_';\n\nlet loadedConfig: Config<typeof zeroOptions> | undefined;\n\nexport function getZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): ZeroConfig {\n if (!loadedConfig || singleProcessMode()) {\n loadedConfig = parseOptions(zeroOptions, {\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n emitDeprecationWarnings: false, // overridden at the top level parse\n ...opts,\n });\n\n if (loadedConfig.queryHydrationStats) {\n runtimeDebugFlags.trackRowCountsVended = true;\n }\n }\n return loadedConfig;\n}\n\n/**\n * Same as {@link getZeroConfig}, with an additional check that the\n * config has already been normalized (i.e. by the top level server/runner).\n */\nexport function getNormalizedZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): NormalizedZeroConfig {\n const config = getZeroConfig(opts);\n assertNormalized(config);\n return config;\n}\n\n/**\n * Gets the server version from the config if provided. Otherwise it gets it\n * from the Zero package.json.\n */\nexport function getServerVersion(\n config: Pick<ZeroConfig, 'serverVersion'> | undefined,\n): string {\n return config?.serverVersion ?? packageJson.version;\n}\n\nexport function isAdminPasswordValid(\n lc: LogContext,\n config: Pick<NormalizedZeroConfig, 'adminPassword'>,\n password: string | undefined,\n) {\n // If development mode, password is optional\n // We use process.env.NODE_ENV === 'development' as a sign that we're in\n // development mode, rather than a custom env var like ZERO_DEVELOPMENT_MODE,\n // because NODE_ENV is more standard and is already used by many tools.\n // Note that if NODE_ENV is not set, we assume production mode.\n\n if (!password && !config.adminPassword && isDevelopmentMode()) {\n warnOnce(\n lc,\n 'No admin password set; allowing access in development mode only',\n );\n return true;\n }\n\n if (!config.adminPassword) {\n lc.warn?.('No admin password set; denying access');\n return false;\n }\n\n if (password !== config.adminPassword) {\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n lc.debug?.('Admin password accepted');\n return true;\n}\n\nlet hasWarned = false;\n\nfunction warnOnce(lc: LogContext, msg: string) {\n if (!hasWarned) {\n lc.warn?.(msg);\n hasWarned = true;\n }\n}\n\n// For testing purposes - reset the warning state\nexport function resetWarnOnceState() {\n hasWarned = false;\n}\n"],"names":["v.string","v.array","v.number","v.boolean","v.literalUnion"],"mappings":";;;;;;;;;AA2BO,MAAM,aAAa;AAAA,EACxB,IAAI;AAAA,IACF,MAAMA,OACH,EACA,QAAQ,MAAM,EACd,OAAO,CAAA,OAAM,0BAA0B,KAAK,EAAE,GAAG,sBAAsB;AAAA,IAC1E,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,M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AAA,IAGF,uBAAuB;AAAA,MACrB,MAAMA,OAAE,EAAS,SAAA;AAAA,MACjB,MAAM;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MAAA;AAAA,IACF;AAAA,EACF;AAEJ;AAIO,MAAM,sBAAsB;AAEnC,IAAI;AAEG,SAAS,cACd,OAA4C,IAChC;AACZ,MAAI,CAAC,gBAAgB,qBAAqB;AACxC,mBAAe,aAAa,aAAa;AAAA,MACvC,eAAe;AAAA,MACf,yBAAyB;AAAA;AAAA,MACzB,GAAG;AAAA,IAAA,CACJ;AAED,QAAI,aAAa,qBAAqB;AACpC,wBAAkB,uBAAuB;AAAA,IAC3C;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,wBACd,OAA4C,IACtB;AACtB,QAAM,SAAS,cAAc,IAAI;AACjC,mBAAiB,MAAM;AACvB,SAAO;AACT;AAMO,SAAS,iBACd,QACQ;AACR,SAAO,QAAQ,iBAAiB,YAAY;AAC9C;AAEO,SAAS,qBACd,IACA,QACA,UACA;AAOA,MAAI,CAAC,YAAY,CAAC,OAAO,iBAAiB,qBAAqB;AAC7D;AAAA,MACE;AAAA,MACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,OAAO,eAAe;AACzB,OAAG,OAAO,uCAAuC;AACjD,WAAO;AAAA,EACT;AAEA,MAAI,aAAa,OAAO,eAAe;AACrC,OAAG,OAAO,wBAAwB;AAClC,WAAO;AAAA,EACT;AAEA,KAAG,QAAQ,yBAAyB;AACpC,SAAO;AACT;AAEA,IAAI,YAAY;AAEhB,SAAS,SAAS,IAAgB,KAAa;AAC7C,MAAI,CAAC,WAAW;AACd,OAAG,OAAO,GAAG;AACb,gBAAY;AAAA,EACd;AACF;"}
@@ -67,7 +67,7 @@ Deploying ${app} permissions without validating against published tables/columns
67
67
  );
68
68
  const validate = validator(tablesToColumns);
69
69
  try {
70
- for (const [table, perms] of Object.entries(permissions.tables)) {
70
+ for (const [table, perms] of Object.entries(permissions?.tables ?? {})) {
71
71
  const validateRule = ([_, cond]) => {
72
72
  mapCondition(cond, table, validate);
73
73
  };
@@ -131,11 +131,14 @@ async function writePermissionsFile(perms, file, format) {
131
131
  colorConsole.info(`Wrote ${format} permissions to ${config.output.file}`);
132
132
  }
133
133
  const ret = await loadSchemaAndPermissions(config.schema.path, true);
134
- if (!ret) {
134
+ if (!ret || Object.keys(ret?.permissions ?? {}).length === 0) {
135
135
  colorConsole.warn(
136
- `No schema found at ${config.schema.path}, so could not deploy permissions. Replicating data, but no tables will be syncable. Create a schema file with permissions to be able to sync data.`
136
+ `No permissions found at ${config.schema.path}, so could not deploy permissions. Replicating data, but no tables will be syncable. Create a schema file with permissions to be able to sync data.`
137
137
  );
138
138
  } else {
139
+ colorConsole.warn(
140
+ `Permissions are deprecated and will be removed in an upcoming release. See: https://zero.rocicorp.dev/docs/auth.`
141
+ );
139
142
  const { permissions } = ret;
140
143
  if (config.output.file) {
141
144
  await writePermissionsFile(
@@ -1 +1 @@
1
- {"version":3,"file":"deploy-permissions.js","sources":["../../../../../zero-cache/src/scripts/deploy-permissions.ts"],"sourcesContent":["import '../../../shared/src/dotenv.ts';\n\nimport {writeFile} from 'node:fs/promises';\nimport {ident as id, literal} from 'pg-format';\nimport {colorConsole, createLogContext} from '../../../shared/src/logging.ts';\nimport {parseOptions} from '../../../shared/src/options.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {mapCondition} from '../../../zero-protocol/src/ast.ts';\nimport {\n type AssetPermissions,\n type PermissionsConfig,\n type Rule,\n} from '../../../zero-schema/src/compiled-permissions.ts';\nimport {validator} from '../../../zero-schema/src/name-mapper.ts';\nimport {ZERO_ENV_VAR_PREFIX} from '../config/zero-config.ts';\nimport {getPublicationInfo} from '../services/change-source/pg/schema/published.ts';\nimport {\n ensureGlobalTables,\n SHARD_CONFIG_TABLE,\n} from '../services/change-source/pg/schema/shard.ts';\nimport {liteTableName} from '../types/names.ts';\nimport {pgClient, type PostgresDB} from '../types/pg.ts';\nimport {appSchema, getShardID, upstreamSchema} from '../types/shards.ts';\nimport {\n deployPermissionsOptions,\n loadSchemaAndPermissions,\n} from './permissions.ts';\n\nconst config = parseOptions(deployPermissionsOptions, {\n argv: process.argv.slice(2),\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n});\n\nconst shard = getShardID(config);\nconst app = appSchema(shard);\n\nconst lc = createLogContext(config);\n\nasync function validatePermissions(\n db: PostgresDB,\n permissions: PermissionsConfig,\n) {\n const schema = upstreamSchema(shard);\n\n // Check if the shardConfig table has been initialized.\n const result = await db`\n SELECT relname FROM pg_class\n JOIN pg_namespace ON relnamespace = pg_namespace.oid\n WHERE nspname = ${schema} AND relname = ${SHARD_CONFIG_TABLE}`;\n if (result.length === 0) {\n colorConsole.warn(\n `zero-cache has not yet initialized the upstream database.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n\n // Get the publications for the shard\n const config = await db<{publications: string[]}[]>`\n SELECT publications FROM ${db(schema + '.' + SHARD_CONFIG_TABLE)}\n `;\n if (config.length === 0) {\n colorConsole.warn(\n `zero-cache has not yet initialized the upstream database.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n colorConsole.info(\n `Validating permissions against tables and columns published for \"${app}\".`,\n );\n\n const [{publications: shardPublications}] = config;\n const {tables, publications} = await getPublicationInfo(\n db,\n shardPublications,\n );\n const pubnames = publications.map(p => p.pubname);\n const missing = difference(new Set(shardPublications), new Set(pubnames));\n if (missing.size) {\n colorConsole.warn(\n `Upstream is missing expected publications \"${[...missing]}\".\\n` +\n `You may need to re-initialize your replica.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n const tablesToColumns = new Map(\n tables.map(t => [liteTableName(t), Object.keys(t.columns)]),\n );\n const validate = validator(tablesToColumns);\n try {\n for (const [table, perms] of Object.entries(permissions.tables)) {\n const validateRule = ([_, cond]: Rule) => {\n mapCondition(cond, table, validate);\n };\n const validateAsset = (asset: AssetPermissions | undefined) => {\n asset?.select?.forEach(validateRule);\n asset?.delete?.forEach(validateRule);\n asset?.insert?.forEach(validateRule);\n asset?.update?.preMutation?.forEach(validateRule);\n asset?.update?.postMutation?.forEach(validateRule);\n };\n validateAsset(perms.row);\n if (perms.cell) {\n Object.values(perms.cell).forEach(validateAsset);\n }\n }\n } catch (e) {\n failWithMessage(String(e));\n }\n}\n\nfunction failWithMessage(msg: string) {\n colorConsole.error(msg);\n colorConsole.info('\\nUse --force to deploy at your own risk.\\n');\n process.exit(-1);\n}\n\nasync function deployPermissions(\n upstreamURI: string,\n permissions: PermissionsConfig,\n force: boolean,\n) {\n const db = pgClient(lc, upstreamURI);\n const {host, port} = db.options;\n colorConsole.debug(`Connecting to upstream@${host}:${port}`);\n try {\n await ensureGlobalTables(db, shard);\n\n const {hash, changed} = await db.begin(async tx => {\n if (force) {\n colorConsole.warn(`--force specified. Skipping validation.`);\n } else {\n await validatePermissions(tx, permissions);\n }\n\n const {appID} = shard;\n colorConsole.info(\n `Deploying permissions for --app-id \"${appID}\" to upstream@${db.options.host}`,\n );\n const [{hash: beforeHash}] = await tx<{hash: string}[]>`\n SELECT hash from ${tx(app)}.permissions`;\n const [{hash}] = await tx<{hash: string}[]>`\n UPDATE ${tx(app)}.permissions SET ${db({permissions})} RETURNING hash`;\n\n return {hash: hash.substring(0, 7), changed: beforeHash !== hash};\n });\n if (changed) {\n colorConsole.info(`Deployed new permissions (hash=${hash})`);\n } else {\n colorConsole.info(`Permissions unchanged (hash=${hash})`);\n }\n } finally {\n await db.end();\n }\n}\n\nasync function writePermissionsFile(\n perms: PermissionsConfig,\n file: string,\n format: 'sql' | 'json' | 'pretty',\n) {\n const contents =\n format === 'sql'\n ? `UPDATE ${id(app)}.permissions SET permissions = ${literal(\n JSON.stringify(perms),\n )};`\n : JSON.stringify(perms, null, format === 'pretty' ? 2 : 0);\n await writeFile(file, contents);\n colorConsole.info(`Wrote ${format} permissions to ${config.output.file}`);\n}\n\nconst ret = await loadSchemaAndPermissions(config.schema.path, true);\nif (!ret) {\n colorConsole.warn(\n `No schema found at ${config.schema.path}, so could not deploy ` +\n `permissions. Replicating data, but no tables will be syncable. ` +\n `Create a schema file with permissions to be able to sync data.`,\n );\n} else {\n const {permissions} = ret;\n if (config.output.file) {\n await writePermissionsFile(\n permissions,\n config.output.file,\n config.output.format,\n );\n } else if (config.upstream.type !== 'pg') {\n colorConsole.warn(\n `Permissions deployment is not supported for ${config.upstream.type} upstreams`,\n );\n process.exit(-1);\n } else if (config.upstream.db) {\n await deployPermissions(config.upstream.db, permissions, config.force);\n } else {\n colorConsole.error(`No --output-file or --upstream-db specified`);\n // Shows the usage text.\n parseOptions(deployPermissionsOptions, {\n argv: ['--help'],\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n });\n }\n}\n"],"names":["config","hash","id"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,SAAS,aAAa,0BAA0B;AAAA,EACpD,MAAM,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC1B,eAAe;AACjB,CAAC;AAED,MAAM,QAAQ,WAAW,MAAM;AAC/B,MAAM,MAAM,UAAU,KAAK;AAE3B,MAAM,KAAK,iBAAiB,MAAM;AAElC,eAAe,oBACb,IACA,aACA;AACA,QAAM,SAAS,eAAe,KAAK;AAGnC,QAAM,SAAS,MAAM;AAAA;AAAA;AAAA,wBAGC,MAAM,kBAAkB,kBAAkB;AAChE,MAAI,OAAO,WAAW,GAAG;AACvB,iBAAa;AAAA,MACX;AAAA,YACe,GAAG;AAAA,IAAA;AAEpB;AAAA,EACF;AAGA,QAAMA,UAAS,MAAM;AAAA,+BACQ,GAAG,SAAS,MAAM,kBAAkB,CAAC;AAAA;AAElE,MAAIA,QAAO,WAAW,GAAG;AACvB,iBAAa;AAAA,MACX;AAAA,YACe,GAAG;AAAA,IAAA;AAEpB;AAAA,EACF;AACA,eAAa;AAAA,IACX,oEAAoE,GAAG;AAA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QAAQ;AAC9B,eAAa,KAAK,SAAS,MAAM,mBAAmB,OAAO,OAAO,IAAI,EAAE;AAC1E;AAEA,MAAM,MAAM,MAAM,yBAAyB,OAAO,OAAO,MAAM,IAAI;AACnE,IAAI,CAAC,KAAK;AACR,eAAa;AAAA,IACX,sBAAsB,OAAO,OAAO,IAAI;AAAA,EAAA;AAI5C,OAAO;AACL,QAAM,EAAC,gBAAe;AACtB,MAAI,OAAO,OAAO,MAAM;AACtB,UAAM;AAAA,MACJ;AAAA,MACA,OAAO,OAAO;AAAA,MACd,OAAO,OAAO;AAAA,IAAA;AAAA,EAElB,WAAW,OAAO,SAAS,SAAS,MAAM;AACxC,iBAAa;AAAA,MACX,+CAA+C,OAAO,SAAS,IAAI;AAAA,IAAA;AAErE,YAAQ,KAAK,EAAE;AAAA,EACjB,WAAW,OAAO,SAAS,IAAI;AAC7B,UAAM,kBAAkB,OAAO,SAAS,IAAI,aAAa,OAAO,KAAK;AAAA,EACvE,OAAO;AACL,iBAAa,MAAM,6CAA6C;AAEhE,iBAAa,0BAA0B;AAAA,MACrC,MAAM,CAAC,QAAQ;AAAA,MACf,eAAe;AAAA,IAAA,CAChB;AAAA,EACH;AACF;"}
1
+ {"version":3,"file":"deploy-permissions.js","sources":["../../../../../zero-cache/src/scripts/deploy-permissions.ts"],"sourcesContent":["import '../../../shared/src/dotenv.ts';\n\nimport {writeFile} from 'node:fs/promises';\nimport {ident as id, literal} from 'pg-format';\nimport {colorConsole, createLogContext} from '../../../shared/src/logging.ts';\nimport {parseOptions} from '../../../shared/src/options.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {mapCondition} from '../../../zero-protocol/src/ast.ts';\nimport {\n type AssetPermissions,\n type PermissionsConfig,\n type Rule,\n} from '../../../zero-schema/src/compiled-permissions.ts';\nimport {validator} from '../../../zero-schema/src/name-mapper.ts';\nimport {ZERO_ENV_VAR_PREFIX} from '../config/zero-config.ts';\nimport {getPublicationInfo} from '../services/change-source/pg/schema/published.ts';\nimport {\n ensureGlobalTables,\n SHARD_CONFIG_TABLE,\n} from '../services/change-source/pg/schema/shard.ts';\nimport {liteTableName} from '../types/names.ts';\nimport {pgClient, type PostgresDB} from '../types/pg.ts';\nimport {appSchema, getShardID, upstreamSchema} from '../types/shards.ts';\nimport {\n deployPermissionsOptions,\n loadSchemaAndPermissions,\n} from './permissions.ts';\n\nconst config = parseOptions(deployPermissionsOptions, {\n argv: process.argv.slice(2),\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n});\n\nconst shard = getShardID(config);\nconst app = appSchema(shard);\n\nconst lc = createLogContext(config);\n\nasync function validatePermissions(\n db: PostgresDB,\n permissions: PermissionsConfig,\n) {\n const schema = upstreamSchema(shard);\n\n // Check if the shardConfig table has been initialized.\n const result = await db`\n SELECT relname FROM pg_class\n JOIN pg_namespace ON relnamespace = pg_namespace.oid\n WHERE nspname = ${schema} AND relname = ${SHARD_CONFIG_TABLE}`;\n if (result.length === 0) {\n colorConsole.warn(\n `zero-cache has not yet initialized the upstream database.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n\n // Get the publications for the shard\n const config = await db<{publications: string[]}[]>`\n SELECT publications FROM ${db(schema + '.' + SHARD_CONFIG_TABLE)}\n `;\n if (config.length === 0) {\n colorConsole.warn(\n `zero-cache has not yet initialized the upstream database.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n colorConsole.info(\n `Validating permissions against tables and columns published for \"${app}\".`,\n );\n\n const [{publications: shardPublications}] = config;\n const {tables, publications} = await getPublicationInfo(\n db,\n shardPublications,\n );\n const pubnames = publications.map(p => p.pubname);\n const missing = difference(new Set(shardPublications), new Set(pubnames));\n if (missing.size) {\n colorConsole.warn(\n `Upstream is missing expected publications \"${[...missing]}\".\\n` +\n `You may need to re-initialize your replica.\\n` +\n `Deploying ${app} permissions without validating against published tables/columns.`,\n );\n return;\n }\n const tablesToColumns = new Map(\n tables.map(t => [liteTableName(t), Object.keys(t.columns)]),\n );\n const validate = validator(tablesToColumns);\n try {\n for (const [table, perms] of Object.entries(permissions?.tables ?? {})) {\n const validateRule = ([_, cond]: Rule) => {\n mapCondition(cond, table, validate);\n };\n const validateAsset = (asset: AssetPermissions | undefined) => {\n asset?.select?.forEach(validateRule);\n asset?.delete?.forEach(validateRule);\n asset?.insert?.forEach(validateRule);\n asset?.update?.preMutation?.forEach(validateRule);\n asset?.update?.postMutation?.forEach(validateRule);\n };\n validateAsset(perms.row);\n if (perms.cell) {\n Object.values(perms.cell).forEach(validateAsset);\n }\n }\n } catch (e) {\n failWithMessage(String(e));\n }\n}\n\nfunction failWithMessage(msg: string) {\n colorConsole.error(msg);\n colorConsole.info('\\nUse --force to deploy at your own risk.\\n');\n process.exit(-1);\n}\n\nasync function deployPermissions(\n upstreamURI: string,\n permissions: PermissionsConfig,\n force: boolean,\n) {\n const db = pgClient(lc, upstreamURI);\n const {host, port} = db.options;\n colorConsole.debug(`Connecting to upstream@${host}:${port}`);\n try {\n await ensureGlobalTables(db, shard);\n\n const {hash, changed} = await db.begin(async tx => {\n if (force) {\n colorConsole.warn(`--force specified. Skipping validation.`);\n } else {\n await validatePermissions(tx, permissions);\n }\n\n const {appID} = shard;\n colorConsole.info(\n `Deploying permissions for --app-id \"${appID}\" to upstream@${db.options.host}`,\n );\n const [{hash: beforeHash}] = await tx<{hash: string}[]>`\n SELECT hash from ${tx(app)}.permissions`;\n const [{hash}] = await tx<{hash: string}[]>`\n UPDATE ${tx(app)}.permissions SET ${db({permissions})} RETURNING hash`;\n\n return {hash: hash.substring(0, 7), changed: beforeHash !== hash};\n });\n if (changed) {\n colorConsole.info(`Deployed new permissions (hash=${hash})`);\n } else {\n colorConsole.info(`Permissions unchanged (hash=${hash})`);\n }\n } finally {\n await db.end();\n }\n}\n\nasync function writePermissionsFile(\n perms: PermissionsConfig,\n file: string,\n format: 'sql' | 'json' | 'pretty',\n) {\n const contents =\n format === 'sql'\n ? `UPDATE ${id(app)}.permissions SET permissions = ${literal(\n JSON.stringify(perms),\n )};`\n : JSON.stringify(perms, null, format === 'pretty' ? 2 : 0);\n await writeFile(file, contents);\n colorConsole.info(`Wrote ${format} permissions to ${config.output.file}`);\n}\n\nconst ret = await loadSchemaAndPermissions(config.schema.path, true);\nif (!ret || Object.keys(ret?.permissions ?? {}).length === 0) {\n colorConsole.warn(\n `No permissions found at ${config.schema.path}, so could not deploy ` +\n `permissions. Replicating data, but no tables will be syncable. ` +\n `Create a schema file with permissions to be able to sync data.`,\n );\n} else {\n colorConsole.warn(\n `Permissions are deprecated and will be removed in an upcoming release. See: https://zero.rocicorp.dev/docs/auth.`,\n );\n\n const {permissions} = ret;\n if (config.output.file) {\n await writePermissionsFile(\n permissions,\n config.output.file,\n config.output.format,\n );\n } else if (config.upstream.type !== 'pg') {\n colorConsole.warn(\n `Permissions deployment is not supported for ${config.upstream.type} upstreams`,\n );\n process.exit(-1);\n } else if (config.upstream.db) {\n await deployPermissions(config.upstream.db, permissions, config.force);\n } else {\n colorConsole.error(`No --output-file or --upstream-db specified`);\n // Shows the usage text.\n parseOptions(deployPermissionsOptions, {\n argv: ['--help'],\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n });\n }\n}\n"],"names":["config","hash","id"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,SAAS,aAAa,0BAA0B;AAAA,EACpD,MAAM,QAAQ,KAAK,MAAM,CAAC;AAAA,EAC1B,eAAe;AACjB,CAAC;AAED,MAAM,QAAQ,WAAW,MAAM;AAC/B,MAAM,MAAM,UAAU,KAAK;AAE3B,MAAM,KAAK,iBAAiB,MAAM;AAElC,eAAe,oBACb,IACA,aACA;AACA,QAAM,SAAS,eAAe,KAAK;AAGnC,QAAM,SAAS,MAAM;AAAA;AAAA;AAAA,wBAGC,MAAM,kBAAkB,kBAAkB;AAChE,MAAI,OAAO,WAAW,GAAG;AACvB,iBAAa;AAAA,MACX;AAAA,YACe,GAAG;AAAA,IAAA;AAEpB;AAAA,EACF;AAG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;AACF;AAEA,eAAe,qBACb,OACA,MACA,QACA;AACA,QAAM,WACJ,WAAW,QACP,UAAUC,MAAG,GAAG,CAAC,kCAAkC;AAAA,IACjD,KAAK,UAAU,KAAK;AAAA,EAAA,CACrB,MACD,KAAK,UAAU,OAAO,MAAM,WAAW,WAAW,IAAI,CAAC;AAC7D,QAAM,UAAU,MAAM,QAAQ;AAC9B,eAAa,KAAK,SAAS,MAAM,mBAAmB,OAAO,OAAO,IAAI,EAAE;AAC1E;AAEA,MAAM,MAAM,MAAM,yBAAyB,OAAO,OAAO,MAAM,IAAI;AACnE,IAAI,CAAC,OAAO,OAAO,KAAK,KAAK,eAAe,CAAA,CAAE,EAAE,WAAW,GAAG;AAC5D,eAAa;AAAA,IACX,2BAA2B,OAAO,OAAO,IAAI;AAAA,EAAA;AAIjD,OAAO;AACL,eAAa;AAAA,IACX;AAAA,EAAA;AAGF,QAAM,EAAC,gBAAe;AACtB,MAAI,OAAO,OAAO,MAAM;AACtB,UAAM;AAAA,MACJ;AAAA,MACA,OAAO,OAAO;AAAA,MACd,OAAO,OAAO;AAAA,IAAA;AAAA,EAElB,WAAW,OAAO,SAAS,SAAS,MAAM;AACxC,iBAAa;AAAA,MACX,+CAA+C,OAAO,SAAS,IAAI;AAAA,IAAA;AAErE,YAAQ,KAAK,EAAE;AAAA,EACjB,WAAW,OAAO,SAAS,IAAI;AAC7B,UAAM,kBAAkB,OAAO,SAAS,IAAI,aAAa,OAAO,KAAK;AAAA,EACvE,OAAO;AACL,iBAAa,MAAM,6CAA6C;AAEhE,iBAAa,0BAA0B;AAAA,MACrC,MAAM,CAAC,QAAQ;AAAA,MACf,eAAe;AAAA,IAAA,CAChB;AAAA,EACH;AACF;"}
@@ -1 +1 @@
1
- {"version":3,"file":"permissions.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/scripts/permissions.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AACnD,OAAO,EAEL,KAAK,i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AAC,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,iBAAiB,CAAA;CAAC,CAAC,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
- import { dirname, resolve, relative, join, sep, basename } from "node:path";
2
+ import { dirname, resolve, relative, join, basename, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { tsImport } from "tsx/esm/api";
5
5
  import { logOptions } from "../../../otel/src/log-options.js";
@@ -13,10 +13,7 @@ const deployPermissionsOptions = {
13
13
  schema: {
14
14
  path: {
15
15
  type: string().default("schema.ts"),
16
- desc: [
17
- "Relative path to the file containing the schema definition.",
18
- "The file must have a default export of type SchemaConfig."
19
- ],
16
+ desc: ["Relative path to the file containing the schema definition."],
20
17
  alias: "p"
21
18
  }
22
19
  },
@@ -64,15 +61,11 @@ async function loadSchemaAndPermissions(schemaPath, allowMissing) {
64
61
 
65
62
  You may need to add \` "type": "module" \` to the package.json file for ${schemaPath}.
66
63
  `;
67
- colorConsole.info(`Loading permissions from ${schemaPath}`);
64
+ colorConsole.info(`Loading schema from ${schemaPath}`);
68
65
  const dir = dirname(fileURLToPath(import.meta.url));
69
66
  const absoluteSchemaPath = resolve(schemaPath);
70
67
  const relativeDir = relative(dir, dirname(absoluteSchemaPath));
71
- let relativePath = join(
72
- // tsImport expects the relativePath to be a path and not just a filename.
73
- relativeDir.length ? relativeDir : `.${sep}`,
74
- basename(absoluteSchemaPath)
75
- );
68
+ let relativePath = relativeDir.length && relativeDir !== "." ? join(relativeDir, basename(absoluteSchemaPath)) : `.${sep}${basename(absoluteSchemaPath)}`;
76
69
  relativePath = relativePath.replace(/\\/g, "/");
77
70
  if (!existsSync(absoluteSchemaPath)) {
78
71
  if (allowMissing) {
@@ -92,7 +85,7 @@ You may need to add \` "type": "module" \` to the package.json file for ${schema
92
85
  }
93
86
  if (!isSchemaConfig(module)) {
94
87
  colorConsole.error(
95
- `Schema file ${schemaPath} must export [schema] and [permissions].` + typeModuleErrorMessage()
88
+ `Schema file ${schemaPath} must export [schema].` + typeModuleErrorMessage()
96
89
  );
97
90
  process.exit(1);
98
91
  }
@@ -100,9 +93,14 @@ You may need to add \` "type": "module" \` to the package.json file for ${schema
100
93
  const schemaConfig = module;
101
94
  const perms = await schemaConfig.permissions;
102
95
  const { schema } = schemaConfig;
96
+ if (perms) {
97
+ colorConsole.warn?.(
98
+ "Permissions are deprecated and will be removed in an upcoming release. See: https://zero.rocicorp.dev/docs/auth."
99
+ );
100
+ }
103
101
  return {
104
102
  schema,
105
- permissions: parse(perms, permissionsConfigSchema)
103
+ permissions: parse(perms ?? {}, permissionsConfigSchema)
106
104
  };
107
105
  } catch (e) {
108
106
  colorConsole.error(`Failed to parse Permissions object`);