@rebasepro/types 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -401,6 +401,16 @@ export type FilterCombinationValidProps = {
401
401
  filterValues: FilterValues<string>;
402
402
  sortBy?: [string, "asc" | "desc"];
403
403
  };
404
+ /** Options of {@link DataDriver.sql}. */
405
+ export interface CallerSqlOptions {
406
+ /** The statement's values, referenced as `$1`, `$2`, … in the query text. */
407
+ params?: unknown[];
408
+ /**
409
+ * Run in a read-write transaction. Off by default: the statement runs
410
+ * read-only, and an `INSERT`, `UPDATE` or `DELETE` fails with `25006`.
411
+ */
412
+ write?: boolean;
413
+ }
404
414
  /**
405
415
  * The integration SPI for plugging a data backend into Rebase.
406
416
  *
@@ -626,6 +636,26 @@ export interface DataDriver {
626
636
  * Optional: a driver without it is called directly, read by read.
627
637
  */
628
638
  readTogether?<T>(work: (driver: DataDriver) => Promise<T>): Promise<T>;
639
+ /**
640
+ * Run one SQL statement as this driver's identity: in the caller's own
641
+ * transaction, under the same row-level security as every read and write
642
+ * on this driver, so the tables' policies decide which rows it sees and
643
+ * changes. Read-only unless `write: true`.
644
+ *
645
+ * The query text must be the application's own. Every value — above all
646
+ * anything a user sent — goes in `params` as `$1`, `$2`, …: identity rides
647
+ * in session settings, and a statement able to change them is refused
648
+ * (`SQL_NOT_ALLOWED`), as is more than one statement.
649
+ *
650
+ * Policies are what it shares with the SDK, and all it shares. Per-field
651
+ * `access` rules, `afterRead`/`beforeQuery` hooks, validation, save hooks
652
+ * and history are application code the SDK runs and this does not.
653
+ *
654
+ * Optional: an engine without row-level security has none. On the
655
+ * server's own (unscoped) driver it is absent too — that one's raw SQL is
656
+ * `admin.executeSql`, which runs as the owner.
657
+ */
658
+ sql?(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;
629
659
  /**
630
660
  * Every row a collection stores, as stored, a page at a time: soft-deleted
631
661
  * rows included, and past every read hook — no `beforeQuery`, no
package/dist/index.es.js CHANGED
@@ -1087,6 +1087,15 @@ var REBASE_SCHEMA = "rebase";
1087
1087
  * the trusted server plane and `IS NOT NULL` a tautology.
1088
1088
  */
1089
1089
  var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
1090
+ /**
1091
+ * Is the caller one of this database's request roles? What a permissive
1092
+ * policy is ANDed with under `rls.policyTarget: "requestRole"`, so another
1093
+ * application's role holding a grant on the table gets nothing from it.
1094
+ * `current_user` is passed in — inside the function, which reads the recorded
1095
+ * roles with its owner's rights, `current_user` would be the owner — and the
1096
+ * sub-select makes it one evaluation per statement, not one per row.
1097
+ */
1098
+ var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;
1090
1099
  /** The request's roles as a comma-separated string, for `string_to_array`. */
1091
1100
  var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
1092
1101
  /**
@@ -1910,17 +1919,25 @@ registerResourceKind({
1910
1919
  ],
1911
1920
  implicitDefault: true
1912
1921
  });
1913
- amendResourceKind("database", { envBases: [
1914
- "DATABASE_URL",
1915
- "DATABASE_READ_URL",
1916
- "DATABASE_DIRECT_URL",
1917
- "DATABASE_POOLED",
1918
- "ADMIN_CONNECTION_STRING",
1919
- "REBASE_DRIVER",
1920
- "DB_POOL_MAX",
1921
- "DB_POOL_IDLE_TIMEOUT",
1922
- "DB_POOL_CONNECT_TIMEOUT"
1923
- ] });
1922
+ amendResourceKind("database", {
1923
+ optionKeys: [
1924
+ "databaseId",
1925
+ "migrations",
1926
+ "extensions",
1927
+ "rls"
1928
+ ],
1929
+ envBases: [
1930
+ "DATABASE_URL",
1931
+ "DATABASE_READ_URL",
1932
+ "DATABASE_DIRECT_URL",
1933
+ "DATABASE_POOLED",
1934
+ "ADMIN_CONNECTION_STRING",
1935
+ "REBASE_DRIVER",
1936
+ "DB_POOL_MAX",
1937
+ "DB_POOL_IDLE_TIMEOUT",
1938
+ "DB_POOL_CONNECT_TIMEOUT"
1939
+ ]
1940
+ });
1924
1941
  function database(keyOrOptions = DEFAULT_RESOURCE_KEY, options = {}) {
1925
1942
  return typeof keyOrOptions === "string" ? declareResource("database", keyOrOptions, options) : declareResource("database", DEFAULT_RESOURCE_KEY, keyOrOptions);
1926
1943
  }
@@ -1945,6 +1962,30 @@ function declaredDatabaseExtensions() {
1945
1962
  }
1946
1963
  return [...names].sort();
1947
1964
  }
1965
+ /** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
1966
+ function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
1967
+ const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
1968
+ return rls && typeof rls === "object" ? rls : {};
1969
+ }
1970
+ /**
1971
+ * The policy settings every compile path must agree on — the boot's policy
1972
+ * ensure, `rebase db generate`, the drift check — read from the one place all
1973
+ * 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.
1976
+ *
1977
+ * Browser-safe: where there is no `process`, only the declaration counts.
1978
+ */
1979
+ function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
1980
+ const declared = declaredDatabaseRls(dataSource);
1981
+ const env = typeof process !== "undefined" ? process.env : void 0;
1982
+ const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();
1983
+ const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();
1984
+ return {
1985
+ policyTarget: envTarget === "requestRole" || envTarget === "public" ? envTarget : declared.policyTarget === "requestRole" ? "requestRole" : "public",
1986
+ defaultPolicies: envDefaults === "false" ? false : envDefaults === "true" ? true : declared.defaultPolicies !== false
1987
+ };
1988
+ }
1948
1989
  registerResourceKind({
1949
1990
  kind: "bucket",
1950
1991
  engines: [
@@ -4002,6 +4043,6 @@ function toDriverAggregateGroup(group) {
4002
4043
  };
4003
4044
  }
4004
4045
  //#endregion
4005
- 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_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, declaredQueueConsumers, declaredResources, 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 };
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 };
4006
4047
 
4007
4048
  //# sourceMappingURL=index.es.js.map