@rebasepro/types 0.29.1 → 0.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -286,6 +286,19 @@ function isRelationAggregateSort(key) {
286
286
  function sortKeyToString(key) {
287
287
  return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;
288
288
  }
289
+ /**
290
+ * Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or
291
+ * `undefined` for any other key.
292
+ *
293
+ * @group Models
294
+ */
295
+ function parseCaseFoldedFieldPath(key) {
296
+ const match = /^(lower|upper)\(\s*([^()\s]+)\s*\)$/.exec(key);
297
+ return match ? {
298
+ fn: match[1],
299
+ field: match[2]
300
+ } : void 0;
301
+ }
289
302
  /** Maps canonical operators to their REST short-code equivalents. */
290
303
  var CANONICAL_TO_REST = {
291
304
  "==": "eq",
@@ -1099,6 +1112,69 @@ var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_
1099
1112
  /** The request's roles as a comma-separated string, for `string_to_array`. */
1100
1113
  var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
1101
1114
  /**
1115
+ * The Postgres role that policies granting only the server context or admins
1116
+ * are written `TO`: the injected `<table>_default_admin_*` baseline, and any
1117
+ * permissive rule whose every clause requires one of the two (`roles: ["admin"]`).
1118
+ *
1119
+ * Postgres ORs the permissive policies that apply to the current role. Written
1120
+ * `TO public`, the baseline applied to every signed-in user too, as
1121
+ * `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement
1122
+ * constant arm cannot use the owner index, so a user's owner-scoped list or
1123
+ * count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`
1124
+ * this role, the policy is not in a user's plan at all.
1125
+ *
1126
+ * It holds no privilege and cannot log in: being in it only decides which
1127
+ * policies apply, and those still test `rebase.uid() IS NULL` or the `admin`
1128
+ * role. Admin requests switch to a request role that inherits it
1129
+ * ({@link adminRequestRoleFor}); a connection that is itself subject to RLS
1130
+ * inherits it for the server context. One fixed name, so the policy text is the
1131
+ * same in every deployment and every generated migration. FROZEN.
1132
+ */
1133
+ var REBASE_ADMIN_ROLE = "rebase_admin";
1134
+ /**
1135
+ * The role the admin request roles ({@link adminRequestRoleFor}) inherit and
1136
+ * nothing else does, so an admin-only grant can apply to admin REQUESTS alone.
1137
+ *
1138
+ * {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for
1139
+ * the server context, and so would any process on it that does not switch
1140
+ * roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the
1141
+ * `admin` role) — and any policy expression that is not a constant is a
1142
+ * security barrier, behind which Postgres will not evaluate a non-leakproof
1143
+ * operator as an index condition. An admin's `tags && $1`, `name ~ $1` or
1144
+ * jsonb filter scanned the whole table where the owner's used the index.
1145
+ *
1146
+ * Each admin-only grant gets a companion `TO` this role `USING (true)`.
1147
+ * Postgres folds the OR of the permissive policies to `true` for a member, the
1148
+ * barrier goes, and an admin request plans as the owner's does; restrictive
1149
+ * policies still apply. Membership is the boundary: only the admin request
1150
+ * roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from
1151
+ * PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds
1152
+ * those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with
1153
+ * its privileges revokes every membership, and the companions admit nobody.
1154
+ * One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.
1155
+ */
1156
+ var REBASE_ADMIN_REQUEST_ROLE = "rebase_admin_request";
1157
+ /**
1158
+ * The role an admin request runs as, for a signed-in request role: it inherits
1159
+ * that role (its grants and every policy written for it) and
1160
+ * {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared
1161
+ * `rebase_admin` itself, because roles belong to the cluster: a project with a
1162
+ * request role of its own (`rls.requestRole`) would otherwise share its admin
1163
+ * access with every other project on the cluster. FROZEN derivation.
1164
+ */
1165
+ function adminRequestRoleFor(requestRole) {
1166
+ return `${requestRole}_admin`;
1167
+ }
1168
+ /**
1169
+ * Whether a request with these roles passes `rolesOverlap(["admin"])` — the
1170
+ * test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the
1171
+ * comma-joined `app.user_roles`, so a role name with a comma in it is split
1172
+ * exactly as Postgres splits it.
1173
+ */
1174
+ function holdsAdminRole(roles) {
1175
+ return roles.join(",").split(",").includes("admin");
1176
+ }
1177
+ /**
1102
1178
  * Whether the caller is a GUEST — signed in through anonymous sign-in rather
1103
1179
  * than with an account.
1104
1180
  *
@@ -1971,8 +2047,9 @@ function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
1971
2047
  * The policy settings every compile path must agree on — the boot's policy
1972
2048
  * ensure, `rebase db generate`, the drift check — read from the one place all
1973
2049
  * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
1974
- * `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults are what Rebase compiled
1975
- * before these existed.
2050
+ * `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults
2051
+ * are what Rebase compiled before these existed, except `adminPolicies`, whose
2052
+ * default (`"adminRole"`) changed what the server-or-admin policies are `TO`.
1976
2053
  *
1977
2054
  * Browser-safe: where there is no `process`, only the declaration counts.
1978
2055
  */
@@ -1980,9 +2057,11 @@ function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
1980
2057
  const declared = declaredDatabaseRls(dataSource);
1981
2058
  const env = typeof process !== "undefined" ? process.env : void 0;
1982
2059
  const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();
2060
+ const envAdmin = env?.REBASE_RLS_ADMIN_POLICIES?.trim();
1983
2061
  const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();
1984
2062
  return {
1985
2063
  policyTarget: envTarget === "requestRole" || envTarget === "public" ? envTarget : declared.policyTarget === "requestRole" ? "requestRole" : "public",
2064
+ adminPolicies: envAdmin === "adminRole" || envAdmin === "public" ? envAdmin : declared.adminPolicies === "public" ? "public" : "adminRole",
1986
2065
  defaultPolicies: envDefaults === "false" ? false : envDefaults === "true" ? true : declared.defaultPolicies !== false
1987
2066
  };
1988
2067
  }
@@ -4019,7 +4098,11 @@ function aggregateAlias(fn, field, p) {
4019
4098
  function isPercentileFraction(p) {
4020
4099
  return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1e3) - p * 1e3) < 1e-9;
4021
4100
  }
