@jantstack/adonis-authz 1.1.0 → 2.4.0-alpha.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.
- package/LICENSE +1 -1
- package/README.md +837 -51
- package/build/commands/authz_catalog_diff.d.ts +28 -0
- package/build/commands/authz_catalog_diff.d.ts.map +1 -0
- package/build/commands/authz_catalog_diff.js +67 -0
- package/build/commands/authz_catalog_diff.js.map +1 -0
- package/build/commands/authz_catalog_prune_orphans.d.ts +78 -0
- package/build/commands/authz_catalog_prune_orphans.d.ts.map +1 -0
- package/build/commands/authz_catalog_prune_orphans.js +136 -0
- package/build/commands/authz_catalog_prune_orphans.js.map +1 -0
- package/build/commands/authz_catalog_sync.d.ts +37 -0
- package/build/commands/authz_catalog_sync.d.ts.map +1 -0
- package/build/commands/authz_catalog_sync.js +81 -0
- package/build/commands/authz_catalog_sync.js.map +1 -0
- package/build/commands/authz_freeze.d.ts +44 -0
- package/build/commands/authz_freeze.d.ts.map +1 -0
- package/build/commands/authz_freeze.js +95 -0
- package/build/commands/authz_freeze.js.map +1 -0
- package/build/commands/authz_reconcile.d.ts +102 -0
- package/build/commands/authz_reconcile.d.ts.map +1 -0
- package/build/commands/authz_reconcile.js +294 -0
- package/build/commands/authz_reconcile.js.map +1 -0
- package/build/commands/authz_relations_reconcile.d.ts +73 -0
- package/build/commands/authz_relations_reconcile.d.ts.map +1 -0
- package/build/commands/authz_relations_reconcile.js +225 -0
- package/build/commands/authz_relations_reconcile.js.map +1 -0
- package/build/commands/authz_scopes_relay.d.ts +47 -0
- package/build/commands/authz_scopes_relay.d.ts.map +1 -0
- package/build/commands/authz_scopes_relay.js +141 -0
- package/build/commands/authz_scopes_relay.js.map +1 -0
- package/build/commands/authz_unfreeze.d.ts +37 -0
- package/build/commands/authz_unfreeze.d.ts.map +1 -0
- package/build/commands/authz_unfreeze.js +92 -0
- package/build/commands/authz_unfreeze.js.map +1 -0
- package/build/commands/main.d.ts +8 -1
- package/build/commands/main.d.ts.map +1 -1
- package/build/commands/main.js +8 -1
- package/build/commands/main.js.map +1 -1
- package/build/commands/openfga_provision.d.ts +46 -4
- package/build/commands/openfga_provision.d.ts.map +1 -1
- package/build/commands/openfga_provision.js +91 -7
- package/build/commands/openfga_provision.js.map +1 -1
- package/build/configure.d.ts +11 -0
- package/build/configure.d.ts.map +1 -1
- package/build/configure.js +37 -1
- package/build/configure.js.map +1 -1
- package/build/index.d.ts +75 -7
- package/build/index.d.ts.map +1 -1
- package/build/index.js +67 -5
- package/build/index.js.map +1 -1
- package/build/providers/authz_provider.d.ts +26 -2
- package/build/providers/authz_provider.d.ts.map +1 -1
- package/build/providers/authz_provider.js +48 -2
- package/build/providers/authz_provider.js.map +1 -1
- package/build/services/relations.d.ts +14 -0
- package/build/services/relations.d.ts.map +1 -0
- package/build/services/relations.js +17 -0
- package/build/services/relations.js.map +1 -0
- package/build/src/catalog/catalog.d.ts +289 -0
- package/build/src/catalog/catalog.d.ts.map +1 -0
- package/build/src/catalog/catalog.js +859 -0
- package/build/src/catalog/catalog.js.map +1 -0
- package/build/src/catalog/catalog_cache.d.ts +324 -0
- package/build/src/catalog/catalog_cache.d.ts.map +1 -0
- package/build/src/catalog/catalog_cache.js +666 -0
- package/build/src/catalog/catalog_cache.js.map +1 -0
- package/build/src/clock.d.ts +24 -0
- package/build/src/clock.d.ts.map +1 -0
- package/build/src/clock.js +7 -0
- package/build/src/clock.js.map +1 -0
- package/build/src/define_config.d.ts +201 -7
- package/build/src/define_config.d.ts.map +1 -1
- package/build/src/define_config.js.map +1 -1
- package/build/src/drivers/database_driver.d.ts +324 -15
- package/build/src/drivers/database_driver.d.ts.map +1 -1
- package/build/src/drivers/database_driver.js +1107 -128
- package/build/src/drivers/database_driver.js.map +1 -1
- package/build/src/drivers/database_relations_driver.d.ts +75 -0
- package/build/src/drivers/database_relations_driver.d.ts.map +1 -0
- package/build/src/drivers/database_relations_driver.js +450 -0
- package/build/src/drivers/database_relations_driver.js.map +1 -0
- package/build/src/drivers/openfga_driver.d.ts +963 -55
- package/build/src/drivers/openfga_driver.d.ts.map +1 -1
- package/build/src/drivers/openfga_driver.js +2693 -372
- package/build/src/drivers/openfga_driver.js.map +1 -1
- package/build/src/drivers/openfga_facts.d.ts +369 -0
- package/build/src/drivers/openfga_facts.d.ts.map +1 -0
- package/build/src/drivers/openfga_facts.js +813 -0
- package/build/src/drivers/openfga_facts.js.map +1 -0
- package/build/src/drivers/openfga_relations_driver.d.ts +120 -0
- package/build/src/drivers/openfga_relations_driver.d.ts.map +1 -0
- package/build/src/drivers/openfga_relations_driver.js +466 -0
- package/build/src/drivers/openfga_relations_driver.js.map +1 -0
- package/build/src/errors.d.ts +586 -0
- package/build/src/errors.d.ts.map +1 -1
- package/build/src/errors.js +583 -0
- package/build/src/errors.js.map +1 -1
- package/build/src/expiry.d.ts +27 -0
- package/build/src/expiry.d.ts.map +1 -0
- package/build/src/expiry.js +50 -0
- package/build/src/expiry.js.map +1 -0
- package/build/src/freeze.d.ts +120 -0
- package/build/src/freeze.d.ts.map +1 -0
- package/build/src/freeze.js +172 -0
- package/build/src/freeze.js.map +1 -0
- package/build/src/hierarchical_resolver.d.ts +56 -0
- package/build/src/hierarchical_resolver.d.ts.map +1 -0
- package/build/src/hierarchical_resolver.js +87 -0
- package/build/src/hierarchical_resolver.js.map +1 -0
- package/build/src/{middleware → http}/app_access_middleware.d.ts +8 -6
- package/build/src/http/app_access_middleware.d.ts.map +1 -0
- package/build/src/{middleware → http}/app_access_middleware.js +10 -26
- package/build/src/http/app_access_middleware.js.map +1 -0
- package/build/src/http/resource_access_middleware.d.ts +105 -0
- package/build/src/http/resource_access_middleware.d.ts.map +1 -0
- package/build/src/http/resource_access_middleware.js +81 -0
- package/build/src/http/resource_access_middleware.js.map +1 -0
- package/build/src/identity.d.ts +228 -0
- package/build/src/identity.d.ts.map +1 -0
- package/build/src/identity.js +457 -0
- package/build/src/identity.js.map +1 -0
- package/build/src/manager.d.ts +536 -7
- package/build/src/manager.d.ts.map +1 -1
- package/build/src/manager.js +2676 -23
- package/build/src/manager.js.map +1 -1
- package/build/src/memoize_ancestors.d.ts +23 -0
- package/build/src/memoize_ancestors.d.ts.map +1 -0
- package/build/src/memoize_ancestors.js +42 -0
- package/build/src/memoize_ancestors.js.map +1 -0
- package/build/src/models/authz_assignment.d.ts +11 -11
- package/build/src/models/authz_assignment.d.ts.map +1 -1
- package/build/src/models/authz_deny.d.ts +11 -11
- package/build/src/models/authz_deny.d.ts.map +1 -1
- package/build/src/models/authz_permission.d.ts +17 -11
- package/build/src/models/authz_permission.d.ts.map +1 -1
- package/build/src/models/authz_permission.js +4 -0
- package/build/src/models/authz_permission.js.map +1 -1
- package/build/src/models/authz_role.d.ts +19 -12
- package/build/src/models/authz_role.d.ts.map +1 -1
- package/build/src/models/authz_role.js +6 -1
- package/build/src/models/authz_role.js.map +1 -1
- package/build/src/models/authz_role_permission.d.ts +11 -11
- package/build/src/models/authz_role_permission.d.ts.map +1 -1
- package/build/src/openfga.d.ts +29 -0
- package/build/src/openfga.d.ts.map +1 -0
- package/build/src/openfga.js +26 -0
- package/build/src/openfga.js.map +1 -0
- package/build/src/reconcile.d.ts +37 -0
- package/build/src/reconcile.d.ts.map +1 -0
- package/build/src/reconcile.js +69 -0
- package/build/src/reconcile.js.map +1 -0
- package/build/src/relation_partition_trigger.d.ts +8 -0
- package/build/src/relation_partition_trigger.d.ts.map +1 -0
- package/build/src/relation_partition_trigger.js +85 -0
- package/build/src/relation_partition_trigger.js.map +1 -0
- package/build/src/relations/define_relations_config.d.ts +58 -0
- package/build/src/relations/define_relations_config.d.ts.map +1 -0
- package/build/src/relations/define_relations_config.js +144 -0
- package/build/src/relations/define_relations_config.js.map +1 -0
- package/build/src/relations/manager.d.ts +38 -0
- package/build/src/relations/manager.d.ts.map +1 -0
- package/build/src/relations/manager.js +156 -0
- package/build/src/relations/manager.js.map +1 -0
- package/build/src/relations/reconcile.d.ts +62 -0
- package/build/src/relations/reconcile.d.ts.map +1 -0
- package/build/src/relations/reconcile.js +138 -0
- package/build/src/relations/reconcile.js.map +1 -0
- package/build/src/relations_config_store.d.ts +22 -0
- package/build/src/relations_config_store.d.ts.map +1 -0
- package/build/src/relations_config_store.js +74 -0
- package/build/src/relations_config_store.js.map +1 -0
- package/build/src/scope_outbox.d.ts +69 -0
- package/build/src/scope_outbox.d.ts.map +1 -0
- package/build/src/scope_outbox.js +291 -0
- package/build/src/scope_outbox.js.map +1 -0
- package/build/src/shared/backend_guard.d.ts +106 -0
- package/build/src/shared/backend_guard.d.ts.map +1 -0
- package/build/src/shared/backend_guard.js +246 -0
- package/build/src/shared/backend_guard.js.map +1 -0
- package/build/src/shared/sql_expiry.d.ts +53 -0
- package/build/src/shared/sql_expiry.d.ts.map +1 -0
- package/build/src/shared/sql_expiry.js +66 -0
- package/build/src/shared/sql_expiry.js.map +1 -0
- package/build/src/sql_descendants.d.ts +97 -0
- package/build/src/sql_descendants.d.ts.map +1 -0
- package/build/src/sql_descendants.js +203 -0
- package/build/src/sql_descendants.js.map +1 -0
- package/build/src/testing/contract.d.ts +212 -7
- package/build/src/testing/contract.d.ts.map +1 -1
- package/build/src/testing/contract.js +3449 -24
- package/build/src/testing/contract.js.map +1 -1
- package/build/src/testing/main.d.ts +10 -2
- package/build/src/testing/main.d.ts.map +1 -1
- package/build/src/testing/main.js +5 -1
- package/build/src/testing/main.js.map +1 -1
- package/build/src/testing/migration_contract.d.ts +284 -0
- package/build/src/testing/migration_contract.d.ts.map +1 -0
- package/build/src/testing/migration_contract.js +586 -0
- package/build/src/testing/migration_contract.js.map +1 -0
- package/build/src/testing/relations_contract.d.ts +51 -0
- package/build/src/testing/relations_contract.d.ts.map +1 -0
- package/build/src/testing/relations_contract.js +654 -0
- package/build/src/testing/relations_contract.js.map +1 -0
- package/build/src/testing/relations_reconcile_contract.d.ts +24 -0
- package/build/src/testing/relations_reconcile_contract.d.ts.map +1 -0
- package/build/src/testing/relations_reconcile_contract.js +172 -0
- package/build/src/testing/relations_reconcile_contract.js.map +1 -0
- package/build/src/testing/scope_tree.d.ts +65 -0
- package/build/src/testing/scope_tree.d.ts.map +1 -0
- package/build/src/testing/scope_tree.js +145 -0
- package/build/src/testing/scope_tree.js.map +1 -0
- package/build/src/traits/authz_scopes.d.ts +30 -6
- package/build/src/traits/authz_scopes.d.ts.map +1 -1
- package/build/src/traits/authz_scopes.js +30 -18
- package/build/src/traits/authz_scopes.js.map +1 -1
- package/build/src/traits/has_uuid.d.ts +12 -12
- package/build/src/traits/has_uuid.d.ts.map +1 -1
- package/build/src/types.d.ts +1313 -28
- package/build/src/types.d.ts.map +1 -1
- package/build/src/types.js +20 -4
- package/build/src/types.js.map +1 -1
- package/build/stubs/config/app_acl.stub +4 -2
- package/build/stubs/config/authorization.stub +168 -14
- package/build/stubs/migration.stub +183 -13
- package/build/stubs/scopes_outbox_migration.stub +57 -0
- package/package.json +14 -7
- package/build/commands/openfga_import.d.ts +0 -28
- package/build/commands/openfga_import.d.ts.map +0 -1
- package/build/commands/openfga_import.js +0 -74
- package/build/commands/openfga_import.js.map +0 -1
- package/build/src/catalog.d.ts +0 -3
- package/build/src/catalog.d.ts.map +0 -1
- package/build/src/catalog.js +0 -103
- package/build/src/catalog.js.map +0 -1
- package/build/src/middleware/app_access_middleware.d.ts.map +0 -1
- package/build/src/middleware/app_access_middleware.js.map +0 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **La config de relaciones PERSISTIDA** (Fase 4, lote 4-5 · 🟡3) — vive en la
|
|
3
|
+
* tabla `authz_relations_config`, bajo el gate de versión (invariante 14), como
|
|
4
|
+
* el catálogo. Es la copia de la config de relaciones en la BASE, para que
|
|
5
|
+
* cualquier proceso —también uno SIN `defineRelationsConfig` en memoria— lea
|
|
6
|
+
* los tipos declarados. Hoy la CONSUME `authz:relations:reconcile` (la config
|
|
7
|
+
* del DESTINO, para vigilar la deriva del modelo fusionado en `--dry-run`).
|
|
8
|
+
*
|
|
9
|
+
* Este módulo vive en `src/` (NO en `src/relations/`, que la regla 2 de pureza
|
|
10
|
+
* mantiene aislado del `db`): es la ruta que TOCA la base, como `catalog.ts`.
|
|
11
|
+
* Importa el TIPO y el validador de `src/relations/` (la dirección permitida:
|
|
12
|
+
* `relations/` no importa hacia afuera; los demás sí importan de él).
|
|
13
|
+
*
|
|
14
|
+
* **Nota (Fase 4-8):** el modelo fusionado del store lo publica
|
|
15
|
+
* `openfga:provision` leyendo los tipos de relación del CONFIG estático
|
|
16
|
+
* (`relations.config`, como `permissions` sale de `catalogs`), no de esta
|
|
17
|
+
* tabla: el comando es `startApp: false` (bootstrap del appliance, sin base) y
|
|
18
|
+
* no puede leer la base. Por eso el antiguo `republishFusedModel` —el
|
|
19
|
+
* republicador basado en esta tabla, con CAS sobre `model_id`— se retiró en
|
|
20
|
+
* 4-8: no tenía llamador de producción (la carrera que protegía no ocurre;
|
|
21
|
+
* republicar el modelo es un paso manual de operador, escritor único). Ver el
|
|
22
|
+
* informe 4-8. La columna `model_id` queda sin uso (cleanup futuro).
|
|
23
|
+
*/
|
|
24
|
+
import { systemClock } from './clock.js';
|
|
25
|
+
import { guardSql } from './shared/backend_guard.js';
|
|
26
|
+
import db from '@adonisjs/lucid/services/db';
|
|
27
|
+
import { invalidateAuthzCatalog, withAuthzCatalogWrite } from './catalog/catalog_cache.js';
|
|
28
|
+
import { defineRelationsConfig } from './relations/define_relations_config.js';
|
|
29
|
+
const TABLE = 'authz_relations_config';
|
|
30
|
+
const ROW_ID = 1;
|
|
31
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
32
|
+
function connectionOf(options) {
|
|
33
|
+
return options?.connection ? db.connection(options.connection) : db;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* **Guarda (persiste) la config de relaciones** bajo el gate de versión: la
|
|
37
|
+
* valida (⚪4/F-05 de config), la serializa a JSON y hace UPSERT de la fila
|
|
38
|
+
* `id=1` dentro de `withAuthzCatalogWrite` —que sube la versión compartida como
|
|
39
|
+
* última sentencia (invariante 14): un sync en otro proceso la ve en la
|
|
40
|
+
* siguiente pregunta—. Devuelve la config congelada.
|
|
41
|
+
*/
|
|
42
|
+
export async function saveRelationsConfig(spec, options = {}) {
|
|
43
|
+
// Valida ANTES de escribir: una config inválida no ensucia la tabla.
|
|
44
|
+
const config = defineRelationsConfig(spec);
|
|
45
|
+
const json = JSON.stringify(spec);
|
|
46
|
+
await withAuthzCatalogWrite(async (trx) => {
|
|
47
|
+
const existing = await trx.from(TABLE).where('id', ROW_ID).first();
|
|
48
|
+
if (existing) {
|
|
49
|
+
await trx.from(TABLE).where('id', ROW_ID).update({ spec: json, updated_at: systemClock() });
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
await trx.table(TABLE).insert({ id: ROW_ID, spec: json, model_id: null, updated_at: systemClock() });
|
|
53
|
+
}
|
|
54
|
+
}, options);
|
|
55
|
+
invalidateAuthzCatalog();
|
|
56
|
+
return config;
|
|
57
|
+
}
|
|
58
|
+
/** Lee el spec persistido (o `null` si no hay relaciones declaradas — opt-in). */
|
|
59
|
+
export async function readRelationsConfigSpec(options = {}) {
|
|
60
|
+
const row = await guardSql('relations-config', 'read', options.timeoutMs ?? DEFAULT_TIMEOUT_MS, () => connectionOf(options).from(TABLE).where('id', ROW_ID).first());
|
|
61
|
+
if (!row?.spec)
|
|
62
|
+
return null;
|
|
63
|
+
return JSON.parse(String(row.spec));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Lee la config persistida ya VALIDADA (o `null`). Es lo que hace 🟡3: un
|
|
67
|
+
* proceso SIN `defineRelationsConfig` en memoria recupera aquí los tipos de
|
|
68
|
+
* relación de la base, así que el modelo que republique los lleva.
|
|
69
|
+
*/
|
|
70
|
+
export async function readRelationsConfig(options = {}) {
|
|
71
|
+
const spec = await readRelationsConfigSpec(options);
|
|
72
|
+
return spec ? defineRelationsConfig(spec) : null;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=relations_config_store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relations_config_store.js","sourceRoot":"","sources":["../../src/relations_config_store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACpD,OAAO,EAAE,MAAM,6BAA6B,CAAA;AAC5C,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AAC1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAA;AAG9E,MAAM,KAAK,GAAG,wBAAwB,CAAA;AACtC,MAAM,MAAM,GAAG,CAAC,CAAA;AAChB,MAAM,kBAAkB,GAAG,KAAK,CAAA;AAOhC,SAAS,YAAY,CAAC,OAAqC;IACzD,OAAO,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AACrE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,IAAyB,EACzB,UAAuC,EAAE;IAEzC,qEAAqE;IACrE,MAAM,MAAM,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAA;IAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;IACjC,MAAM,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACxC,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,EAAE,CAAA;QAClE,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE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2d; panel 2, cruce 4 · S5).
|
|
3
|
+
*
|
|
4
|
+
* El puerto es `ScopeOutbox` (`src/types.ts`) y el paquete NO impone tabla:
|
|
5
|
+
* cualquier implementación vale. Esta es la que se publica para quien no
|
|
6
|
+
* quiera escribir la suya, junto con su migración
|
|
7
|
+
* (`stubs/scopes_outbox_migration.stub`, que hay que COPIAR al proyecto:
|
|
8
|
+
* `configure` no la publica sola porque la outbox es opt-in).
|
|
9
|
+
*
|
|
10
|
+
* import { sqlScopeOutbox } from '@jantstack/adonis-authz'
|
|
11
|
+
*
|
|
12
|
+
* const outbox = sqlScopeOutbox()
|
|
13
|
+
* export default defineConfig({
|
|
14
|
+
* scopes: { resolveChain, outbox },
|
|
15
|
+
* ...
|
|
16
|
+
* })
|
|
17
|
+
*
|
|
18
|
+
* // y en el sitio donde mueves tu árbol:
|
|
19
|
+
* await db.transaction(async (trx) => {
|
|
20
|
+
* await authorization.scopes.moved(unit, nuevaOrg, { within, actor, transaction: trx })
|
|
21
|
+
* await unit.useTransaction(trx).merge({ organizationId: nuevaOrg.uuid }).save()
|
|
22
|
+
* })
|
|
23
|
+
*
|
|
24
|
+
* Lo único que tiene que cumplir una implementación del puerto es que
|
|
25
|
+
* `enqueue` escriba DENTRO de la transacción que le pasan: es lo que hace
|
|
26
|
+
* que el cambio del árbol y su propagación al backend confirmen —o se vayan—
|
|
27
|
+
* juntos. Todo lo demás (nombres de columna, si las filas aplicadas se
|
|
28
|
+
* borran o se marcan, si hay reintento con backoff) es del consumidor.
|
|
29
|
+
*
|
|
30
|
+
* Aquí las filas aplicadas se MARCAN (`applied_at`), no se borran: la cola
|
|
31
|
+
* es también el registro de lo que se propagó y cuándo, y `authz:scopes:relay`
|
|
32
|
+
* no puede ser silencioso.
|
|
33
|
+
*/
|
|
34
|
+
import type { Clock } from './clock.js';
|
|
35
|
+
import type { ScopeOutbox } from './types.js';
|
|
36
|
+
export interface SqlScopeOutboxOptions {
|
|
37
|
+
/** Tabla de la cola (default `authz_scope_outbox`, la del stub). */
|
|
38
|
+
table?: string;
|
|
39
|
+
/** Nombre de la conexión Lucid (default: la primaria). */
|
|
40
|
+
connection?: string;
|
|
41
|
+
/** Deadline de cada consulta en ms (default 5000): vencido ⇒ 503. */
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
/**
|
|
44
|
+
* Reloj de pared con el que se sellan `created_at` y `applied_at`
|
|
45
|
+
* (2.5 · J1). Default `() => new Date()`; inyectable para fijar el
|
|
46
|
+
* instante en tests.
|
|
47
|
+
*/
|
|
48
|
+
now?: Clock;
|
|
49
|
+
/**
|
|
50
|
+
* **Cuántas veces se reintenta una entrada antes de APARCARLA** (3b-2h ·
|
|
51
|
+
* 🔴 2; default 5). Alcanzado el tope, `pending()` deja de ofrecerla y sale
|
|
52
|
+
* por `dead()`: hay entradas que no se pueden aplicar NUNCA —el scope padre
|
|
53
|
+
* del `attached` encolado lo borró el tenant antes del relevo y no va a
|
|
54
|
+
* volver— y sin tope esa fila se reintenta en todas las pasadas para
|
|
55
|
+
* siempre. Aparcar no es olvidar: el relay la reporta en cada pasada y el
|
|
56
|
+
* comando sale ≠ 0 mientras haya alguna, porque el árbol del backend queda
|
|
57
|
+
* permanentemente divergente en ese nodo (lo reconcilia `authz:reconcile`,
|
|
58
|
+
* 3b-3, o un `scopes.detached`/`attached` nuevo del consumidor).
|
|
59
|
+
*/
|
|
60
|
+
maxAttempts?: number;
|
|
61
|
+
}
|
|
62
|
+
/** Lo que se necesita del `db` de Lucid; inyectable para probar sin servidor. */
|
|
63
|
+
interface DatabaseLike {
|
|
64
|
+
from(table: string): any;
|
|
65
|
+
table(table: string): any;
|
|
66
|
+
}
|
|
67
|
+
export declare function sqlScopeOutbox(options?: SqlScopeOutboxOptions, database?: DatabaseLike): ScopeOutbox;
|
|
68
|
+
export {};
|
|
69
|
+
//# sourceMappingURL=scope_outbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope_outbox.d.ts","sourceRoot":"","sources":["../../src/scope_outbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAKH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAKvC,OAAO,KAAK,EAEV,WAAW,EAKZ,MAAM,YAAY,CAAA;AAEnB,MAAM,WAAW,qBAAqB;IACpC,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;;OAIG;IACH,GAAG,CAAC,EAAE,KAAK,CAAA;IACX;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAgBD,iFAAiF;AACjF,UAAU,YAAY;IACpB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAA;IACxB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAA;CAC1B;AAuFD,wBAAgB,cAAc,CAC5B,OAAO,GAAE,qBAA0B,EACnC,QAAQ,GAAE,YAA4C,GACrD,WAAW,CAsLb"}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **La outbox del árbol sobre Lucid** (3b-2d; panel 2, cruce 4 · S5).
|
|
3
|
+
*
|
|
4
|
+
* El puerto es `ScopeOutbox` (`src/types.ts`) y el paquete NO impone tabla:
|
|
5
|
+
* cualquier implementación vale. Esta es la que se publica para quien no
|
|
6
|
+
* quiera escribir la suya, junto con su migración
|
|
7
|
+
* (`stubs/scopes_outbox_migration.stub`, que hay que COPIAR al proyecto:
|
|
8
|
+
* `configure` no la publica sola porque la outbox es opt-in).
|
|
9
|
+
*
|
|
10
|
+
* import { sqlScopeOutbox } from '@jantstack/adonis-authz'
|
|
11
|
+
*
|
|
12
|
+
* const outbox = sqlScopeOutbox()
|
|
13
|
+
* export default defineConfig({
|
|
14
|
+
* scopes: { resolveChain, outbox },
|
|
15
|
+
* ...
|
|
16
|
+
* })
|
|
17
|
+
*
|
|
18
|
+
* // y en el sitio donde mueves tu árbol:
|
|
19
|
+
* await db.transaction(async (trx) => {
|
|
20
|
+
* await authorization.scopes.moved(unit, nuevaOrg, { within, actor, transaction: trx })
|
|
21
|
+
* await unit.useTransaction(trx).merge({ organizationId: nuevaOrg.uuid }).save()
|
|
22
|
+
* })
|
|
23
|
+
*
|
|
24
|
+
* Lo único que tiene que cumplir una implementación del puerto es que
|
|
25
|
+
* `enqueue` escriba DENTRO de la transacción que le pasan: es lo que hace
|
|
26
|
+
* que el cambio del árbol y su propagación al backend confirmen —o se vayan—
|
|
27
|
+
* juntos. Todo lo demás (nombres de columna, si las filas aplicadas se
|
|
28
|
+
* borran o se marcan, si hay reintento con backoff) es del consumidor.
|
|
29
|
+
*
|
|
30
|
+
* Aquí las filas aplicadas se MARCAN (`applied_at`), no se borran: la cola
|
|
31
|
+
* es también el registro de lo que se propagó y cuándo, y `authz:scopes:relay`
|
|
32
|
+
* no puede ser silencioso.
|
|
33
|
+
*/
|
|
34
|
+
import db from '@adonisjs/lucid/services/db';
|
|
35
|
+
import { AuthorizationConfigError } from './errors.js';
|
|
36
|
+
import { systemClock } from './clock.js';
|
|
37
|
+
import { assertScope, assertSubject } from './identity.js';
|
|
38
|
+
import { guardSql } from './shared/backend_guard.js';
|
|
39
|
+
import { dialectOf, isSqliteDialect } from './shared/sql_expiry.js';
|
|
40
|
+
import { APP_SCOPE, APP_SCOPE_TYPE } from './types.js';
|
|
41
|
+
const DEFAULT_TABLE = 'authz_scope_outbox';
|
|
42
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
43
|
+
/** Intentos antes de aparcar una entrada (3b-2h · 🔴 2). */
|
|
44
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
45
|
+
/**
|
|
46
|
+
* Leases tomados por ESTE proceso (SQLite y cualquier dialecto sin cerrojo de
|
|
47
|
+
* sesión): la exclusión es entonces de proceso, no de despliegue, y va escrita
|
|
48
|
+
* en el README. Con PostgreSQL y MySQL el cerrojo es del servidor.
|
|
49
|
+
*/
|
|
50
|
+
const localLeases = new Set();
|
|
51
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
52
|
+
/** Las tres operaciones del árbol, tal como se guardan en la columna `op`. */
|
|
53
|
+
const OPS = ['attached', 'moved', 'detached'];
|
|
54
|
+
/** El scope que va a la fila: la raíz se guarda como `app` con uuid nulo. */
|
|
55
|
+
function columnsOf(scope) {
|
|
56
|
+
return { type: scope.type, uuid: scope.type === APP_SCOPE_TYPE ? null : scope.uuid };
|
|
57
|
+
}
|
|
58
|
+
/** La vuelta: `app` sin uuid es `APP_SCOPE`; el resto, la fila tal cual. */
|
|
59
|
+
function scopeOf(type, uuid) {
|
|
60
|
+
return type === APP_SCOPE_TYPE ? APP_SCOPE : { type, uuid: uuid === null ? null : String(uuid) };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Valida el cambio ANTES del INSERT (422): una cola es un diferido, y un
|
|
64
|
+
* `ScopeRef` mal formado que entrara aquí explotaría días después dentro del
|
|
65
|
+
* relay, lejos del call-site que lo escribió.
|
|
66
|
+
*/
|
|
67
|
+
function assertChange(change) {
|
|
68
|
+
if (!change || !OPS.includes(change.op)) {
|
|
69
|
+
throw new AuthorizationConfigError(`sqlScopeOutbox: 'op' debe ser uno de ${OPS.join(', ')} (llegó ${String(change?.op)})`);
|
|
70
|
+
}
|
|
71
|
+
assertScope(change.child);
|
|
72
|
+
if (change.op !== 'detached')
|
|
73
|
+
assertScope(change.parent);
|
|
74
|
+
}
|
|
75
|
+
/** Namespace de los advisory locks del paquete en PostgreSQL. */
|
|
76
|
+
const ADVISORY_LOCK_NAMESPACE = 0x617a;
|
|
77
|
+
/** Hash de 32 bits con signo (lo que acepta `pg_try_advisory_xact_lock`). */
|
|
78
|
+
function hash32(value) {
|
|
79
|
+
let hash = 0;
|
|
80
|
+
for (let i = 0; i < value.length; i++)
|
|
81
|
+
hash = (Math.imul(hash, 31) + value.charCodeAt(i)) | 0;
|
|
82
|
+
return hash;
|
|
83
|
+
}
|
|
84
|
+
/** El primer valor de un `rawQuery`, sea cual sea la forma del dialecto. */
|
|
85
|
+
function firstValue(result, column) {
|
|
86
|
+
const rows = Array.isArray(result) ? result[0] : (result?.rows ?? result);
|
|
87
|
+
const row = Array.isArray(rows) ? rows[0] : rows;
|
|
88
|
+
return row?.[column];
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* El cliente con el que se toma el lease: la conexión con nombre, la primaria
|
|
92
|
+
* del `db` de Lucid, o `null` si lo que se inyectó no es un cliente de Lucid
|
|
93
|
+
* (los dobles de test) — entonces el lease es de proceso.
|
|
94
|
+
*/
|
|
95
|
+
function lockClientOf(database, connection) {
|
|
96
|
+
if (connection)
|
|
97
|
+
return db.connection(connection);
|
|
98
|
+
const client = database;
|
|
99
|
+
if (typeof client?.transaction === 'function' && client?.dialect)
|
|
100
|
+
return client;
|
|
101
|
+
if (typeof client?.connection === 'function') {
|
|
102
|
+
const primary = client.connection();
|
|
103
|
+
return typeof primary?.transaction === 'function' ? primary : null;
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
/** Una fila de la cola, tal como la ve el puerto. */
|
|
108
|
+
function rowToPending(row) {
|
|
109
|
+
const child = scopeOf(String(row.child_type), row.child_uuid);
|
|
110
|
+
const change = row.op === 'detached'
|
|
111
|
+
? { op: 'detached', child }
|
|
112
|
+
: { op: row.op, child, parent: scopeOf(String(row.parent_type), row.parent_uuid) };
|
|
113
|
+
const actor = row.actor_type === null || row.actor_type === undefined
|
|
114
|
+
? undefined
|
|
115
|
+
: { type: String(row.actor_type), uuid: String(row.actor_uuid) };
|
|
116
|
+
return {
|
|
117
|
+
id: row.id,
|
|
118
|
+
change,
|
|
119
|
+
attempts: Number(row.attempts ?? 0),
|
|
120
|
+
actor,
|
|
121
|
+
...(row.last_error === null || row.last_error === undefined ? {} : { lastError: String(row.last_error) }),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** La cota de `pending`/`dead`: entera y positiva o 500 (config rota). */
|
|
125
|
+
function assertLimit(limit) {
|
|
126
|
+
if (!(Number.isInteger(limit) && limit >= 1)) {
|
|
127
|
+
throw new AuthorizationConfigError(`sqlScopeOutbox: limit debe ser un entero >= 1 (llegó ${String(limit)})`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export function sqlScopeOutbox(options = {}, database = db) {
|
|
131
|
+
const table = options.table ?? DEFAULT_TABLE;
|
|
132
|
+
if (!IDENTIFIER.test(table)) {
|
|
133
|
+
throw new AuthorizationConfigError(`sqlScopeOutbox: table '${table}' no es un identificador SQL simple (letras, dígitos y _).`);
|
|
134
|
+
}
|
|
135
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
136
|
+
const connection = options.connection;
|
|
137
|
+
const now = options.now ?? systemClock;
|
|
138
|
+
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
139
|
+
if (!(Number.isInteger(maxAttempts) && maxAttempts >= 1)) {
|
|
140
|
+
throw new AuthorizationConfigError(`sqlScopeOutbox: maxAttempts debe ser un entero >= 1 (llegó ${String(options.maxAttempts)})`);
|
|
141
|
+
}
|
|
142
|
+
/** El cliente de la consulta: la transacción del consumidor si la hay. */
|
|
143
|
+
const clientOf = (context) => {
|
|
144
|
+
const trx = context?.transaction;
|
|
145
|
+
if (trx === undefined || trx === null)
|
|
146
|
+
return database;
|
|
147
|
+
if (typeof trx.from !== 'function' || typeof trx.table !== 'function') {
|
|
148
|
+
throw new AuthorizationConfigError("sqlScopeOutbox: 'transaction' no parece un cliente de Lucid (le faltan .from()/.table()). " +
|
|
149
|
+
'Pasa el `trx` de db.transaction(); si tu outbox usa otra cosa, implementa el puerto a mano.');
|
|
150
|
+
}
|
|
151
|
+
return trx;
|
|
152
|
+
};
|
|
153
|
+
const query = (operation, run) => guardSql('sqlScopeOutbox', operation, timeoutMs, run);
|
|
154
|
+
/** Igual que el resto del paquete: la conexión con nombre si se declaró. */
|
|
155
|
+
const on = (client) => (connection && client === database ? db.connection(connection) : client);
|
|
156
|
+
return {
|
|
157
|
+
async enqueue(change, context) {
|
|
158
|
+
assertChange(change);
|
|
159
|
+
if (context?.actor !== undefined)
|
|
160
|
+
assertSubject(context.actor);
|
|
161
|
+
const child = columnsOf(change.child);
|
|
162
|
+
const parent = change.op === 'detached' ? { type: null, uuid: null } : columnsOf(change.parent);
|
|
163
|
+
const client = on(clientOf(context));
|
|
164
|
+
await query('enqueue', () => client.table(table).insert({
|
|
165
|
+
op: change.op,
|
|
166
|
+
child_type: child.type,
|
|
167
|
+
child_uuid: child.uuid,
|
|
168
|
+
parent_type: parent.type,
|
|
169
|
+
parent_uuid: parent.uuid,
|
|
170
|
+
actor_type: context?.actor?.type ?? null,
|
|
171
|
+
actor_uuid: context?.actor?.uuid ?? null,
|
|
172
|
+
attempts: 0,
|
|
173
|
+
last_error: null,
|
|
174
|
+
created_at: now(),
|
|
175
|
+
applied_at: null,
|
|
176
|
+
}));
|
|
177
|
+
},
|
|
178
|
+
async pending(limit, after) {
|
|
179
|
+
assertLimit(limit);
|
|
180
|
+
const client = on(database);
|
|
181
|
+
const rows = await query('pending', () => {
|
|
182
|
+
// Lo APARCADO (`attempts >= maxAttempts`) sale por `dead()`, no por
|
|
183
|
+
// aquí: si volviera, la pasada la reintentaría eternamente.
|
|
184
|
+
const q = client
|
|
185
|
+
.from(table)
|
|
186
|
+
.whereNull('applied_at')
|
|
187
|
+
.where('attempts', '<', maxAttempts)
|
|
188
|
+
.orderBy('id', 'asc')
|
|
189
|
+
.limit(limit);
|
|
190
|
+
// `after` es el último id que el relay ya vio EN ESTA PASADA: lo que
|
|
191
|
+
// dejó sin aplicar sigue pendiente y sin esto volvería a salir el
|
|
192
|
+
// primero para siempre (3b-2h · 🔴 2).
|
|
193
|
+
return after === undefined ? q : q.where('id', '>', after);
|
|
194
|
+
});
|
|
195
|
+
return rows.map(rowToPending);
|
|
196
|
+
},
|
|
197
|
+
/**
|
|
198
|
+
* Las entradas APARCADAS: pendientes que agotaron sus intentos. No se
|
|
199
|
+
* reintentan, se MIRAN (3b-2h · 🔴 2).
|
|
200
|
+
*/
|
|
201
|
+
async dead(limit) {
|
|
202
|
+
assertLimit(limit);
|
|
203
|
+
const client = on(database);
|
|
204
|
+
const rows = await query('dead', () => client
|
|
205
|
+
.from(table)
|
|
206
|
+
.whereNull('applied_at')
|
|
207
|
+
.where('attempts', '>=', maxAttempts)
|
|
208
|
+
.orderBy('id', 'asc')
|
|
209
|
+
.limit(limit));
|
|
210
|
+
return rows.map(rowToPending);
|
|
211
|
+
},
|
|
212
|
+
/**
|
|
213
|
+
* **El lease del escritor ÚNICO** (3b-2h · 🟠 4). Cerrojo del SERVIDOR en
|
|
214
|
+
* PostgreSQL (`pg_try_advisory_xact_lock`, que se suelta con la
|
|
215
|
+
* transacción) y en MySQL (`GET_LOCK(name, 0)`); en SQLite —y en
|
|
216
|
+
* cualquier dialecto sin cerrojo de sesión— es un cerrojo de PROCESO, y
|
|
217
|
+
* eso está escrito: SQLite ya serializa sus escrituras y no es el motor
|
|
218
|
+
* de un despliegue con dos réplicas del relay.
|
|
219
|
+
*
|
|
220
|
+
* La transacción se abre SOLO para sostener el cerrojo (no escribe nada)
|
|
221
|
+
* y se revierte al soltarlo: es una conexión ocupada mientras dura la
|
|
222
|
+
* pasada, que es el precio de que dos pasadas no se pisen.
|
|
223
|
+
*/
|
|
224
|
+
async acquire() {
|
|
225
|
+
const name = `authz_scope_outbox:${connection ?? 'default'}:${table}`;
|
|
226
|
+
const client = lockClientOf(database, connection);
|
|
227
|
+
if (client === null || isSqliteDialect(client)) {
|
|
228
|
+
if (localLeases.has(name))
|
|
229
|
+
return null;
|
|
230
|
+
localLeases.add(name);
|
|
231
|
+
return { release: async () => void localLeases.delete(name) };
|
|
232
|
+
}
|
|
233
|
+
const dialect = dialectOf(client);
|
|
234
|
+
const trx = await query('acquire', () => client.transaction());
|
|
235
|
+
try {
|
|
236
|
+
if (dialect.startsWith('postgres')) {
|
|
237
|
+
const result = await query('acquire', () => trx.rawQuery('select pg_try_advisory_xact_lock(?, ?) as taken', [ADVISORY_LOCK_NAMESPACE, hash32(name)]));
|
|
238
|
+
if (!firstValue(result, 'taken')) {
|
|
239
|
+
await trx.rollback();
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
// El cerrojo es de la TRANSACCIÓN: revertirla lo suelta.
|
|
243
|
+
return { release: async () => void (await trx.rollback()) };
|
|
244
|
+
}
|
|
245
|
+
if (dialect.startsWith('mysql')) {
|
|
246
|
+
const result = await query('acquire', () => trx.rawQuery('select get_lock(?, 0) as taken', [name.slice(0, 64)]));
|
|
247
|
+
if (Number(firstValue(result, 'taken') ?? 0) !== 1) {
|
|
248
|
+
await trx.rollback();
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
release: async () => {
|
|
253
|
+
try {
|
|
254
|
+
await trx.rawQuery('select release_lock(?)', [name.slice(0, 64)]);
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
await trx.rollback();
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
// Un dialecto que no sabemos cerrar: se cierra en el proceso y se
|
|
263
|
+
// suelta la transacción (nunca se devuelve un lease de mentira).
|
|
264
|
+
await trx.rollback();
|
|
265
|
+
if (localLeases.has(name))
|
|
266
|
+
return null;
|
|
267
|
+
localLeases.add(name);
|
|
268
|
+
return { release: async () => void localLeases.delete(name) };
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
await trx.rollback().catch(() => { });
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
async markApplied(id) {
|
|
276
|
+
const client = on(database);
|
|
277
|
+
await query('markApplied', () => client.from(table).where('id', id).update({ applied_at: now(), last_error: null }));
|
|
278
|
+
},
|
|
279
|
+
async markFailed(id, error) {
|
|
280
|
+
const client = on(database);
|
|
281
|
+
// El intento se cuenta aunque el mensaje sea larguísimo: se recorta el
|
|
282
|
+
// texto, nunca el hecho de que falló.
|
|
283
|
+
await query('markFailed', () => client
|
|
284
|
+
.from(table)
|
|
285
|
+
.where('id', id)
|
|
286
|
+
.update({ last_error: String(error).slice(0, 2000) })
|
|
287
|
+
.increment('attempts', 1));
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
//# sourceMappingURL=scope_outbox.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope_outbox.js","sourceRoot":"","sources":["../../src/scope_outbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,MAAM,6BAA6B,CAAA;AAC5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAExC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACpD,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAqCtD,MAAM,aAAa,GAAG,oBAAoB,CAAA;AAC1C,MAAM,kBAAkB,GAAG,KAAK,CAAA;AAChC,4DAA4D;AAC5D,MAAM,oBAAoB,GAAG,CAAC,CAAA;AAC9B;;;;GAIG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAA;AACrC,MAAM,UAAU,GAAG,0BAA0B,CAAA;AAC7C,8EAA8E;AAC9E,MAAM,GAAG,GAAG,CAAC,U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b,CAAC;QACH,CAAC;QAED,KAAK,CAAC,WAAW,CAAC,EAAmB;YACnC,MAAM,MAAM,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAA;YAC3B,MAAM,KAAK,CAAC,aAAa,EAAE,GAAG,EAAE,CAC9B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CACnF,CAAA;QACH,CAAC;QAED,KAAK,CAAC,UAAU,CAAC,EAAmB,EAAE,KAAa;YACjD,MAAM,MAAM,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAA;YAC3B,uEAAuE;YACvE,sCAAsC;YACtC,MAAM,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,CAC7B,MAAM;iBACH,IAAI,CAAC,KAAK,CAAC;iBACX,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;iBACf,MAAM,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,CAAC;iBACpD,SAAS,CAAC,UAAU,EAAE,CAAC,CAAC,CAC5B,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { ScopeChainResolver, ScopeRef } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Clasificación de fallos de dependencias, compartida por ambos drivers.
|
|
4
|
+
*
|
|
5
|
+
* Tres dependencias participan en una pregunta: el catálogo (SQL, en ambos
|
|
6
|
+
* drivers), el árbol del consumidor (`resolveChain`) y el backend de
|
|
7
|
+
* hechos (SQL o FGA). Las tres se clasifican igual: 503 con código propio,
|
|
8
|
+
* la causa original conservada, y NUNCA un `false` ni un error crudo — el
|
|
9
|
+
* invariante 5 tal como está publicado (L0.11, N3).
|
|
10
|
+
*
|
|
11
|
+
* Lo que ya es un error del paquete (422 de catálogo, 500 de programación)
|
|
12
|
+
* pasa intacto: un rol inexistente no es una caída.
|
|
13
|
+
*/
|
|
14
|
+
/** ¿Es un error que este paquete ya clasificó (tiene `code` E_AUTHZ_*)? */
|
|
15
|
+
export declare function isAuthzError(error: unknown): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* ¿Es un error del CLIENTE SQL (pg, mysql2, better-sqlite3, knex) y no del
|
|
18
|
+
* código del consumidor? Por la forma que cada cliente da a sus errores:
|
|
19
|
+
* `pg` un `DatabaseError` con SQLSTATE de 5 caracteres (`25P02`…) y
|
|
20
|
+
* `severity`; `mysql2` un `errno` numérico con `sqlState`; SQLite un `code`
|
|
21
|
+
* `SQLITE_*`; knex un `KnexTimeoutError`. Sirve para clasificar (503) lo que
|
|
22
|
+
* un `fn` del consumidor deja escapar desde dentro de una transacción
|
|
23
|
+
* (2.5-B · K12): un error crudo del cliente nunca cruza la frontera.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isSqlDriverError(error: unknown): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* ¿El error viene de un deadline vencido? knex lanza `KnexTimeoutError` (o, si
|
|
28
|
+
* además falló la cancelación, el error de cancelación con `timeout` puesto);
|
|
29
|
+
* axios usa `ECONNABORTED`/`ETIMEDOUT`, a veces envuelto por el SDK como
|
|
30
|
+
* `cause`. Se mira la cadena entera de causas.
|
|
31
|
+
*/
|
|
32
|
+
export declare function isTimeoutLike(error: unknown): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Ejecuta una consulta SQL con deadline y traduce su fallo. El builder de
|
|
35
|
+
* Lucid es perezoso (se ejecuta al hacer `await`), así que el `timeout` se
|
|
36
|
+
* fija aquí, en el ÚNICO punto por el que pasan todas las consultas: un
|
|
37
|
+
* call-site nuevo lo hereda sin saberlo. `cancel: true` pide a knex que
|
|
38
|
+
* cancele la consulta en el servidor cuando el dialecto lo permite.
|
|
39
|
+
*/
|
|
40
|
+
export declare function guardSql<T>(driver: string, operation: string, timeoutMs: number, fn: () => Promise<T>): Promise<T>;
|
|
41
|
+
/**
|
|
42
|
+
* Deadline TOTAL de una llamada al backend: vencido ⇒ rechaza con el error
|
|
43
|
+
* que fabrique `onTimeout`. El timer no retiene el event loop y se limpia al
|
|
44
|
+
* resolver. La promesa original sigue su curso —la petición en vuelo puede
|
|
45
|
+
* aterrizar después— pero el llamante ya fue liberado: por eso el manager
|
|
46
|
+
* notifica `indeterminate: true` en las escrituras que vencen (D2) y el
|
|
47
|
+
* driver openfga no deja al SDK reintentar por su cuenta (`maxRetry: 0`).
|
|
48
|
+
*/
|
|
49
|
+
export declare function withDeadline<T>(promise: Promise<T>, ms: number, onTimeout: () => Error): Promise<T>;
|
|
50
|
+
/**
|
|
51
|
+
* El resolutor que usa un driver construido SIN `resolveChain`: solo
|
|
52
|
+
* conoce la raíz. Sustituye al default plano de 1.x (`resto → [APP_SCOPE]`),
|
|
53
|
+
* que hacía descender de `app` cualquier scope inventado o borrado (L0.3).
|
|
54
|
+
* No se lanza al construir el driver, sino en la primera pregunta por un
|
|
55
|
+
* scope intermedio: un despliegue que solo usa `app` es legítimo sin árbol.
|
|
56
|
+
*/
|
|
57
|
+
export declare const rootOnlyResolver: ScopeChainResolver;
|
|
58
|
+
/**
|
|
59
|
+
* Cadena CANÓNICA `[scope canónico, ...ancestros]` con el resolutor del
|
|
60
|
+
* consumidor envuelto (2.5-B · K1): el elemento 0 es el scope tal como está
|
|
61
|
+
* en la tabla del consumidor —no tal como lo escribió el llamante—, y es la
|
|
62
|
+
* identidad con la que el paquete lee y escribe TODOS los hechos. Antes se
|
|
63
|
+
* devolvía `[scope del llamante, ...ancestros]`: un alias del uuid (que el
|
|
64
|
+
* árbol fundía con la fila real) resolvía la cadena entera y el grant del
|
|
65
|
+
* ancestro aplicaba, pero el deny —escrito con la forma canónica— no casaba.
|
|
66
|
+
*
|
|
67
|
+
* Si el resolutor lanza, sale como `ScopeResolverError` (503): el árbol es
|
|
68
|
+
* una dependencia más y su caída no es un bug del paquete ni un "sin
|
|
69
|
+
* permiso". `null` = el scope no existe para el consumidor; el llamante decide
|
|
70
|
+
* qué significa (denegar en lectura, 422 en escritura). La raíz no se
|
|
71
|
+
* pregunta: el motor la conoce y su cadena es `[APP_SCOPE]` por definición.
|
|
72
|
+
*
|
|
73
|
+
* La RESPUESTA se valida (D13 + K1): no-array, elemento mal formado
|
|
74
|
+
* (`{app, 'X'}`, `{organization, 'a|b'}`), cadena vacía, o un elemento 0 que
|
|
75
|
+
* no es el scope pedido (otro tipo; un uuid que no es el mismo id salvo
|
|
76
|
+
* mayúsculas/guiones) ⇒ 503 con el motivo como causa. Nunca se acepta en
|
|
77
|
+
* silencio una identidad que el llamante no pidió.
|
|
78
|
+
*/
|
|
79
|
+
export declare function resolveChain(resolver: ScopeChainResolver, scope: ScopeRef, operation: string): Promise<ScopeRef[] | null>;
|
|
80
|
+
/**
|
|
81
|
+
* El scope CANÓNICO para una escritura que no exige que exista (`revoke`,
|
|
82
|
+
* `removeDeny`, `purgeScope`): la fila del árbol si lo conoce (un alias se
|
|
83
|
+
* canoniza y el hecho canónico se encuentra, K1); el scope tal cual si ya no
|
|
84
|
+
* lo conoce (un hecho de un scope borrado sin avisar, D8, sigue siendo
|
|
85
|
+
* alcanzable con su identidad exacta) o si el driver no tiene resolutor (solo
|
|
86
|
+
* existe la raíz: no hay nada con lo que canonizar). Un resolutor que LANZA
|
|
87
|
+
* sigue siendo 503: no se limpia a ciegas cuando el árbol está caído.
|
|
88
|
+
*/
|
|
89
|
+
export declare function canonicalScope(resolver: ScopeChainResolver, scope: ScopeRef, operation: string): Promise<ScopeRef>;
|
|
90
|
+
/**
|
|
91
|
+
* **Los scopes destino de un DELETE que no exige que el scope exista**
|
|
92
|
+
* (`revoke`/`removeDeny`; 3b-8 · A4, mismo cierre que 3b-2h · 🟠 3 dio a
|
|
93
|
+
* `scopes.detached`). Con la fila viva es exactamente UNO, el canónico
|
|
94
|
+
* (`chain[0]`). Sin cadena con la que canonizar —la fila ya borrada, o sin
|
|
95
|
+
* resolutor— la ortografía del llamante a secas hacía del delete un no-op
|
|
96
|
+
* SILENCIOSO cuando llegaba un alias del uuid (el mismo uuid sin guiones,
|
|
97
|
+
* que el tipo `uuid` de PG o una collation `*_ci` funden con la fila real):
|
|
98
|
+
* el hecho canónico seguía escrito y volvía a conceder si el scope se
|
|
99
|
+
* restauraba. Se reusa el fan-out de `scopeSpellings`: la ortografía del
|
|
100
|
+
* llamante Y la canónica de la que puede ser alias. Quitar nunca concede,
|
|
101
|
+
* así que borrar de más no existe aquí.
|
|
102
|
+
*/
|
|
103
|
+
export declare function canonicalScopeTargets(resolver: ScopeChainResolver, scope: ScopeRef, operation: string): Promise<ScopeRef[]>;
|
|
104
|
+
/** La cadena canónica, o 422 `E_AUTHZ_UNKNOWN_SCOPE` si el scope no existe (para escrituras). */
|
|
105
|
+
export declare function assertKnownScope(resolver: ScopeChainResolver, scope: ScopeRef, operation: string): Promise<ScopeRef[]>;
|
|
106
|
+
//# sourceMappingURL=backend_guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend_guard.d.ts","sourceRoot":"","sources":["../../../src/shared/backend_guard.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAI/D;;;;;;;;;;;GAWG;AAEH,2EAA2E;AAC3E,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAEpD;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAQxD;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAQrD;AAED;;;;;;GAMG;AACH,wBAAsB,QAAQ,CAAC,CAAC,EAC9B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM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