@venizia/ignis-connectors 0.4.8-0 → 0.4.8-10
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/README.md +4 -2
- package/dist/esm/common/driver-data-source.d.ts +13 -6
- package/dist/esm/common/driver-data-source.js +71 -10
- package/dist/esm/common/driver-data-source.js.map +1 -1
- package/dist/esm/common/internal/index.d.ts +0 -1
- package/dist/esm/common/internal/index.js +0 -1
- package/dist/esm/common/internal/index.js.map +1 -1
- package/dist/esm/common/scope-filter.d.ts +1 -0
- package/dist/esm/common/scope-filter.js +1 -0
- package/dist/esm/common/scope-filter.js.map +1 -1
- package/dist/esm/http/common/types.d.ts +8 -0
- package/dist/esm/http/common/types.js.map +1 -1
- package/dist/esm/http/datasource.d.ts +13 -0
- package/dist/esm/http/datasource.js +54 -0
- package/dist/esm/http/datasource.js.map +1 -1
- package/dist/esm/http/repository.d.ts +8 -42
- package/dist/esm/http/repository.js +0 -8
- package/dist/esm/http/repository.js.map +1 -1
- package/dist/esm/relational/core/datasources/abstract.d.ts +2 -0
- package/dist/esm/relational/core/datasources/abstract.js +4 -0
- package/dist/esm/relational/core/datasources/abstract.js.map +1 -1
- package/dist/esm/relational/core/datasources/base.d.ts +5 -1
- package/dist/esm/relational/core/datasources/base.js +12 -0
- package/dist/esm/relational/core/datasources/base.js.map +1 -1
- package/dist/esm/relational/core/datasources/common/types.d.ts +19 -2
- package/dist/esm/relational/core/datasources/common/types.js.map +1 -1
- package/dist/esm/relational/core/datasources/transaction-lifecycle.d.ts +2 -0
- package/dist/esm/relational/core/datasources/transaction-lifecycle.js +1 -0
- package/dist/esm/relational/core/datasources/transaction-lifecycle.js.map +1 -1
- package/dist/esm/relational/core/drivers/driver.d.ts +12 -0
- package/dist/esm/relational/core/drivers/driver.js +9 -1
- package/dist/esm/relational/core/drivers/driver.js.map +1 -1
- package/dist/esm/relational/core/migrations/runner.d.ts +33 -3
- package/dist/esm/relational/core/migrations/runner.js +114 -23
- package/dist/esm/relational/core/migrations/runner.js.map +1 -1
- package/dist/esm/relational/core/models/base.d.ts +0 -2
- package/dist/esm/relational/core/models/base.js +0 -10
- package/dist/esm/relational/core/models/base.js.map +1 -1
- package/dist/esm/relational/core/models/common/types.d.ts +30 -1
- package/dist/esm/relational/core/models/common/types.js +1 -0
- package/dist/esm/relational/core/models/common/types.js.map +1 -1
- package/dist/esm/relational/core/models/common/unique-key-reader.d.ts +32 -0
- package/dist/esm/relational/core/models/common/unique-key-reader.js +140 -0
- package/dist/esm/relational/core/models/common/unique-key-reader.js.map +1 -0
- package/dist/esm/relational/core/models/factory.d.ts +14 -0
- package/dist/esm/relational/core/models/factory.js +14 -0
- package/dist/esm/relational/core/models/factory.js.map +1 -1
- package/dist/esm/relational/core/models/index.d.ts +1 -0
- package/dist/esm/relational/core/models/index.js +1 -0
- package/dist/esm/relational/core/models/index.js.map +1 -1
- package/dist/esm/relational/core/models/relations.d.ts +1 -0
- package/dist/esm/relational/core/models/relations.js +1 -0
- package/dist/esm/relational/core/models/relations.js.map +1 -1
- package/dist/esm/relational/core/models/unique-keys.d.ts +42 -0
- package/dist/esm/relational/core/models/unique-keys.js +41 -0
- package/dist/esm/relational/core/models/unique-keys.js.map +1 -0
- package/dist/esm/relational/core/repositories/common/executor.d.ts +20 -1
- package/dist/esm/relational/core/repositories/common/executor.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/scope-filter.d.ts +17 -0
- package/dist/esm/relational/core/repositories/common/scope-filter.js +46 -1
- package/dist/esm/relational/core/repositories/common/scope-filter.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/scope-write-guard.d.ts +7 -0
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js +18 -8
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/types.d.ts +30 -0
- package/dist/esm/relational/core/repositories/common/types.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/upsert-plan.d.ts +37 -0
- package/dist/esm/relational/core/repositories/common/upsert-plan.js +98 -0
- package/dist/esm/relational/core/repositories/common/upsert-plan.js.map +1 -0
- package/dist/esm/relational/core/repositories/core/base.d.ts +25 -45
- package/dist/esm/relational/core/repositories/core/base.js +100 -33
- package/dist/esm/relational/core/repositories/core/base.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/persistable.d.ts +167 -23
- package/dist/esm/relational/core/repositories/core/persistable.js +129 -17
- package/dist/esm/relational/core/repositories/core/persistable.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/readable.d.ts +95 -9
- package/dist/esm/relational/core/repositories/core/readable.js +167 -12
- package/dist/esm/relational/core/repositories/core/readable.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/soft-deletable.d.ts +40 -29
- package/dist/esm/relational/core/repositories/core/soft-deletable.js +77 -23
- package/dist/esm/relational/core/repositories/core/soft-deletable.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/filter.d.ts +58 -5
- package/dist/esm/relational/core/repositories/dialect/filter.js +225 -53
- package/dist/esm/relational/core/repositories/dialect/filter.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.d.ts +19 -0
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.js +79 -0
- package/dist/esm/relational/core/repositories/dialect/internal/date-operand.js.map +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.d.ts +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.js +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/index.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/internal/json-utils.d.ts +1 -0
- package/dist/esm/relational/core/repositories/dialect/internal/json-utils.js +5 -4
- package/dist/esm/relational/core/repositories/dialect/internal/json-utils.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/relations/create.d.ts +1 -0
- package/dist/esm/relational/core/repositories/dialect/relations/create.js +1 -0
- package/dist/esm/relational/core/repositories/dialect/relations/create.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/update.js +4 -2
- package/dist/esm/relational/core/repositories/dialect/update.js.map +1 -1
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.d.ts +2 -0
- package/dist/esm/relational/core/repositories/sqls/recursive-tree.js.map +1 -1
- package/dist/esm/relational/postgres/datasources/base.d.ts +21 -0
- package/dist/esm/relational/postgres/datasources/base.js +21 -0
- package/dist/esm/relational/postgres/datasources/base.js.map +1 -1
- package/dist/esm/relational/postgres/datasources/common/types.d.ts +3 -0
- package/dist/esm/relational/postgres/datasources/common/types.js +1 -0
- package/dist/esm/relational/postgres/datasources/common/types.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/node-postgres.d.ts +3 -0
- package/dist/esm/relational/postgres/drivers/node-postgres.js +4 -0
- package/dist/esm/relational/postgres/drivers/node-postgres.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/pglite.d.ts +3 -0
- package/dist/esm/relational/postgres/drivers/pglite.js +3 -0
- package/dist/esm/relational/postgres/drivers/pglite.js.map +1 -1
- package/dist/esm/relational/postgres/drivers/postgres-js.d.ts +3 -0
- package/dist/esm/relational/postgres/drivers/postgres-js.js +4 -0
- package/dist/esm/relational/postgres/drivers/postgres-js.js.map +1 -1
- package/dist/esm/relational/postgres/models/common/types/enrichers.d.ts +26 -1
- package/dist/esm/relational/postgres/models/common/types/enrichers.js.map +1 -1
- package/dist/esm/relational/postgres/models/common/types/table.d.ts +8 -0
- package/dist/esm/relational/postgres/models/common/types/table.js.map +1 -1
- package/dist/esm/relational/postgres/models/enrichers/data-type.enricher.d.ts +1 -0
- package/dist/esm/relational/postgres/models/enrichers/data-type.enricher.js +1 -0
- package/dist/esm/relational/postgres/models/enrichers/data-type.enricher.js.map +1 -1
- package/dist/esm/relational/postgres/models/enrichers/id.enricher.d.ts +16 -0
- package/dist/esm/relational/postgres/models/enrichers/id.enricher.js +15 -0
- package/dist/esm/relational/postgres/models/enrichers/id.enricher.js.map +1 -1
- package/dist/esm/relational/postgres/models/enrichers/principal.enricher.d.ts +1 -0
- package/dist/esm/relational/postgres/models/enrichers/principal.enricher.js +1 -0
- package/dist/esm/relational/postgres/models/enrichers/principal.enricher.js.map +1 -1
- package/dist/esm/relational/postgres/models/enrichers/tz.enricher.d.ts +18 -0
- package/dist/esm/relational/postgres/models/enrichers/tz.enricher.js +17 -0
- package/dist/esm/relational/postgres/models/enrichers/tz.enricher.js.map +1 -1
- package/dist/esm/relational/postgres/models/enrichers/user-audit.enricher.d.ts +2 -0
- package/dist/esm/relational/postgres/models/enrichers/user-audit.enricher.js +1 -0
- package/dist/esm/relational/postgres/models/enrichers/user-audit.enricher.js.map +1 -1
- package/dist/esm/relational/postgres/repositories/core/index.d.ts +1 -0
- package/dist/esm/relational/postgres/repositories/core/index.js +1 -0
- package/dist/esm/relational/postgres/repositories/core/index.js.map +1 -1
- package/dist/esm/relational/postgres/repositories/core/pglite.d.ts +18 -0
- package/dist/esm/relational/postgres/repositories/core/pglite.js +4 -0
- package/dist/esm/relational/postgres/repositories/core/pglite.js.map +1 -0
- package/dist/esm/relational/postgres/repositories/executor.d.ts +2 -0
- package/dist/esm/relational/postgres/repositories/executor.js +23 -2
- package/dist/esm/relational/postgres/repositories/executor.js.map +1 -1
- package/dist/esm/relational/postgres/supabase/pooler.d.ts +3 -0
- package/dist/esm/relational/postgres/supabase/pooler.js +1 -0
- package/dist/esm/relational/postgres/supabase/pooler.js.map +1 -1
- package/dist/esm/relational/postgres/supabase/rls.d.ts +1 -0
- package/dist/esm/relational/postgres/supabase/rls.js +1 -0
- package/dist/esm/relational/postgres/supabase/rls.js.map +1 -1
- package/dist/esm/relational/sqlite/datasources/common/types.d.ts +1 -0
- package/dist/esm/relational/sqlite/datasources/common/types.js.map +1 -1
- package/dist/esm/relational/sqlite/drivers/libsql.d.ts +2 -0
- package/dist/esm/relational/sqlite/drivers/libsql.js +3 -0
- package/dist/esm/relational/sqlite/drivers/libsql.js.map +1 -1
- package/dist/esm/relational/sqlite/models/common/types/enrichers.d.ts +23 -2
- package/dist/esm/relational/sqlite/models/common/types/enrichers.js.map +1 -1
- package/dist/esm/relational/sqlite/models/common/types/table.d.ts +8 -0
- package/dist/esm/relational/sqlite/models/common/types/table.js.map +1 -1
- package/dist/esm/relational/sqlite/models/enrichers/data-type.enricher.d.ts +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/data-type.enricher.js +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/data-type.enricher.js.map +1 -1
- package/dist/esm/relational/sqlite/models/enrichers/id.enricher.d.ts +2 -0
- package/dist/esm/relational/sqlite/models/enrichers/id.enricher.js +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/id.enricher.js.map +1 -1
- package/dist/esm/relational/sqlite/models/enrichers/principal.enricher.d.ts +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/principal.enricher.js +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/principal.enricher.js.map +1 -1
- package/dist/esm/relational/sqlite/models/enrichers/tz.enricher.d.ts +2 -0
- package/dist/esm/relational/sqlite/models/enrichers/tz.enricher.js +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/tz.enricher.js.map +1 -1
- package/dist/esm/relational/sqlite/models/enrichers/user-audit.enricher.d.ts +2 -0
- package/dist/esm/relational/sqlite/models/enrichers/user-audit.enricher.js +1 -0
- package/dist/esm/relational/sqlite/models/enrichers/user-audit.enricher.js.map +1 -1
- package/dist/esm/relational/sqlite/repositories/executor.d.ts +2 -0
- package/dist/esm/relational/sqlite/repositories/executor.js +22 -2
- package/dist/esm/relational/sqlite/repositories/executor.js.map +1 -1
- package/dist/esm/search/core/connector.d.ts +7 -0
- package/dist/esm/search/core/connector.js +1 -0
- package/dist/esm/search/core/connector.js.map +1 -1
- package/dist/esm/search/core/controllers/abstract.d.ts +8 -1
- package/dist/esm/search/core/controllers/abstract.js +14 -1
- package/dist/esm/search/core/controllers/abstract.js.map +1 -1
- package/dist/esm/search/core/controllers/engine-params.d.ts +37 -0
- package/dist/esm/search/core/controllers/engine-params.js +124 -0
- package/dist/esm/search/core/controllers/engine-params.js.map +1 -0
- package/dist/esm/search/core/controllers/factory.d.ts +52 -37
- package/dist/esm/search/core/controllers/factory.js +39 -26
- package/dist/esm/search/core/controllers/factory.js.map +1 -1
- package/dist/esm/search/core/controllers/index.d.ts +2 -0
- package/dist/esm/search/core/controllers/index.js +2 -0
- package/dist/esm/search/core/controllers/index.js.map +1 -1
- package/dist/esm/search/core/controllers/raw-access.d.ts +25 -0
- package/dist/esm/search/core/controllers/raw-access.js +48 -0
- package/dist/esm/search/core/controllers/raw-access.js.map +1 -0
- package/dist/esm/search/core/controllers/scope.d.ts +3 -2
- package/dist/esm/search/core/controllers/scope.js +3 -8
- package/dist/esm/search/core/controllers/scope.js.map +1 -1
- package/dist/esm/search/core/datasources/base.d.ts +1 -1
- package/dist/esm/search/core/datasources/base.js +5 -5
- package/dist/esm/search/core/datasources/base.js.map +1 -1
- package/dist/esm/search/core/datasources/common/types.d.ts +6 -1
- package/dist/esm/search/core/datasources/common/types.js.map +1 -1
- package/dist/esm/search/core/internal/search-connector-internal.js +1 -2
- package/dist/esm/search/core/internal/search-connector-internal.js.map +1 -1
- package/dist/esm/search/core/models/common/constants.d.ts +2 -0
- package/dist/esm/search/core/models/common/constants.js.map +1 -1
- package/dist/esm/search/core/models/common/types/collection.d.ts +2 -0
- package/dist/esm/search/core/models/common/types/collection.js.map +1 -1
- package/dist/esm/search/core/models/common/types/embedding.d.ts +1 -0
- package/dist/esm/search/core/models/common/types/embedding.js.map +1 -1
- package/dist/esm/search/core/models/common/types/field.d.ts +1 -0
- package/dist/esm/search/core/models/common/types/field.js.map +1 -1
- package/dist/esm/search/core/models/define-search-collection.d.ts +2 -0
- package/dist/esm/search/core/models/define-search-collection.js +2 -0
- package/dist/esm/search/core/models/define-search-collection.js.map +1 -1
- package/dist/esm/search/core/repositories/common/constants.d.ts +8 -3
- package/dist/esm/search/core/repositories/common/constants.js +1 -0
- package/dist/esm/search/core/repositories/common/constants.js.map +1 -1
- package/dist/esm/search/core/repositories/common/dialect-helpers.d.ts +8 -2
- package/dist/esm/search/core/repositories/common/dialect-helpers.js +8 -3
- package/dist/esm/search/core/repositories/common/dialect-helpers.js.map +1 -1
- package/dist/esm/search/core/repositories/common/query-params.d.ts +1 -0
- package/dist/esm/search/core/repositories/common/query-params.js +1 -0
- package/dist/esm/search/core/repositories/common/query-params.js.map +1 -1
- package/dist/esm/search/core/repositories/common/types.d.ts +13 -3
- package/dist/esm/search/core/repositories/common/types.js.map +1 -1
- package/dist/esm/search/core/repositories/core/base.d.ts +16 -2
- package/dist/esm/search/core/repositories/core/base.js +67 -1
- package/dist/esm/search/core/repositories/core/base.js.map +1 -1
- package/dist/esm/search/core/repositories/core/persistable.d.ts +8 -8
- package/dist/esm/search/core/repositories/core/persistable.js +12 -12
- package/dist/esm/search/core/repositories/core/persistable.js.map +1 -1
- package/dist/esm/search/core/repositories/core/readable.d.ts +5 -9
- package/dist/esm/search/core/repositories/core/readable.js +34 -14
- package/dist/esm/search/core/repositories/core/readable.js.map +1 -1
- package/dist/esm/search/meilisearch/common/types.d.ts +15 -2
- package/dist/esm/search/meilisearch/common/types.js.map +1 -1
- package/dist/esm/search/meilisearch/compiler.d.ts +1 -0
- package/dist/esm/search/meilisearch/compiler.js +1 -0
- package/dist/esm/search/meilisearch/compiler.js.map +1 -1
- package/dist/esm/search/meilisearch/connector.js +1 -2
- package/dist/esm/search/meilisearch/connector.js.map +1 -1
- package/dist/esm/search/meilisearch/internal/connector-internal.js +1 -1
- package/dist/esm/search/meilisearch/internal/connector-internal.js.map +1 -1
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.d.ts +14 -0
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js +60 -11
- package/dist/esm/search/meilisearch/repositories/dialect/query-dialect.js.map +1 -1
- package/dist/esm/search/typesense/common/constants.d.ts +4 -0
- package/dist/esm/search/typesense/common/constants.js +2 -0
- package/dist/esm/search/typesense/common/constants.js.map +1 -1
- package/dist/esm/search/typesense/common/types/client.d.ts +2 -0
- package/dist/esm/search/typesense/common/types/client.js.map +1 -1
- package/dist/esm/search/typesense/common/types/options.d.ts +8 -1
- package/dist/esm/search/typesense/common/types/options.js.map +1 -1
- package/dist/esm/search/typesense/common/types/schema.d.ts +4 -0
- package/dist/esm/search/typesense/common/types/schema.js.map +1 -1
- package/dist/esm/search/typesense/common/types/search.d.ts +6 -0
- package/dist/esm/search/typesense/common/types/search.js.map +1 -1
- package/dist/esm/search/typesense/compiler.d.ts +1 -0
- package/dist/esm/search/typesense/compiler.js +1 -0
- package/dist/esm/search/typesense/compiler.js.map +1 -1
- package/dist/esm/search/typesense/connector.d.ts +3 -1
- package/dist/esm/search/typesense/connector.js +1 -2
- package/dist/esm/search/typesense/connector.js.map +1 -1
- package/dist/esm/search/typesense/internal/guards.js +1 -1
- package/dist/esm/search/typesense/internal/guards.js.map +1 -1
- package/dist/esm/search/typesense/internal/mappers.js +1 -1
- package/dist/esm/search/typesense/internal/mappers.js.map +1 -1
- package/dist/esm/search/typesense/repositories/common/types.d.ts +14 -0
- package/dist/esm/search/typesense/repositories/common/types.js.map +1 -1
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.d.ts +5 -0
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.js +14 -4
- package/dist/esm/search/typesense/repositories/dialect/query-dialect.js.map +1 -1
- package/dist/esm/testing/repository-double.d.ts +3 -0
- package/dist/esm/testing/repository-double.js +10 -1
- package/dist/esm/testing/repository-double.js.map +1 -1
- package/dist/esm/testing/transaction-double.d.ts +16 -1
- package/dist/esm/testing/transaction-double.js +18 -1
- package/dist/esm/testing/transaction-double.js.map +1 -1
- package/package.json +6 -6
- package/dist/esm/common/internal/record.d.ts +0 -5
- package/dist/esm/common/internal/record.js +0 -7
- package/dist/esm/common/internal/record.js.map +0 -1
- package/dist/esm/relational/core/models/common/constants.d.ts +0 -13
- package/dist/esm/relational/core/models/common/constants.js +0 -20
- package/dist/esm/relational/core/models/common/constants.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ The datasources, drivers, entity bases and repositories IGNIS uses to reach a ba
|
|
|
4
4
|
through Drizzle (Postgres, PGlite, SQLite), search engines (Typesense, Meilisearch), and another
|
|
5
5
|
IGNIS server over HTTP.
|
|
6
6
|
|
|
7
|
-
Server applications get
|
|
8
|
-
directly when you use the connectors without the server, for example in a browser Worker.
|
|
7
|
+
Server applications get the Postgres entry through `@venizia/ignis`; every other entry is imported from this
|
|
8
|
+
package. Install it directly when you use the connectors without the server, for example in a browser Worker.
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
@@ -123,6 +123,8 @@ styles can live in one application.
|
|
|
123
123
|
| `/typesense/controllers` | The same search controllers as `/search/controllers` | `hono`, `@hono/zod-openapi` |
|
|
124
124
|
| `/meilisearch` | `MeilisearchDataSource`, `MeilisearchConnector`, `MeilisearchQueryDialect` | `meilisearch` |
|
|
125
125
|
| `/http` | `HttpDataSource` and `HttpRepository` - read another IGNIS server's REST routes with the same filter vocabulary | none |
|
|
126
|
+
| `/raw-sql` | `BaseRawSqlDataSource`, `BaseRawSqlRepository`, `RawSqlEntity` - an engine that only runs raw SQL and returns rows, with no dialect and no transactions; you supply the connector and the driver | none to load (`drizzle-orm` for the `SQLWrapper` type) |
|
|
127
|
+
| `/testing` | Test-only: `RepositoryDouble`, `TransactionDouble`, `PostgresTransactionDouble`, `SqliteTransactionDouble`; never imported from a production barrel | none |
|
|
126
128
|
|
|
127
129
|
The root entry imports no driver and no engine client. A driver loads only when you import its
|
|
128
130
|
entry and name its class in `@datasource({ driver })`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
1
|
+
import type { IDataSourceOpening, TAnyDataSourceSchema } from '@venizia/ignis-kernel';
|
|
2
2
|
import { AbstractDataSource } from '@venizia/ignis-kernel/repository';
|
|
3
3
|
import type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';
|
|
4
4
|
import type { IConnectorDriver } from './driver.js';
|
|
@@ -14,15 +14,15 @@ import type { IConnectorDriver } from './driver.js';
|
|
|
14
14
|
* neutral base - do not move it down into a family.
|
|
15
15
|
*/
|
|
16
16
|
export declare abstract class AbstractDriverDataSource<Settings extends object = {}, Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema, ConfigurableOptions extends object = {}, Client = unknown, TConnector = unknown, TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {
|
|
17
|
-
connector
|
|
17
|
+
connector?: TConnector;
|
|
18
18
|
protected client?: Client;
|
|
19
19
|
protected driver?: TDriver;
|
|
20
20
|
private closePromise?;
|
|
21
21
|
/**
|
|
22
22
|
* Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client
|
|
23
|
-
* `configure()` assigned, then the connector from it.
|
|
23
|
+
* `configure()` assigned, then the connector from it. Returns the connector.
|
|
24
24
|
*/
|
|
25
|
-
protected wireDriverFromMetadata():
|
|
25
|
+
protected wireDriverFromMetadata(): TConnector;
|
|
26
26
|
/**
|
|
27
27
|
* Rejects a driver-name string from untyped JS
|
|
28
28
|
* callers: a string carries no module into the bundle.
|
|
@@ -31,12 +31,16 @@ export declare abstract class AbstractDriverDataSource<Settings extends object =
|
|
|
31
31
|
protected resolveDriver(): TDriver;
|
|
32
32
|
/**
|
|
33
33
|
* Assigns `this.driver` AND builds `this.connector` in one step - a
|
|
34
|
-
* driver without its connector is silently bypassed on pooled queries.
|
|
34
|
+
* driver without its connector is silently bypassed on pooled queries. Returns the connector.
|
|
35
35
|
*/
|
|
36
36
|
protected useDriver(opts: {
|
|
37
37
|
driver: TDriver;
|
|
38
38
|
schema?: Schema;
|
|
39
|
-
}):
|
|
39
|
+
}): TConnector;
|
|
40
|
+
/** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */
|
|
41
|
+
private assertOpenForSyncUse;
|
|
42
|
+
/** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */
|
|
43
|
+
protected createOpening(): IDataSourceOpening<TConnector, Client>;
|
|
40
44
|
/** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */
|
|
41
45
|
getConnector(): TConnector;
|
|
42
46
|
/**
|
|
@@ -44,12 +48,15 @@ export declare abstract class AbstractDriverDataSource<Settings extends object =
|
|
|
44
48
|
* than handing back an `undefined` typed as `Client`.
|
|
45
49
|
*/
|
|
46
50
|
getClient(): Client;
|
|
51
|
+
private readClient;
|
|
47
52
|
/**
|
|
48
53
|
* Ends the connection `configure()` opened. Runs once: every later call returns the first call's
|
|
49
54
|
* promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the
|
|
50
55
|
* engine's whole teardown - PGlite also clears the exit status it plants on the host process.
|
|
51
56
|
*/
|
|
52
57
|
close(): Promise<void>;
|
|
58
|
+
/** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */
|
|
59
|
+
protected discardPartialOpen(): Promise<void>;
|
|
53
60
|
private endConnection;
|
|
54
61
|
/**
|
|
55
62
|
* Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without
|
|
@@ -15,15 +15,16 @@ import { getError } from '@venizia/ignis-helpers/core';
|
|
|
15
15
|
export class AbstractDriverDataSource extends AbstractDataSource {
|
|
16
16
|
/**
|
|
17
17
|
* Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client
|
|
18
|
-
* `configure()` assigned, then the connector from it.
|
|
18
|
+
* `configure()` assigned, then the connector from it. Returns the connector.
|
|
19
19
|
*/
|
|
20
20
|
wireDriverFromMetadata() {
|
|
21
21
|
if (this.connector) {
|
|
22
|
-
return;
|
|
22
|
+
return this.connector;
|
|
23
23
|
}
|
|
24
24
|
if (this.driver) {
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
const connector = this.driver.createConnector({ schema: this.getSchema() });
|
|
26
|
+
this.connector = connector;
|
|
27
|
+
return connector;
|
|
27
28
|
}
|
|
28
29
|
if (!this.client) {
|
|
29
30
|
throw getError({
|
|
@@ -31,7 +32,7 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
31
32
|
});
|
|
32
33
|
}
|
|
33
34
|
const DriverClass = this.resolveDriverClass();
|
|
34
|
-
this.useDriver({ driver: new DriverClass({ client: this.client }) });
|
|
35
|
+
return this.useDriver({ driver: new DriverClass({ client: this.client }) });
|
|
35
36
|
}
|
|
36
37
|
/**
|
|
37
38
|
* Rejects a driver-name string from untyped JS
|
|
@@ -55,22 +56,57 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
55
56
|
}
|
|
56
57
|
/**
|
|
57
58
|
* Assigns `this.driver` AND builds `this.connector` in one step - a
|
|
58
|
-
* driver without its connector is silently bypassed on pooled queries.
|
|
59
|
+
* driver without its connector is silently bypassed on pooled queries. Returns the connector.
|
|
59
60
|
*/
|
|
60
61
|
useDriver(opts) {
|
|
61
62
|
this.driver = opts.driver;
|
|
62
|
-
|
|
63
|
+
const connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });
|
|
64
|
+
this.connector = connector;
|
|
65
|
+
return connector;
|
|
66
|
+
}
|
|
67
|
+
/** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */
|
|
68
|
+
assertOpenForSyncUse(opts) {
|
|
69
|
+
if (!this.isOpenDeferred()) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (this.isClosed()) {
|
|
73
|
+
throw getError({
|
|
74
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource is closed | It opens on first use only before close()`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (this.isOpening()) {
|
|
78
|
+
throw getError({
|
|
79
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource is still opening | Inside configure() use the opening argument (opening.${opts.member}()); outside it, await ensureOpen()`,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (!this.isOpen()) {
|
|
83
|
+
throw getError({
|
|
84
|
+
message: `[${this.constructor.name}][${opts.member}] The datasource opens on first use and is not open | Await ensureOpen() first; repository calls do it for you`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */
|
|
89
|
+
createOpening() {
|
|
90
|
+
return {
|
|
91
|
+
...super.createOpening(),
|
|
92
|
+
getConnector: () => this.wireDriverFromMetadata(),
|
|
93
|
+
getClient: () => this.readClient(),
|
|
94
|
+
};
|
|
63
95
|
}
|
|
64
96
|
/** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */
|
|
65
97
|
getConnector() {
|
|
66
|
-
this.
|
|
67
|
-
return this.
|
|
98
|
+
this.assertOpenForSyncUse({ member: this.getConnector.name });
|
|
99
|
+
return this.wireDriverFromMetadata();
|
|
68
100
|
}
|
|
69
101
|
/**
|
|
70
102
|
* Raw driver client (`pg.Pool` / `Sql`). Throws rather
|
|
71
103
|
* than handing back an `undefined` typed as `Client`.
|
|
72
104
|
*/
|
|
73
105
|
getClient() {
|
|
106
|
+
this.assertOpenForSyncUse({ member: this.getClient.name });
|
|
107
|
+
return this.readClient();
|
|
108
|
+
}
|
|
109
|
+
readClient() {
|
|
74
110
|
if (this.driver) {
|
|
75
111
|
return this.driver.getClient();
|
|
76
112
|
}
|
|
@@ -87,9 +123,28 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
87
123
|
* engine's whole teardown - PGlite also clears the exit status it plants on the host process.
|
|
88
124
|
*/
|
|
89
125
|
close() {
|
|
90
|
-
|
|
126
|
+
// A stop that arrives while the first use is still opening waits for that open, then closes what it built.
|
|
127
|
+
this.closePromise ??= this.settleOpening().then(() => this.endConnection());
|
|
91
128
|
return this.closePromise;
|
|
92
129
|
}
|
|
130
|
+
/** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */
|
|
131
|
+
async discardPartialOpen() {
|
|
132
|
+
const { client, driver } = this;
|
|
133
|
+
this.client = undefined;
|
|
134
|
+
this.driver = undefined;
|
|
135
|
+
this.connector = undefined;
|
|
136
|
+
// A close() that is waiting for this open owns the slot: clearing it would let a second close end the connection twice.
|
|
137
|
+
if (!this.isClosed()) {
|
|
138
|
+
this.closePromise = undefined;
|
|
139
|
+
}
|
|
140
|
+
if (driver && typeof driver.end === 'function') {
|
|
141
|
+
await driver.end();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (client !== undefined) {
|
|
145
|
+
await this.drainClient({ client });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
93
148
|
async endConnection() {
|
|
94
149
|
if (!this.driver && this.client === undefined) {
|
|
95
150
|
return;
|
|
@@ -120,6 +175,12 @@ export class AbstractDriverDataSource extends AbstractDataSource {
|
|
|
120
175
|
*/
|
|
121
176
|
async onSecretRotated(opts) {
|
|
122
177
|
const logger = this.logger.for(this.onSecretRotated.name);
|
|
178
|
+
// Nothing is open yet, so there is no pool to swap: the rotated credentials wait in the settings for the first use.
|
|
179
|
+
if (this.isOpenDeferred() && !this.isOpen()) {
|
|
180
|
+
Object.assign(this.settings, this.mapSecretToSettings({ secret: opts.secret }));
|
|
181
|
+
logger.info('Datasource not open yet; credentials kept for its first use | key: %s', opts.key);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
123
184
|
const oldClient = this.getClient();
|
|
124
185
|
// Snapshot so a failed rebuild restores the datasource verbatim;
|
|
125
186
|
// `settings` is copied because rotation mutates it in place.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"driver-data-source.js","sourceRoot":"","sources":["../../../src/common/driver-data-source.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;;;;;;;;G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EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3C,MAAM,MAAM,GAAc,EAAE,CAAC;QAE7B,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACzB,CAAC;QAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import type { TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IConnectorDriver } from './driver';\n\n/**\n * A datasource that holds one client and a connector built over it through a driver: the lifecycle\n * every connector family that talks to an external engine shares - wiring the driver named by\n * `@datasource({ driver })`, closing once, soft-evicting the client after a secret rotation, draining\n * a client by whichever verb its engine spells it with. No SQL members: the relational family adds\n * its dialect, executor and transactions in `AbstractRelationalDataSource`, a raw-SQL engine adds\n * nothing (`BaseRawSqlDataSource`). Transactions stay NotSupported, as in `AbstractDataSource`.\n *\n * `mapSecretToSettings` is a driver-config convention, not Postgres SQL, so it belongs on this\n * neutral base - do not move it down into a family.\n */\nexport abstract class AbstractDriverDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector: TConnector;\n\n protected client?: Client;\n protected driver?: TDriver;\n\n private closePromise?: Promise<void>;\n\n /**\n * Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client\n * `configure()` assigned, then the connector from it.\n */\n protected wireDriverFromMetadata(): void {\n if (this.connector) {\n return;\n }\n\n if (this.driver) {\n this.connector = this.driver.createConnector({ schema: this.getSchema() });\n\n return;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][wireDriverFromMetadata] No driver and no client | Assign this.client in configure(), or wire a custom driver with useDriver()`,\n });\n }\n\n const DriverClass = this.resolveDriverClass();\n this.useDriver({ driver: new DriverClass({ client: this.client }) });\n }\n\n /**\n * Rejects a driver-name string from untyped JS\n * callers: a string carries no module into the bundle.\n */\n protected resolveDriverClass(): TClass<TDriver> {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n const driver = metadata?.driver;\n\n if (typeof driver !== 'function') {\n throw getError({\n message: `[${this.constructor.name}][resolveDriverClass] @datasource({ driver }) must name a driver CLASS | Got: ${String(driver)} | Use \\`@datasource({ driver: NodePostgresDriver })\\` with \\`import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres'\\`, or wire a custom driver with useDriver()`,\n });\n }\n\n return driver as TClass<TDriver>;\n }\n\n protected resolveDriver(): TDriver {\n this.wireDriverFromMetadata();\n\n return this.driver as TDriver;\n }\n\n /**\n * Assigns `this.driver` AND builds `this.connector` in one step - a\n * driver without its connector is silently bypassed on pooled queries.\n */\n protected useDriver(opts: { driver: TDriver; schema?: Schema }): void {\n this.driver = opts.driver;\n this.connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });\n }\n\n /** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */\n getConnector(): TConnector {\n this.wireDriverFromMetadata();\n\n return this.connector;\n }\n\n /**\n * Raw driver client (`pg.Pool` / `Sql`). Throws rather\n * than handing back an `undefined` typed as `Client`.\n */\n getClient(): Client {\n if (this.driver) {\n return this.driver.getClient() as Client;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][getClient] No driver and no client | Assign this.driver in configure()`,\n });\n }\n\n return this.client;\n }\n\n /**\n * Ends the connection `configure()` opened. Runs once: every later call returns the first call's\n * promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the\n * engine's whole teardown - PGlite also clears the exit status it plants on the host process.\n */\n override close(): Promise<void> {\n this.closePromise ??= this.endConnection();\n\n return this.closePromise;\n }\n\n private async endConnection(): Promise<void> {\n if (!this.driver && this.client === undefined) {\n return;\n }\n\n let driver: TDriver;\n\n try {\n driver = this.resolveDriver();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .warn('No driver to end the connection with | draining the client | error: %s', error);\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n // A hand-made driver cast past `IConnectorDriver` can lack the `end()` its type promises.\n if (typeof driver.end !== 'function') {\n this.logger.for(this.close.name).warn('The driver has no end() | draining the client');\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n await driver.end();\n }\n\n /**\n * Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without\n * touching live fields, swaps atomically, then drains the old pool. On failure live state is\n * restored, any half-built pool drained, and the error rethrown.\n */\n async onSecretRotated(opts: { key: string; secret: Record<string, string> }): Promise<void> {\n const logger = this.logger.for(this.onSecretRotated.name);\n const oldClient = this.getClient() as AnyType;\n\n // Snapshot so a failed rebuild restores the datasource verbatim;\n // `settings` is copied because rotation mutates it in place.\n const savedClient = this.client;\n const savedSettings = { ...(this.settings as AnyObject) };\n\n // Rotation only takes effect through this.settings + configure(); a configure() that\n // hard-codes its connection string or reads the environment directly rebuilds with stale credentials.\n Object.assign(this.settings as AnyObject, this.mapSecretToSettings({ secret: opts.secret }));\n\n // configure() overwrites this.client, so the new pool is captured\n // into a local and the old client restored at once - live fields\n // are never nulled and the old pool keeps serving until the swap.\n let newClient: Client;\n\n try {\n await this.configure();\n newClient = this.client as Client;\n } catch (error) {\n const halfBuilt = this.client as AnyType;\n this.client = savedClient;\n this.restoreSettings({ saved: savedSettings });\n\n if (halfBuilt && halfBuilt !== savedClient) {\n await this.drainClient({ client: halfBuilt });\n }\n\n logger.error('Secret rotation failed in configure(); kept old pool | key: %s', opts.key);\n throw error;\n }\n\n this.client = savedClient;\n\n // Wired into locals: live state must stay on the old pool until the swap below.\n let newDriver: TDriver;\n let newConnector: TConnector;\n\n try {\n const DriverClass = this.resolveDriverClass();\n newDriver = new DriverClass({ client: newClient as AnyType });\n newConnector = newDriver.createConnector({ schema: this.getSchema() });\n } catch (error) {\n this.restoreSettings({ saved: savedSettings });\n await this.drainClient({ client: newClient });\n\n logger.error('Secret rotation failed while wiring driver; kept old pool | key: %s', opts.key);\n throw error;\n }\n\n // Commit the live fields in one synchronous step so there is no null window,\n // then soft-evict the old pool so its in-flight transactions can finish.\n this.client = newClient as AnyType;\n this.driver = newDriver;\n this.connector = newConnector as AnyType;\n\n const isDrained = await this.drainClient({ client: oldClient });\n\n if (isDrained) {\n logger.info('Old pool drained after secret rotation | key: %s', opts.key);\n }\n }\n\n /** Puts `settings` back to the snapshot: a key the failed rotation added (the rotated `password`) is removed, not left behind. */\n private restoreSettings(opts: { saved: AnyObject }): void {\n const settings = this.settings as AnyObject;\n\n for (const key of Object.keys(settings)) {\n if (!(key in opts.saved)) {\n delete settings[key];\n }\n }\n\n Object.assign(settings, opts.saved);\n }\n\n /**\n * Shuts a client down by whichever verb its engine spells it with -\n * `pg.Pool` and postgres.js have `end()`, PGlite and libsql only `close()`.\n * Probed rather than type-tested: this tier must not name an engine, and a\n * client left undrained keeps a WASM instance or file handle alive forever.\n */\n protected async drainClient(opts: { client: unknown }): Promise<boolean> {\n const client = opts.client as AnyType;\n\n const drain = typeof client?.end === 'function' ? client.end : client?.close;\n\n if (typeof drain !== 'function') {\n this.logger\n .for(this.drainClient.name)\n .warn('Client exposes neither end() nor close(); nothing to drain');\n\n return false;\n }\n\n await drain.call(client);\n\n return true;\n }\n\n /** Vault's database engine returns `{ username, password }`; pg expects `{ user, password }`. */\n protected mapSecretToSettings(opts: { secret: Record<string, string> }): AnyObject {\n const { username, password } = opts.secret;\n const mapped: AnyObject = {};\n\n if (username !== undefined) {\n mapped.user = username;\n }\n\n if (password !== undefined) {\n mapped.password = password;\n }\n\n return mapped;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"driver-data-source.js","sourceRoot":"","sources":["../../../src/common/driver-data-source.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD;;;;;;;;;;GAUG;AACH,MAAM,OAAgB,wBAOpB,SAAQ,kBAAyD;IAQjE;;;OAGG;IACO,sBAAsB;QAC9B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,IAAI,CAAC,SAAS,CAAC;QACxB,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;YAC5E,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;YAE3B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,iIAAiI;aACpK,CAAC,CAAC;QACL,CAAC;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAE9C,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED;;;OAGG;IACO,kBAAkB;QAC1B,MAAM,QAAQ,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC,qBAAqB,CAAC;YACpE,MAAM,EA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AI,CAAC;iBAC1B,IAAI,CAAC,4DAA4D,CAAC,CAAC;YAEtE,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,iGAAiG;IACvF,mBAAmB,CAAC,IAAwC;QACpE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3C,MAAM,MAAM,GAAc,EAAE,CAAC;QAE7B,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACzB,CAAC;QAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import type { IDataSourceOpening, TAnyDataSourceSchema } from '@venizia/ignis-kernel';\nimport { AbstractDataSource } from '@venizia/ignis-kernel/repository';\nimport { MetadataRegistry } from '@venizia/ignis-kernel/metadata';\nimport type { AnyObject, AnyType, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IConnectorDriver } from './driver';\n\n/**\n * A datasource that holds one client and a connector built over it through a driver: the lifecycle\n * every connector family that talks to an external engine shares - wiring the driver named by\n * `@datasource({ driver })`, closing once, soft-evicting the client after a secret rotation, draining\n * a client by whichever verb its engine spells it with. No SQL members: the relational family adds\n * its dialect, executor and transactions in `AbstractRelationalDataSource`, a raw-SQL engine adds\n * nothing (`BaseRawSqlDataSource`). Transactions stay NotSupported, as in `AbstractDataSource`.\n *\n * `mapSecretToSettings` is a driver-config convention, not Postgres SQL, so it belongs on this\n * neutral base - do not move it down into a family.\n */\nexport abstract class AbstractDriverDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n Client = unknown,\n TConnector = unknown,\n TDriver extends IConnectorDriver<TConnector, AnyType> = IConnectorDriver<TConnector, Client>,\n> extends AbstractDataSource<Settings, Schema, ConfigurableOptions> {\n connector?: TConnector;\n\n protected client?: Client;\n protected driver?: TDriver;\n\n private closePromise?: Promise<void>;\n\n /**\n * Lazy and idempotent: builds the driver named by `@datasource({ driver })` over the client\n * `configure()` assigned, then the connector from it. Returns the connector.\n */\n protected wireDriverFromMetadata(): TConnector {\n if (this.connector) {\n return this.connector;\n }\n\n if (this.driver) {\n const connector = this.driver.createConnector({ schema: this.getSchema() });\n this.connector = connector;\n\n return connector;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][wireDriverFromMetadata] No driver and no client | Assign this.client in configure(), or wire a custom driver with useDriver()`,\n });\n }\n\n const DriverClass = this.resolveDriverClass();\n\n return this.useDriver({ driver: new DriverClass({ client: this.client }) });\n }\n\n /**\n * Rejects a driver-name string from untyped JS\n * callers: a string carries no module into the bundle.\n */\n protected resolveDriverClass(): TClass<TDriver> {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n const driver = metadata?.driver;\n\n if (typeof driver !== 'function') {\n throw getError({\n message: `[${this.constructor.name}][resolveDriverClass] @datasource({ driver }) must name a driver CLASS | Got: ${String(driver)} | Use \\`@datasource({ driver: NodePostgresDriver })\\` with \\`import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres'\\`, or wire a custom driver with useDriver()`,\n });\n }\n\n return driver as TClass<TDriver>;\n }\n\n protected resolveDriver(): TDriver {\n this.wireDriverFromMetadata();\n\n return this.driver as TDriver;\n }\n\n /**\n * Assigns `this.driver` AND builds `this.connector` in one step - a\n * driver without its connector is silently bypassed on pooled queries. Returns the connector.\n */\n protected useDriver(opts: { driver: TDriver; schema?: Schema }): TConnector {\n this.driver = opts.driver;\n const connector = opts.driver.createConnector({ schema: opts.schema ?? this.getSchema() });\n this.connector = connector;\n\n return connector;\n }\n\n /** A datasource that opens on first use has no client, driver or connector until the first call that needs it has awaited `ensureOpen()`. */\n private assertOpenForSyncUse(opts: { member: string }): void {\n if (!this.isOpenDeferred()) {\n return;\n }\n\n if (this.isClosed()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource is closed | It opens on first use only before close()`,\n });\n }\n\n if (this.isOpening()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource is still opening | Inside configure() use the opening argument (opening.${opts.member}()); outside it, await ensureOpen()`,\n });\n }\n\n if (!this.isOpen()) {\n throw getError({\n message: `[${this.constructor.name}][${opts.member}] The datasource opens on first use and is not open | Await ensureOpen() first; repository calls do it for you`,\n });\n }\n }\n\n /** The handles `configure()` is given: the connector and the client through the ungated internals, so its own database work (migrations, seeding) needs no gate. */\n protected override createOpening(): IDataSourceOpening<TConnector, Client> {\n return {\n ...super.createOpening(),\n getConnector: () => this.wireDriverFromMetadata(),\n getClient: () => this.readClient(),\n };\n }\n\n /** Wires the driver on first use, so a `configure()` that only builds `this.client` is enough. */\n getConnector(): TConnector {\n this.assertOpenForSyncUse({ member: this.getConnector.name });\n\n return this.wireDriverFromMetadata();\n }\n\n /**\n * Raw driver client (`pg.Pool` / `Sql`). Throws rather\n * than handing back an `undefined` typed as `Client`.\n */\n getClient(): Client {\n this.assertOpenForSyncUse({ member: this.getClient.name });\n\n return this.readClient();\n }\n\n private readClient(): Client {\n if (this.driver) {\n return this.driver.getClient() as Client;\n }\n\n if (!this.client) {\n throw getError({\n message: `[${this.constructor.name}][getClient] No driver and no client | Assign this.driver in configure()`,\n });\n }\n\n return this.client;\n }\n\n /**\n * Ends the connection `configure()` opened. Runs once: every later call returns the first call's\n * promise. Goes through the driver, wired now if nothing queried yet, because its `end()` is the\n * engine's whole teardown - PGlite also clears the exit status it plants on the host process.\n */\n override close(): Promise<void> {\n // A stop that arrives while the first use is still opening waits for that open, then closes what it built.\n this.closePromise ??= this.settleOpening().then(() => this.endConnection());\n\n return this.closePromise;\n }\n\n /** Ends a client that a failed open left half-built and forgets the driver and connector, so the next open starts from nothing. */\n protected override async discardPartialOpen(): Promise<void> {\n const { client, driver } = this;\n\n this.client = undefined;\n this.driver = undefined;\n this.connector = undefined;\n\n // A close() that is waiting for this open owns the slot: clearing it would let a second close end the connection twice.\n if (!this.isClosed()) {\n this.closePromise = undefined;\n }\n\n if (driver && typeof driver.end === 'function') {\n await driver.end();\n\n return;\n }\n\n if (client !== undefined) {\n await this.drainClient({ client });\n }\n }\n\n private async endConnection(): Promise<void> {\n if (!this.driver && this.client === undefined) {\n return;\n }\n\n let driver: TDriver;\n\n try {\n driver = this.resolveDriver();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .warn('No driver to end the connection with | draining the client | error: %s', error);\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n // A hand-made driver cast past `IConnectorDriver` can lack the `end()` its type promises.\n if (typeof driver.end !== 'function') {\n this.logger.for(this.close.name).warn('The driver has no end() | draining the client');\n await this.drainClient({ client: this.client });\n\n return;\n }\n\n await driver.end();\n }\n\n /**\n * Soft-evicts the pool after a secret rotation: rebuilds against the rotated credentials without\n * touching live fields, swaps atomically, then drains the old pool. On failure live state is\n * restored, any half-built pool drained, and the error rethrown.\n */\n async onSecretRotated(opts: { key: string; secret: Record<string, string> }): Promise<void> {\n const logger = this.logger.for(this.onSecretRotated.name);\n\n // Nothing is open yet, so there is no pool to swap: the rotated credentials wait in the settings for the first use.\n if (this.isOpenDeferred() && !this.isOpen()) {\n Object.assign(this.settings, this.mapSecretToSettings({ secret: opts.secret }));\n logger.info(\n 'Datasource not open yet; credentials kept for its first use | key: %s',\n opts.key,\n );\n\n return;\n }\n\n const oldClient = this.getClient() as AnyType;\n\n // Snapshot so a failed rebuild restores the datasource verbatim;\n // `settings` is copied because rotation mutates it in place.\n const savedClient = this.client;\n const savedSettings = { ...(this.settings as AnyObject) };\n\n // Rotation only takes effect through this.settings + configure(); a configure() that\n // hard-codes its connection string or reads the environment directly rebuilds with stale credentials.\n Object.assign(this.settings as AnyObject, this.mapSecretToSettings({ secret: opts.secret }));\n\n // configure() overwrites this.client, so the new pool is captured\n // into a local and the old client restored at once - live fields\n // are never nulled and the old pool keeps serving until the swap.\n let newClient: Client;\n\n try {\n await this.configure();\n newClient = this.client as Client;\n } catch (error) {\n const halfBuilt = this.client as AnyType;\n this.client = savedClient;\n this.restoreSettings({ saved: savedSettings });\n\n if (halfBuilt && halfBuilt !== savedClient) {\n await this.drainClient({ client: halfBuilt });\n }\n\n logger.error('Secret rotation failed in configure(); kept old pool | key: %s', opts.key);\n throw error;\n }\n\n this.client = savedClient;\n\n // Wired into locals: live state must stay on the old pool until the swap below.\n let newDriver: TDriver;\n let newConnector: TConnector;\n\n try {\n const DriverClass = this.resolveDriverClass();\n newDriver = new DriverClass({ client: newClient as AnyType });\n newConnector = newDriver.createConnector({ schema: this.getSchema() });\n } catch (error) {\n this.restoreSettings({ saved: savedSettings });\n await this.drainClient({ client: newClient });\n\n logger.error('Secret rotation failed while wiring driver; kept old pool | key: %s', opts.key);\n throw error;\n }\n\n // Commit the live fields in one synchronous step so there is no null window,\n // then soft-evict the old pool so its in-flight transactions can finish.\n this.client = newClient as AnyType;\n this.driver = newDriver;\n this.connector = newConnector as AnyType;\n\n const isDrained = await this.drainClient({ client: oldClient });\n\n if (isDrained) {\n logger.info('Old pool drained after secret rotation | key: %s', opts.key);\n }\n }\n\n /** Puts `settings` back to the snapshot: a key the failed rotation added (the rotated `password`) is removed, not left behind. */\n private restoreSettings(opts: { saved: AnyObject }): void {\n const settings = this.settings as AnyObject;\n\n for (const key of Object.keys(settings)) {\n if (!(key in opts.saved)) {\n delete settings[key];\n }\n }\n\n Object.assign(settings, opts.saved);\n }\n\n /**\n * Shuts a client down by whichever verb its engine spells it with -\n * `pg.Pool` and postgres.js have `end()`, PGlite and libsql only `close()`.\n * Probed rather than type-tested: this tier must not name an engine, and a\n * client left undrained keeps a WASM instance or file handle alive forever.\n */\n protected async drainClient(opts: { client: unknown }): Promise<boolean> {\n const client = opts.client as AnyType;\n\n const drain = typeof client?.end === 'function' ? client.end : client?.close;\n\n if (typeof drain !== 'function') {\n this.logger\n .for(this.drainClient.name)\n .warn('Client exposes neither end() nor close(); nothing to drain');\n\n return false;\n }\n\n await drain.call(client);\n\n return true;\n }\n\n /** Vault's database engine returns `{ username, password }`; pg expects `{ user, password }`. */\n protected mapSecretToSettings(opts: { secret: Record<string, string> }): AnyObject {\n const { username, password } = opts.secret;\n const mapped: AnyObject = {};\n\n if (username !== undefined) {\n mapped.user = username;\n }\n\n if (password !== undefined) {\n mapped.password = password;\n }\n\n return mapped;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/internal/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAC
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/internal/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAC","sourcesContent":["export * from './echo';\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ILogger } from '@venizia/ignis-helpers/core';
|
|
2
|
+
/** Boot-time checks for models that declare `settings.access` (scope filtering). */
|
|
2
3
|
export declare class ScopeFilterUtility {
|
|
3
4
|
/**
|
|
4
5
|
* Why a `through` chain cannot work, or undefined. Walks from `name` toward the model that holds a resolver: every
|
|
@@ -4,6 +4,7 @@ import { MetadataRegistry, ScopeWriteGuards } from '@venizia/ignis-kernel';
|
|
|
4
4
|
import { ScopeThroughLink } from '../relational/core/repositories/common/scope-through.js';
|
|
5
5
|
import { BaseSearchEntity } from '../search/core/models/index.js';
|
|
6
6
|
import { getTableColumns, getTableName, is, Table } from 'drizzle-orm';
|
|
7
|
+
/** Boot-time checks for models that declare `settings.access` (scope filtering). */
|
|
7
8
|
export class ScopeFilterUtility {
|
|
8
9
|
/**
|
|
9
10
|
* Why a `through` chain cannot work, or undefined. Walks from `name` toward the model that holds a resolver: every
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,qDAAqD,CAAC;AACvF,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEvE,MAAM,OAAO,kBAAkB;IAC7B;;;;OAIG;IACK,MAAM,CAAC,cAAc,CAAC,IAI7B;QACC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QACtC,IAAI,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;QACnC,IAAI,IAAI,GAAG,CAAC,CAAC;QAEb,OAAO,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACpD,IAAI,IAAI,CAAC,CAAC;YAEV,IAAI,IAAI,GAAG,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBACtC,OAAO,0BAA0B,gBAAgB,CAAC,SAAS,OAAO,CAAC;YACrE,CAAC;YAED,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;YAE3B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,mDAAmD,CAAC;YAC7D,CAAC;YAED,IAAI,IAA4C,CAAC;YAEj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KAAK,CAAC;aACd,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport { MetadataRegistry, ScopeWriteGuards } from '@venizia/ignis-kernel';\nimport type { IModelRegistryEntry } from '@venizia/ignis-kernel';\nimport { ScopeThroughLink } from '@/relational/core/repositories/common/scope-through';\nimport { BaseSearchEntity } from '@/search/core/models';\nimport { getTableColumns, getTableName, is, Table } from 'drizzle-orm';\n\nexport class ScopeFilterUtility {\n /**\n * Why a `through` chain cannot work, or undefined. Walks from `name` toward the model that holds a resolver: every\n * hop needs a `one` relation with a single-column key, the parent needs an `access`, and the chain is at most\n * `ScopeThroughLink.MAX_DEPTH` hops with no model twice. A key with no index is a warning: it still works, slowly.\n */\n private static throughProblem(opts: {\n name: string;\n models: Map<string, IModelRegistryEntry>;\n logger?: ILogger;\n }): string | undefined {\n const { name, models, logger } = opts;\n let current = models.get(name);\n const visited = new Set([current]);\n let hops = 0;\n\n while (current?.metadata?.settings?.access?.through) {\n hops += 1;\n\n if (hops > ScopeThroughLink.MAX_DEPTH) {\n return `through is deeper than ${ScopeThroughLink.MAX_DEPTH} hops`;\n }\n\n const { schema } = current;\n\n if (!is(schema, Table)) {\n return 'the model has no table to read a foreign key from';\n }\n\n let link: ReturnType<typeof ScopeThroughLink.of>;\n\n try {\n link = ScopeThroughLink.of({\n schema,\n relation: current.metadata.settings.access.through.relation,\n relations: ScopeThroughLink.relationsOf({ entry: current }),\n });\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n\n if (hops === 1 && !ScopeThroughLink.isIndexed({ schema, property: link.childProperty })) {\n logger\n ?.for('assertScopeFilterSupported')\n .warn(\n '%s: the foreign key %s has no index, so every scoped read scans the table',\n name,\n link.childProperty,\n );\n }\n\n const { parentEntry } = link;\n\n if (!parentEntry?.metadata?.settings?.access) {\n return `the parent ${getTableName(link.parentSchema)} has no access setting`;\n }\n\n if (visited.has(parentEntry)) {\n return `through goes in a cycle at ${getTableName(link.parentSchema)}`;\n }\n\n visited.add(parentEntry);\n current = parentEntry;\n }\n\n return undefined;\n }\n\n /**\n * Refuses to boot when `settings.access` is declared where it cannot be honoured. Both cases\n * are silent at runtime and fail in OPPOSITE directions: a search-backed model returns more rows,\n * a context-less one returns none. The caller supplies `asyncContextEnabled` so no application\n * config type reaches into this tier.\n */\n static assertScopeFilterSupported(opts: {\n asyncContextEnabled: boolean;\n logger?: ILogger;\n }): void {\n const models = MetadataRegistry.getInstance().getAllModels();\n\n const searchBacked: string[] = [];\n const withoutAmbientContext: string[] = [];\n const invalidWriteGuard: string[] = [];\n const invalidThrough: string[] = [];\n\n for (const [name, entry] of models) {\n if (!entry.metadata?.settings?.access) {\n continue;\n }\n\n const modelClass = ResolverUtility.resolveValue({ value: entry.target });\n\n if (modelClass === BaseSearchEntity || modelClass.prototype instanceof BaseSearchEntity) {\n searchBacked.push(name);\n continue;\n }\n\n if (!opts.asyncContextEnabled) {\n withoutAmbientContext.push(name);\n }\n\n const { access } = entry.metadata.settings;\n\n if (!access.through === !access.resolve) {\n invalidThrough.push(`${name}: declare resolve or through, not both and not neither`);\n continue;\n }\n\n if (access.through) {\n const problem = ScopeFilterUtility.throughProblem({ name, models, logger: opts.logger });\n\n if (access.onMissing !== undefined) {\n invalidThrough.push(\n `${name}: onMissing is not available on through, a parent that resolves no scope always denies`,\n );\n }\n\n if (access.columns || access.write) {\n invalidThrough.push(`${name}: columns and write belong to a resolver, not to through`);\n }\n\n if (problem) {\n invalidThrough.push(`${name}: ${problem}`);\n }\n\n continue;\n }\n\n const { columns, write } = access;\n const writeGuard = write?.mode;\n\n if (writeGuard !== undefined && !ScopeWriteGuards.isValid(writeGuard)) {\n invalidWriteGuard.push(\n `${name}: write.mode '${String(writeGuard)}' is not reject or assign`,\n );\n }\n\n if (columns !== undefined) {\n const schema = (modelClass as { schema?: unknown }).schema;\n const known = is(schema, Table) ? Object.keys(getTableColumns(schema)) : undefined;\n const unknown = columns.filter((column) => known !== undefined && !known.includes(column));\n\n if (!Array.isArray(columns) || columns.length === 0) {\n invalidWriteGuard.push(`${name}: columns must be a non-empty list of property names`);\n } else if (unknown.length > 0) {\n invalidWriteGuard.push(\n `${name}: columns names ${unknown.join(', ')}, which the model does not have`,\n );\n }\n }\n }\n\n if (searchBacked.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access on a search-backed model | models: ${searchBacked.join(', ')}`,\n 'Search repositories never read this setting, so no row scope is applied.',\n 'Unlike the relational path, a missing scope here returns MORE rows rather than none - nothing fails, the result is just wider.',\n 'Scope the search query in the application, and remove settings.access from the model.',\n ].join(' | '),\n });\n }\n\n if (invalidThrough.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] invalid settings.access.through | ${invalidThrough.join(' | ')}`,\n 'A model declares resolve or through. A through names a one relation whose parent has an access of its own.',\n ].join(' | '),\n });\n }\n\n if (invalidWriteGuard.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] invalid settings.access write guard | ${invalidWriteGuard.join(' | ')}`,\n 'write.mode is reject or assign; columns, when declared, names properties of the model.',\n ].join(' | '),\n });\n }\n\n if (withoutAmbientContext.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access declared while asyncContext.enable is false | models: ${withoutAmbientContext.join(', ')}`,\n 'access.resolve() reads the ambient request context; the operation is its only argument.',\n 'With no context store every resolve() returns undefined, onMissing denies by default, and EVERY query on these models matches zero rows - with nothing naming the flag as the cause.',\n 'Set asyncContext.enable to true, or remove settings.access.',\n ].join(' | '),\n });\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scope-filter.js","sourceRoot":"","sources":["../../../src/common/scope-filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,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C,CAC9E,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC5B,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE;oBACP,mFAAmF,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;oBAC5G,0EAA0E;oBAC1E,gIAAgI;oBAChI,uFAAuF;iBACxF,CAAC,IAAI,CAAC,KAAK,CAAC;aACd,CAAC,CAAC;QACL,CAAC;QAED,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9B,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE;oBACP,kEAAkE,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;oBAC9F,4GAA4G;iBAC7G,CAAC,IAAI,CAAC,KAAK,CAAC;aACd,CAAC,CAAC;QACL,CAAC;QAED,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjC,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE;oBACP,sEAAsE,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;oBACrG,wFAAwF;iBACzF,CAAC,IAAI,CAAC,KAAK,CAAC;aACd,CAAC,CAAC;QACL,CAAC;QAED,IAAI,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrC,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE;oBACP,sGAAsG,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;oBACxI,yFAAyF;oBACzF,sLAAsL;oBACtL,6DAA6D;iBAC9D,CAAC,IAAI,CAAC,KAAK,CAAC;aACd,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport { MetadataRegistry, ScopeWriteGuards } from '@venizia/ignis-kernel';\nimport type { IModelRegistryEntry } from '@venizia/ignis-kernel';\nimport { ScopeThroughLink } from '@/relational/core/repositories/common/scope-through';\nimport { BaseSearchEntity } from '@/search/core/models';\nimport { getTableColumns, getTableName, is, Table } from 'drizzle-orm';\n\n/** Boot-time checks for models that declare `settings.access` (scope filtering). */\nexport class ScopeFilterUtility {\n /**\n * Why a `through` chain cannot work, or undefined. Walks from `name` toward the model that holds a resolver: every\n * hop needs a `one` relation with a single-column key, the parent needs an `access`, and the chain is at most\n * `ScopeThroughLink.MAX_DEPTH` hops with no model twice. A key with no index is a warning: it still works, slowly.\n */\n private static throughProblem(opts: {\n name: string;\n models: Map<string, IModelRegistryEntry>;\n logger?: ILogger;\n }): string | undefined {\n const { name, models, logger } = opts;\n let current = models.get(name);\n const visited = new Set([current]);\n let hops = 0;\n\n while (current?.metadata?.settings?.access?.through) {\n hops += 1;\n\n if (hops > ScopeThroughLink.MAX_DEPTH) {\n return `through is deeper than ${ScopeThroughLink.MAX_DEPTH} hops`;\n }\n\n const { schema } = current;\n\n if (!is(schema, Table)) {\n return 'the model has no table to read a foreign key from';\n }\n\n let link: ReturnType<typeof ScopeThroughLink.of>;\n\n try {\n link = ScopeThroughLink.of({\n schema,\n relation: current.metadata.settings.access.through.relation,\n relations: ScopeThroughLink.relationsOf({ entry: current }),\n });\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n\n if (hops === 1 && !ScopeThroughLink.isIndexed({ schema, property: link.childProperty })) {\n logger\n ?.for('assertScopeFilterSupported')\n .warn(\n '%s: the foreign key %s has no index, so every scoped read scans the table',\n name,\n link.childProperty,\n );\n }\n\n const { parentEntry } = link;\n\n if (!parentEntry?.metadata?.settings?.access) {\n return `the parent ${getTableName(link.parentSchema)} has no access setting`;\n }\n\n if (visited.has(parentEntry)) {\n return `through goes in a cycle at ${getTableName(link.parentSchema)}`;\n }\n\n visited.add(parentEntry);\n current = parentEntry;\n }\n\n return undefined;\n }\n\n /**\n * Refuses to boot when `settings.access` is declared where it cannot be honoured. Both cases\n * are silent at runtime and fail in OPPOSITE directions: a search-backed model returns more rows,\n * a context-less one returns none. The caller supplies `asyncContextEnabled` so no application\n * config type reaches into this tier.\n */\n static assertScopeFilterSupported(opts: {\n asyncContextEnabled: boolean;\n logger?: ILogger;\n }): void {\n const models = MetadataRegistry.getInstance().getAllModels();\n\n const searchBacked: string[] = [];\n const withoutAmbientContext: string[] = [];\n const invalidWriteGuard: string[] = [];\n const invalidThrough: string[] = [];\n\n for (const [name, entry] of models) {\n if (!entry.metadata?.settings?.access) {\n continue;\n }\n\n const modelClass = ResolverUtility.resolveValue({ value: entry.target });\n\n if (modelClass === BaseSearchEntity || modelClass.prototype instanceof BaseSearchEntity) {\n searchBacked.push(name);\n continue;\n }\n\n if (!opts.asyncContextEnabled) {\n withoutAmbientContext.push(name);\n }\n\n const { access } = entry.metadata.settings;\n\n if (!access.through === !access.resolve) {\n invalidThrough.push(`${name}: declare resolve or through, not both and not neither`);\n continue;\n }\n\n if (access.through) {\n const problem = ScopeFilterUtility.throughProblem({ name, models, logger: opts.logger });\n\n if (access.onMissing !== undefined) {\n invalidThrough.push(\n `${name}: onMissing is not available on through, a parent that resolves no scope always denies`,\n );\n }\n\n if (access.columns || access.write) {\n invalidThrough.push(`${name}: columns and write belong to a resolver, not to through`);\n }\n\n if (problem) {\n invalidThrough.push(`${name}: ${problem}`);\n }\n\n continue;\n }\n\n const { columns, write } = access;\n const writeGuard = write?.mode;\n\n if (writeGuard !== undefined && !ScopeWriteGuards.isValid(writeGuard)) {\n invalidWriteGuard.push(\n `${name}: write.mode '${String(writeGuard)}' is not reject or assign`,\n );\n }\n\n if (columns !== undefined) {\n const schema = (modelClass as { schema?: unknown }).schema;\n const known = is(schema, Table) ? Object.keys(getTableColumns(schema)) : undefined;\n const unknown = columns.filter((column) => known !== undefined && !known.includes(column));\n\n if (!Array.isArray(columns) || columns.length === 0) {\n invalidWriteGuard.push(`${name}: columns must be a non-empty list of property names`);\n } else if (unknown.length > 0) {\n invalidWriteGuard.push(\n `${name}: columns names ${unknown.join(', ')}, which the model does not have`,\n );\n }\n }\n }\n\n if (searchBacked.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access on a search-backed model | models: ${searchBacked.join(', ')}`,\n 'Search repositories never read this setting, so no row scope is applied.',\n 'Unlike the relational path, a missing scope here returns MORE rows rather than none - nothing fails, the result is just wider.',\n 'Scope the search query in the application, and remove settings.access from the model.',\n ].join(' | '),\n });\n }\n\n if (invalidThrough.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] invalid settings.access.through | ${invalidThrough.join(' | ')}`,\n 'A model declares resolve or through. A through names a one relation whose parent has an access of its own.',\n ].join(' | '),\n });\n }\n\n if (invalidWriteGuard.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] invalid settings.access write guard | ${invalidWriteGuard.join(' | ')}`,\n 'write.mode is reject or assign; columns, when declared, names properties of the model.',\n ].join(' | '),\n });\n }\n\n if (withoutAmbientContext.length > 0) {\n throw getError({\n message: [\n `[assertScopeFilterSupported] settings.access declared while asyncContext.enable is false | models: ${withoutAmbientContext.join(', ')}`,\n 'access.resolve() reads the ambient request context; the operation is its only argument.',\n 'With no context store every resolve() returns undefined, onMissing denies by default, and EVERY query on these models matches zero rows - with nothing naming the flag as the cause.',\n 'Set asyncContext.enable to true, or remove settings.access.',\n ].join(' | '),\n });\n }\n }\n}\n"]}
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import type { TFilter } from '@venizia/ignis-filter';
|
|
2
|
+
/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */
|
|
2
3
|
export interface IAuthToken {
|
|
3
4
|
value: string;
|
|
5
|
+
/**
|
|
6
|
+
* The authorization scheme.
|
|
7
|
+
*
|
|
8
|
+
* @default 'Bearer'
|
|
9
|
+
*/
|
|
4
10
|
type?: string;
|
|
5
11
|
provider?: string;
|
|
6
12
|
}
|
|
@@ -31,6 +37,7 @@ export interface IHttpCallOptions {
|
|
|
31
37
|
headers?: THttpHeaders;
|
|
32
38
|
signal?: AbortSignal;
|
|
33
39
|
}
|
|
40
|
+
/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */
|
|
34
41
|
export interface IHttpDataSourceSettings {
|
|
35
42
|
/** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */
|
|
36
43
|
baseUrl: string;
|
|
@@ -70,6 +77,7 @@ export interface IHttpWriteResult<R> {
|
|
|
70
77
|
/** What the route answered beside the rows, when the server marked it with `x-response-extra`. */
|
|
71
78
|
extra?: Record<string, unknown>;
|
|
72
79
|
}
|
|
80
|
+
/** The query a repository call sends: an optional `filter` typed against the entity `E`. */
|
|
73
81
|
export type THttpQuery<E extends object> = {
|
|
74
82
|
filter?: TFilter<E>;
|
|
75
83
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TFilter } from '@venizia/ignis-filter';\n\nexport interface IAuthToken {\n value: string;\n type?: string;\n provider?: string;\n}\n\n/** The request a hook is asked about: the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/** `undefined` means no token for this request. A throw fails the request with that error. */\nexport type TAuthTokenResolver = (context: IHttpRequestContext) => IAuthToken | undefined;\n\n/** Headers for this request. A throw fails the request with that error. */\nexport type THttpHeadersResolver = (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n/** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */\nexport type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Run on every send, the 401 retry included. Wins over `headers`; a call's own headers win over\n * it. `x-request-count` is refused here too; an `authorization` here stands only when no token is\n * resolved.\n */\n headersResolver?: THttpHeadersResolver;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. */\n authTokenResolver?: TAuthTokenResolver;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */\n onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;\n}\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\nexport type THttpQuery<E extends object> = { filter?: TFilter<E> };\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/http/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TFilter } from '@venizia/ignis-filter';\n\n/** A credential the HTTP datasource attaches to a request: `Authorization: <type> <value>`, and `provider`, when set, as the `x-auth-provider` header. */\nexport interface IAuthToken {\n value: string;\n /**\n * The authorization scheme.\n *\n * @default 'Bearer'\n */\n type?: string;\n provider?: string;\n}\n\n/** The request a hook is asked about: the repository `paths`, the method, and the final URL with its query. */\nexport interface IHttpRequestContext {\n paths: Array<string>;\n method: string;\n url: string;\n /** The call's own signal: a hook may stop waiting on it. A refresh shared by other calls should not be aborted by one. */\n signal?: AbortSignal;\n}\n\n/** `undefined` means no token for this request. A throw fails the request with that error. */\nexport type TAuthTokenResolver = (context: IHttpRequestContext) => IAuthToken | undefined;\n\n/** Headers for this request. A throw fails the request with that error. */\nexport type THttpHeadersResolver = (context: IHttpRequestContext) => THttpHeaders | undefined;\n\n/** Not `Record` alone: header names are case-insensitive, and an object merge appends two spellings. */\nexport type THttpHeaders = Headers | Array<[string, string]> | Record<string, string>;\n\n/**\n * A request body. A plain object or array goes out as JSON; a string, `Blob`, `FormData`,\n * `URLSearchParams`, `ArrayBuffer` or typed array goes out as it is. Never a stream: the 401 retry\n * sends the same body twice.\n */\nexport type THttpBody = string | object;\n\n/** The list-extras request and result types live with the server contract, in kernel. */\nexport type { TExtraRequest, TExtraResult } from '@venizia/ignis-kernel/repository';\n\n/** What one call may add: its own headers (they win over the configured ones) and a signal to abort it. */\nexport interface IHttpCallOptions {\n headers?: THttpHeaders;\n signal?: AbortSignal;\n}\n\n/** Settings of the HTTP datasource: where to send, which headers and token to attach, and what to do on a 401. */\nexport interface IHttpDataSourceSettings {\n /** An absolute URL, or a path from the page origin (`/api`). A path-relative one is refused. */\n baseUrl: string;\n\n /** The server's `error.rootKey`: an error envelope wrapped under it is unwrapped before it is read. */\n errorRootKey?: string;\n\n /** Sent on every request. `x-request-count` is refused - the connector owns it. */\n headers?: THttpHeaders;\n\n /**\n * Run on every send, the 401 retry included. Wins over `headers`; a call's own headers win over\n * it. `x-request-count` is refused here too; an `authorization` here stands only when no token is\n * resolved.\n */\n headersResolver?: THttpHeadersResolver;\n\n /** Wins over `authTokenResolver`, and is sent whatever the request. */\n authToken?: IAuthToken;\n\n /** Run on every send, the 401 retry included. */\n authTokenResolver?: TAuthTokenResolver;\n\n /** Runs on a 401: `true` retries once (re-resolving the token), `false` lets the 401 stand. */\n onUnauthorized?: (context: IHttpRequestContext) => Promise<boolean> | boolean;\n}\n\n/** A list with no `Content-Range` has no total - `hasRange` says so rather than using the page size. */\nexport interface IHttpReadResult<R> {\n data: R;\n hasRange: boolean;\n /** Raw header: tells a present-but-unreadable one from an absent one. */\n contentRange?: string;\n total?: number;\n skip?: number;\n dataLength: number;\n /** What a list answered beside its rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** What a write answers: the rows the server returned, and its `x-response-count`. */\nexport interface IHttpWriteResult<R> {\n data: R;\n count: number;\n /** What the route answered beside the rows, when the server marked it with `x-response-extra`. */\n extra?: Record<string, unknown>;\n}\n\n/** The query a repository call sends: an optional `filter` typed against the entity `E`. */\nexport type THttpQuery<E extends object> = { filter?: TFilter<E> };\n\n/** Query parameters a route takes beside `filter` or `where` - a keyword, a scope. The filter and `where` win over a key of the same name. */\nexport type THttpExtraQuery = Record<string, unknown>;\n\n/** What the IGNIS search route answers: the total as `found` (`isFoundExact` is false when it is an estimate) and the hits. */\nexport interface IHttpSearchResult<R> {\n found: number;\n isFoundExact: boolean;\n hits: Array<{ document: R; score?: number; highlight?: unknown; highlights?: Array<unknown> }>;\n}\n"]}
|
|
@@ -34,6 +34,19 @@ export declare class HttpDataSource extends AbstractDataSource<IHttpDataSourceSe
|
|
|
34
34
|
}): Headers;
|
|
35
35
|
/** The browser global `location` is not declared for a server build, so it is probed, not assumed. */
|
|
36
36
|
protected resolveLocationOrigin(): string | undefined;
|
|
37
|
+
/** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */
|
|
38
|
+
protected static toEchoedPath(opts: {
|
|
39
|
+
path: string;
|
|
40
|
+
}): string;
|
|
41
|
+
/** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */
|
|
42
|
+
protected assertPathsStayUnderBase(opts: {
|
|
43
|
+
paths: Array<string>;
|
|
44
|
+
}): void;
|
|
45
|
+
/** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */
|
|
46
|
+
protected assertUnderBase(opts: {
|
|
47
|
+
url: URL;
|
|
48
|
+
origin?: string;
|
|
49
|
+
}): void;
|
|
37
50
|
buildUrl(opts: {
|
|
38
51
|
paths: Array<string>;
|
|
39
52
|
query?: Record<string, unknown>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { EchoUtility } from '../common/internal/index.js';
|
|
1
2
|
import { HttpReadShapes } from './common/constants.js';
|
|
2
3
|
import { AbstractDataSource } from '@venizia/ignis-kernel/repository';
|
|
3
4
|
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
@@ -7,6 +8,14 @@ import { HttpResponseReader } from './common/readers.js';
|
|
|
7
8
|
import { HttpWire } from './common/wire.js';
|
|
8
9
|
/** A scheme and `//` make a URL absolute - `localhost:3000` has neither. Read by pattern: `URL.canParse` needs Safari 17 or Chrome 120, and this runs in pages. */
|
|
9
10
|
const ABSOLUTE_URL_PATTERN = /^[a-z][a-z\d+.-]*:\/\//i;
|
|
11
|
+
/** A backslash is a separator to the URL parser, and a control character (a tab or a newline inside `.<TAB>.`) is dropped by it: neither may hide a dot segment. `%5c` is the encoded backslash. */
|
|
12
|
+
const UNSAFE_REQUEST_PATH_PATTERN = /[\p{Cc}\\]|%5c/iu;
|
|
13
|
+
/** What ends a path segment for the URL parser: a slash, a `?` or a `#` (it ends the path itself, so `..?` is a `..` segment), and the encoded slash, which a server may decode into a separator. */
|
|
14
|
+
const REQUEST_PATH_SEPARATOR_PATTERN = /[/?#]|%2f/i;
|
|
15
|
+
/** The longest part of a refused path an error message copies: a huge path is not copied whole into the error and the log. */
|
|
16
|
+
const MAX_ECHOED_PATH_LENGTH = 200;
|
|
17
|
+
/** A segment that is `.` or `..` once its `%2e` is decoded. */
|
|
18
|
+
const DOT_SEGMENT_PATTERN = /^(?:\.|%2e){1,2}$/i;
|
|
10
19
|
/** Reads an IGNIS REST server through the repository contract. Targets IGNIS, not any REST API. */
|
|
11
20
|
export class HttpDataSource extends AbstractDataSource {
|
|
12
21
|
constructor(opts) {
|
|
@@ -23,6 +32,13 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
23
32
|
message: `[${name}] baseUrl '${settings.baseUrl}' is neither absolute nor a path from the origin | Pass '/api' or an absolute URL such as 'https://api.example.com'`,
|
|
24
33
|
});
|
|
25
34
|
}
|
|
35
|
+
// A `?` or `#` in the base would swallow the request paths into the query or the fragment.
|
|
36
|
+
if (/[?#]/.test(settings.baseUrl)) {
|
|
37
|
+
throw getError({
|
|
38
|
+
statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
|
|
39
|
+
message: `[${name}] baseUrl must not carry a query or a fragment: the request paths would end up inside it | Pass the base without '?' or '#', and use the call's query option`,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
26
42
|
this.configuredHeaders = configured;
|
|
27
43
|
this.name = name;
|
|
28
44
|
this.settings = settings;
|
|
@@ -82,8 +98,45 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
82
98
|
}
|
|
83
99
|
return typeof location.origin === 'string' ? location.origin : undefined;
|
|
84
100
|
}
|
|
101
|
+
/** The path as an error message quotes it: cut at 200 characters, with an ellipsis. */
|
|
102
|
+
static toEchoedPath(opts) {
|
|
103
|
+
const { path } = opts;
|
|
104
|
+
return path.length > MAX_ECHOED_PATH_LENGTH
|
|
105
|
+
? `${path.slice(0, MAX_ECHOED_PATH_LENGTH)}…`
|
|
106
|
+
: path;
|
|
107
|
+
}
|
|
108
|
+
/** The request paths name a place under the base path, so none may be a dot segment, hide one, or carry a separator the URL parser would read differently from a server. */
|
|
109
|
+
assertPathsStayUnderBase(opts) {
|
|
110
|
+
for (const path of opts.paths) {
|
|
111
|
+
const segments = path.split(REQUEST_PATH_SEPARATOR_PATTERN);
|
|
112
|
+
const isEscaping = UNSAFE_REQUEST_PATH_PATTERN.test(path) ||
|
|
113
|
+
// A trailing space is stripped from the whole URL by the parser, so `.. ` ends as `..`.
|
|
114
|
+
segments.some((segment) => DOT_SEGMENT_PATTERN.test(segment.trimEnd()));
|
|
115
|
+
if (isEscaping) {
|
|
116
|
+
throw getError({
|
|
117
|
+
statusCode: HTTP.ResultCodes.RS_4.BadRequest,
|
|
118
|
+
message: `[${this.name}] A request path must stay under the base path: no dot segment, backslash or control character | path: '${EchoUtility.toSafeEcho({ value: HttpDataSource.toEchoedPath({ path }) })}'`,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** The resolved URL, whatever built it, is on the base's origin and under its path: the check that holds when the text checks above miss a form. */
|
|
124
|
+
assertUnderBase(opts) {
|
|
125
|
+
const { url, origin } = opts;
|
|
126
|
+
const base = new URL(this.settings.baseUrl, origin);
|
|
127
|
+
const basePath = base.pathname.replace(/\/+$/, '');
|
|
128
|
+
const isUnderBase = url.origin === base.origin &&
|
|
129
|
+
(url.pathname === basePath || url.pathname.startsWith(`${basePath}/`));
|
|
130
|
+
if (!isUnderBase) {
|
|
131
|
+
throw getError({
|
|
132
|
+
statusCode: HTTP.ResultCodes.RS_4.BadRequest,
|
|
133
|
+
message: `[${this.name}] A request path must stay under the base path: the URL left the origin or the base path`,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
85
137
|
buildUrl(opts) {
|
|
86
138
|
const { paths, query } = opts;
|
|
139
|
+
this.assertPathsStayUnderBase({ paths });
|
|
87
140
|
const requestUrl = this.network.getRequestUrl({ paths });
|
|
88
141
|
// A page or a Web Worker has an origin to resolve '/api' against; a server has none.
|
|
89
142
|
const origin = this.isRelativeBaseUrl ? this.resolveLocationOrigin() : undefined;
|
|
@@ -94,6 +147,7 @@ export class HttpDataSource extends AbstractDataSource {
|
|
|
94
147
|
});
|
|
95
148
|
}
|
|
96
149
|
const url = new URL(requestUrl, origin);
|
|
150
|
+
this.assertUnderBase({ url, origin });
|
|
97
151
|
const parameters = Object.entries(query ?? {});
|
|
98
152
|
for (const [key, value] of parameters) {
|
|
99
153
|
if (value === undefined) {
|