4022
- /** An `AggregateSelect` as a driver is handed it. */
4101
+ /**
4102
+ * An `AggregateSelect` as a driver is handed it — but for its `where`, which
4103
+ * the caller decodes into the driver's `filter` (this package has no filter
4104
+ * codec).
4105
+ */
4023
4106
  function toDriverAggregate(select) {
4024
4107
  const field = "field" in select ? select.field : void 0;
4025
4108
  const p = select.fn === "percentile" ? select.p : void 0;
@@ -4027,9 +4110,19 @@ function toDriverAggregate(select) {
4027
4110
  fn: select.fn,
4028
4111
  ...field !== void 0 ? { field } : {},
4029
4112
  ...p !== void 0 ? { p } : {},
4030
- alias: aggregateAlias(select.fn, field, p)
4113
+ alias: select.as ?? aggregateAlias(select.fn, field, p)
4031
4114
  };
4032
4115
  }
4116
+ /** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */
4117
+ function isTimeZoneName(timeZone) {
4118
+ if (typeof timeZone !== "string" || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timeZone)) return false;
4119
+ try {
4120
+ new Intl.DateTimeFormat("en-US", { timeZone });
4121
+ return true;
4122
+ } catch {
4123
+ return false;
4124
+ }
4125
+ }
4033
4126
  /** The key a group comes back under: the column's name, or `<transform>_<field>`. */
4034
4127
  function aggregateGroupKey(group) {
4035
4128
  return typeof group === "string" ? group : `${group.transform}_${group.field}`;
@@ -4039,10 +4132,11 @@ function toDriverAggregateGroup(group) {
4039
4132
  return typeof group === "string" ? group : {
4040
4133
  field: group.field,
4041
4134
  transform: group.transform,
4135
+ ...group.timeZone ? { timeZone: group.timeZone } : {},
4042
4136
  key: aggregateGroupKey(group)
4043
4137
  };
4044
4138
  }
4045
4139
  //#endregion
4046
- export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
4140
+ export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, holdsAdminRole, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isTimeZoneName, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
4047
4141
 
4048
4142
  //# sourceMappingURL=index.es.js.map