@designerbyron/lifecode-rag 0.0.0-stage → 1.0.0
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 +21 -0
- package/README.md +191 -2
- package/bin/lifecode-rag.mjs +449 -0
- package/client.js +2801 -0
- package/cordis.patch.yml +3 -0
- package/docs/ARCHITECTURE-v0.2.md +269 -0
- package/docs/AUTO-DISCOVERY.md +111 -0
- package/docs/AUTOMATION-POLICIES.md +232 -0
- package/docs/CONTRATO-v0.1.md +195 -0
- package/docs/EMBEDDING-PROVIDERS.md +105 -0
- package/docs/OBSERVABILITY.md +241 -0
- package/docs/PA-UI-0-API-CONTRACT.md +802 -0
- package/docs/PERFORMANCE-BUDGETS.md +118 -0
- package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
- package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
- package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
- package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
- package/docs/WORKSPACE-API.md +239 -0
- package/icon.svg +7 -0
- package/index.js +198 -0
- package/lib/audit-export.mjs +70 -0
- package/lib/audit.mjs +120 -0
- package/lib/auto-context.mjs +322 -0
- package/lib/automation.mjs +214 -0
- package/lib/chunk.mjs +100 -0
- package/lib/config-resolve.mjs +119 -0
- package/lib/context.mjs +150 -0
- package/lib/conversation-events.mjs +145 -0
- package/lib/db.mjs +309 -0
- package/lib/diagnose.mjs +197 -0
- package/lib/discovery.mjs +402 -0
- package/lib/doctor.mjs +82 -0
- package/lib/embed.mjs +96 -0
- package/lib/embedders.mjs +103 -0
- package/lib/errors.mjs +227 -0
- package/lib/exec-context.mjs +238 -0
- package/lib/extract.mjs +260 -0
- package/lib/harness-workspaces.mjs +85 -0
- package/lib/hash.mjs +34 -0
- package/lib/ingest.mjs +239 -0
- package/lib/inputs.mjs +67 -0
- package/lib/library-state.mjs +252 -0
- package/lib/maintenance.mjs +113 -0
- package/lib/metrics.mjs +164 -0
- package/lib/migrate.mjs +373 -0
- package/lib/operations.mjs +132 -0
- package/lib/pa-api.mjs +517 -0
- package/lib/paths.mjs +345 -0
- package/lib/policy.mjs +125 -0
- package/lib/profile.mjs +128 -0
- package/lib/readmodel.mjs +159 -0
- package/lib/recovery.mjs +557 -0
- package/lib/registry-schema.mjs +206 -0
- package/lib/registry.mjs +406 -0
- package/lib/resolve.mjs +311 -0
- package/lib/retention.mjs +143 -0
- package/lib/revocation.mjs +124 -0
- package/lib/roots-structure.mjs +224 -0
- package/lib/schema.mjs +173 -0
- package/lib/scope-ops.mjs +379 -0
- package/lib/scope-stores.mjs +128 -0
- package/lib/search.mjs +345 -0
- package/lib/selection.mjs +150 -0
- package/lib/server.mjs +335 -0
- package/lib/session-identity.mjs +51 -0
- package/lib/sessions.mjs +343 -0
- package/lib/sync-scheduler.mjs +354 -0
- package/lib/sync.mjs +755 -0
- package/lib/tags.mjs +45 -0
- package/lib/tools.mjs +364 -0
- package/lib/trusted-roots.mjs +149 -0
- package/lib/worker-context.mjs +22 -0
- package/package.json +67 -5
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errores del núcleo de LifeCode RAG.
|
|
3
|
+
*
|
|
4
|
+
* Todo fallo esperable se lanza como `RagError` con un `code` estable: el adaptador lo traduce a un
|
|
5
|
+
* resultado de herramienta con `isError: true` y un mensaje accionable, sin trazas ni rutas internas.
|
|
6
|
+
* Un error sin `code` es un defecto del programa, no una condición del almacén, y también se cierra.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Códigos públicos. Añadir uno es un cambio de contrato: va documentado y con prueba.
|
|
11
|
+
*
|
|
12
|
+
* Hasta ACP-02 esta lista se presentaba como cerrada pero le faltaban 18 códigos que el código lanza de
|
|
13
|
+
* verdad (entre ellos los de autorización); ahora está completa y `tests/error-codes.test.mjs` recorre el
|
|
14
|
+
* fuente para que no vuelva a desincronizarse.
|
|
15
|
+
*/
|
|
16
|
+
export const RAG_CODES = Object.freeze([
|
|
17
|
+
// entrada / validación
|
|
18
|
+
'invalid-argument',
|
|
19
|
+
'invalid-config',
|
|
20
|
+
'invalid-tag',
|
|
21
|
+
'sequence-conflict',
|
|
22
|
+
// almacén y esquema
|
|
23
|
+
'store-not-initialized',
|
|
24
|
+
'store-not-rag',
|
|
25
|
+
'store-version-unsupported',
|
|
26
|
+
'store-busy',
|
|
27
|
+
'store-corrupt',
|
|
28
|
+
'fts-integrity',
|
|
29
|
+
'vector-index-incomplete',
|
|
30
|
+
'recovery-verification-failed',
|
|
31
|
+
'operation-uncertain',
|
|
32
|
+
// fuentes y rutas
|
|
33
|
+
'source-not-found',
|
|
34
|
+
'source-unreadable',
|
|
35
|
+
'path-outside-root',
|
|
36
|
+
'path-denied',
|
|
37
|
+
'path-not-allowed',
|
|
38
|
+
'path-protected',
|
|
39
|
+
'path-unsupported',
|
|
40
|
+
'path-escape',
|
|
41
|
+
'hardlink-refused',
|
|
42
|
+
'root-symlink',
|
|
43
|
+
'root-changed',
|
|
44
|
+
'root-overlap',
|
|
45
|
+
'sync-root-unavailable',
|
|
46
|
+
// límites
|
|
47
|
+
'too-large',
|
|
48
|
+
'response-too-large',
|
|
49
|
+
'too-many-files',
|
|
50
|
+
'binary-file',
|
|
51
|
+
// aprobación y autorización
|
|
52
|
+
'approval-required',
|
|
53
|
+
'approval-unavailable',
|
|
54
|
+
'unauthenticated',
|
|
55
|
+
'forbidden',
|
|
56
|
+
'authorization-unavailable',
|
|
57
|
+
'session-invalid',
|
|
58
|
+
'session-expired',
|
|
59
|
+
'scope-forbidden',
|
|
60
|
+
'scope-unresolved',
|
|
61
|
+
'scope-ambiguous',
|
|
62
|
+
'scope-too-many',
|
|
63
|
+
'grant-revoked',
|
|
64
|
+
'project-not-authorized',
|
|
65
|
+
'revision-conflict',
|
|
66
|
+
// registro Project-Aware
|
|
67
|
+
'registry-corrupt',
|
|
68
|
+
'registry-unavailable',
|
|
69
|
+
'scope-store-corrupt',
|
|
70
|
+
'scope-store-unavailable',
|
|
71
|
+
// embeddings y red
|
|
72
|
+
'egress-denied',
|
|
73
|
+
'embedding-failed',
|
|
74
|
+
// control
|
|
75
|
+
'cancelled',
|
|
76
|
+
'internal',
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
/** Conjunto para consultas O(1) y para las pruebas de exhaustividad. */
|
|
80
|
+
export const RAG_CODE_SET = Object.freeze(new Set(RAG_CODES));
|
|
81
|
+
|
|
82
|
+
/** `true` si el código está en el catálogo público. */
|
|
83
|
+
export function isCataloguedCode(code) {
|
|
84
|
+
return RAG_CODE_SET.has(code);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Status HTTP de cada código. **Un solo mapa**: las dos APIs del plugin lo usan en vez de mantener su
|
|
89
|
+
* propia tabla, para que un código de seguridad no acabe en `500` por olvido.
|
|
90
|
+
*/
|
|
91
|
+
export const HTTP_STATUS = Object.freeze({
|
|
92
|
+
'invalid-argument': 400,
|
|
93
|
+
'invalid-config': 400,
|
|
94
|
+
'invalid-tag': 400,
|
|
95
|
+
'sequence-conflict': 409,
|
|
96
|
+
'store-not-initialized': 503,
|
|
97
|
+
'store-not-rag': 409,
|
|
98
|
+
'store-version-unsupported': 409,
|
|
99
|
+
'store-busy': 503,
|
|
100
|
+
'store-corrupt': 500,
|
|
101
|
+
'fts-integrity': 500,
|
|
102
|
+
'vector-index-incomplete': 500,
|
|
103
|
+
'recovery-verification-failed': 500,
|
|
104
|
+
'operation-uncertain': 409,
|
|
105
|
+
'source-not-found': 404,
|
|
106
|
+
'source-unreadable': 422,
|
|
107
|
+
'path-outside-root': 409,
|
|
108
|
+
'path-denied': 403,
|
|
109
|
+
'path-not-allowed': 403,
|
|
110
|
+
'path-protected': 403,
|
|
111
|
+
'path-unsupported': 415,
|
|
112
|
+
'path-escape': 403,
|
|
113
|
+
'hardlink-refused': 403,
|
|
114
|
+
'root-symlink': 409,
|
|
115
|
+
'root-changed': 409,
|
|
116
|
+
'root-overlap': 409,
|
|
117
|
+
'sync-root-unavailable': 503,
|
|
118
|
+
'too-large': 413,
|
|
119
|
+
'response-too-large': 500,
|
|
120
|
+
'too-many-files': 413,
|
|
121
|
+
'binary-file': 415,
|
|
122
|
+
'approval-required': 403,
|
|
123
|
+
'approval-unavailable': 503,
|
|
124
|
+
unauthenticated: 401,
|
|
125
|
+
forbidden: 403,
|
|
126
|
+
'authorization-unavailable': 503,
|
|
127
|
+
'session-invalid': 401,
|
|
128
|
+
'session-expired': 409,
|
|
129
|
+
'scope-forbidden': 403,
|
|
130
|
+
'scope-unresolved': 409,
|
|
131
|
+
'scope-ambiguous': 403,
|
|
132
|
+
'scope-too-many': 409,
|
|
133
|
+
'grant-revoked': 403,
|
|
134
|
+
'project-not-authorized': 403,
|
|
135
|
+
'revision-conflict': 409,
|
|
136
|
+
'registry-corrupt': 500,
|
|
137
|
+
'registry-unavailable': 503,
|
|
138
|
+
'scope-store-corrupt': 500,
|
|
139
|
+
'scope-store-unavailable': 503,
|
|
140
|
+
'egress-denied': 403,
|
|
141
|
+
'embedding-failed': 502,
|
|
142
|
+
cancelled: 499,
|
|
143
|
+
internal: 500,
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Diferencias documentadas de la API heredada v0.2 (`CONTRATO-v0.1.md`), que no se tocan aquí para no
|
|
148
|
+
* romper su contrato: `store-not-initialized` respondía 404 y la aprobación 409.
|
|
149
|
+
*/
|
|
150
|
+
export const LEGACY_HTTP_OVERRIDES = Object.freeze({
|
|
151
|
+
'store-not-initialized': 404,
|
|
152
|
+
'approval-required': 409,
|
|
153
|
+
'approval-unavailable': 409,
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
/** Status de un código; `500` sólo para lo no clasificado (nunca para un código de seguridad). */
|
|
157
|
+
export function httpStatusFor(code, { legacy = false } = {}) {
|
|
158
|
+
if (legacy && Object.prototype.hasOwnProperty.call(LEGACY_HTTP_OVERRIDES, code)) {
|
|
159
|
+
return LEGACY_HTTP_OVERRIDES[code];
|
|
160
|
+
}
|
|
161
|
+
return Object.prototype.hasOwnProperty.call(HTTP_STATUS, code) ? HTTP_STATUS[code] : 500;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Decisiones de autorización: un fallo de esta lista se responde con 4xx y **nunca** se degrada a 5xx
|
|
166
|
+
* (un 500 aquí es un fallo de clasificación, no «algo del servidor»).
|
|
167
|
+
*/
|
|
168
|
+
export const SECURITY_CODES = Object.freeze([
|
|
169
|
+
'approval-required',
|
|
170
|
+
'unauthenticated',
|
|
171
|
+
'forbidden',
|
|
172
|
+
'session-invalid',
|
|
173
|
+
'session-expired',
|
|
174
|
+
'scope-forbidden',
|
|
175
|
+
'scope-unresolved',
|
|
176
|
+
'scope-ambiguous',
|
|
177
|
+
'scope-too-many',
|
|
178
|
+
'grant-revoked',
|
|
179
|
+
'project-not-authorized',
|
|
180
|
+
'path-denied',
|
|
181
|
+
'path-not-allowed',
|
|
182
|
+
'path-protected',
|
|
183
|
+
'path-escape',
|
|
184
|
+
'hardlink-refused',
|
|
185
|
+
'egress-denied',
|
|
186
|
+
]);
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Cierres por falta de mecanismo, no por una decisión: el host no ofrece compuerta o aprobación, así que
|
|
190
|
+
* la operación se rechaza. Son `503` a propósito —el fallo es del servicio— pero nunca `2xx` ni un 4xx
|
|
191
|
+
* que se lea como error del usuario.
|
|
192
|
+
*/
|
|
193
|
+
export const FAIL_CLOSED_CODES = Object.freeze([
|
|
194
|
+
'approval-unavailable',
|
|
195
|
+
'authorization-unavailable',
|
|
196
|
+
]);
|
|
197
|
+
|
|
198
|
+
/** `true` si el código pertenece a la familia de autorización/seguridad (decisión o cierre). */
|
|
199
|
+
export function isSecurityCode(code) {
|
|
200
|
+
return SECURITY_CODES.includes(code) || FAIL_CLOSED_CODES.includes(code);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export class RagError extends Error {
|
|
204
|
+
/**
|
|
205
|
+
* @param {string} code uno de `RAG_CODES`
|
|
206
|
+
* @param {string} message mensaje accionable, sin datos sensibles
|
|
207
|
+
* @param {object} [options]
|
|
208
|
+
* @param {Record<string, unknown>} [options.details] datos mínimos para diagnosticar
|
|
209
|
+
* @param {Error} [options.cause]
|
|
210
|
+
*
|
|
211
|
+
* El código se conserva tal cual: un código no catalogado **no** se convierte en `internal` en
|
|
212
|
+
* silencio (eso degradaría un fallo de seguridad a genérico). `catalogued` lo deja visible y
|
|
213
|
+
* `tests/error-codes.test.mjs` impide que el fuente introduzca uno sin catalogarlo.
|
|
214
|
+
*/
|
|
215
|
+
constructor(code, message, { details = {}, cause } = {}) {
|
|
216
|
+
super(message, { cause });
|
|
217
|
+
this.name = 'RagError';
|
|
218
|
+
this.code = code;
|
|
219
|
+
this.details = details;
|
|
220
|
+
this.catalogued = isCataloguedCode(code);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** `true` si el error es una condición prevista del almacén, no un defecto del programa. */
|
|
225
|
+
export function isRagError(error) {
|
|
226
|
+
return error instanceof RagError;
|
|
227
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contexto de ejecución autorizado (PA3) con revocación efectiva (PA4-B).
|
|
3
|
+
*
|
|
4
|
+
* Toda herramienta pública pasa por aquí antes de tocar un almacén. El flujo es el del contrato:
|
|
5
|
+
*
|
|
6
|
+
* identidad del host → perfil → registro → selección/resolución → ámbitos efectivos → almacenes
|
|
7
|
+
*
|
|
8
|
+
* Si cualquier paso falla, la herramienta falla en cerrado: no hay proyecto por defecto, no hay
|
|
9
|
+
* búsqueda global de rescate y no se abre ningún almacén antes de resolver.
|
|
10
|
+
*
|
|
11
|
+
* PA4 añade puntos de control de autorización (`revalidate`): se comprueban antes de abrir un ámbito
|
|
12
|
+
* y otra vez antes de devolver información. Una revocación detectada a mitad de operación aborta la
|
|
13
|
+
* operación con `grant-revoked` y no se devuelve ningún resultado: el contrato v0.1 no tiene un campo
|
|
14
|
+
* público para decir «parcial», así que un conjunto reducido se leería como exhaustivo.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { RagError } from './errors.mjs';
|
|
18
|
+
import { appendRegistryAudit, closeRegistry, openRegistry } from './registry.mjs';
|
|
19
|
+
import { profileKey, profileRoot } from './profile.mjs';
|
|
20
|
+
import { captureSession } from './session-identity.mjs';
|
|
21
|
+
import { listOpenProjects } from './harness-workspaces.mjs';
|
|
22
|
+
import { resolveScope } from './resolve.mjs';
|
|
23
|
+
import { openScopeStore, scopeStoreExists, scopeStoreDir } from './scope-stores.mjs';
|
|
24
|
+
import { closeDatabase } from './db.mjs';
|
|
25
|
+
import { authorizationLostError, currentAuthorization, diffScopes, revocationError } from './revocation.mjs';
|
|
26
|
+
import { assertRootUnchanged } from './roots-structure.mjs';
|
|
27
|
+
|
|
28
|
+
function nowOf(services) {
|
|
29
|
+
return typeof services.now === 'function' ? services.now() : Date.now();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function cancelledError(where) {
|
|
33
|
+
return new RagError('cancelled', 'la operación se canceló', { details: { reason: 'signal-aborted', where } });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* El `cwd` sólo sirve para resolver; si el host no puede darlo, no se inventa. Una sesión con
|
|
38
|
+
* selección explícita sigue funcionando; sin selección el resultado será `scope-unresolved`.
|
|
39
|
+
*/
|
|
40
|
+
async function cwdOf(services, exec) {
|
|
41
|
+
const directory = services.workingDirectory;
|
|
42
|
+
if (!directory || typeof directory.ensure !== 'function') return null;
|
|
43
|
+
try {
|
|
44
|
+
return await directory.ensure(exec.agent, exec.signal);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// Una cancelación no es «no hay directorio»: se propaga para no confundir un turno abortado con
|
|
47
|
+
// un ámbito sin resolver (el host distingue `cancelled` de `scope-unresolved`).
|
|
48
|
+
if (exec.signal?.aborted) {
|
|
49
|
+
throw new RagError('cancelled', 'la operación se canceló mientras se resolvía el directorio', {
|
|
50
|
+
details: { reason: 'signal-aborted', where: 'cwd' },
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Ejecuta `work` con el contexto autorizado y cierra todo al terminar, incluso si `work` falla.
|
|
59
|
+
*
|
|
60
|
+
* @param {{services: object, exec: object}} options
|
|
61
|
+
* @param {(ctx: object) => Promise<any>|any} work
|
|
62
|
+
*/
|
|
63
|
+
export async function withAuthorizedContext({ services, exec }, work) {
|
|
64
|
+
if (!exec || typeof exec !== 'object') {
|
|
65
|
+
throw new RagError('session-invalid', 'la herramienta se ejecutó sin contexto', { details: { reason: 'missing-exec' } });
|
|
66
|
+
}
|
|
67
|
+
if (!exec.agent || typeof exec.agent !== 'object') {
|
|
68
|
+
throw new RagError('session-invalid', 'el host no entregó identidad de sesión', {
|
|
69
|
+
details: { reason: 'missing-agent' },
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const env = services.env ?? process.env;
|
|
74
|
+
const now = nowOf(services);
|
|
75
|
+
const key = profileKey(env);
|
|
76
|
+
const root = profileRoot(env);
|
|
77
|
+
const identity = captureSession(exec.agent, { env, now });
|
|
78
|
+
const signal = exec.signal ?? null;
|
|
79
|
+
if (signal?.aborted) throw cancelledError('before-resolve');
|
|
80
|
+
const cwd = await cwdOf(services, exec);
|
|
81
|
+
|
|
82
|
+
let registry;
|
|
83
|
+
try {
|
|
84
|
+
registry = openRegistry({ root, create: false, now });
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error instanceof RagError && error.code === 'store-not-initialized') {
|
|
87
|
+
throw new RagError('registry-unavailable', 'este perfil no tiene registro Project-Aware', {
|
|
88
|
+
details: { profile: key, root },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const opened = new Map();
|
|
95
|
+
const openedScopes = [];
|
|
96
|
+
const revocations = [];
|
|
97
|
+
try {
|
|
98
|
+
// Proyectos abiertos en Harness: señal de contexto, nunca autorización. Se leen antes de
|
|
99
|
+
// resolver para que un `cwd` contenedor no oculte el proyecto que la persona tiene abierto.
|
|
100
|
+
const openProjects = await listOpenProjects(services.workspaces);
|
|
101
|
+
const resolved = resolveScope(registry.db, {
|
|
102
|
+
identity, expectedProfileKey: key, cwd, openProjects, now,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const scopes = resolved.scopes.map((scope) => ({
|
|
106
|
+
...scope,
|
|
107
|
+
dir: scopeStoreDir(root, scope.id),
|
|
108
|
+
exists: scopeStoreExists(root, scope.id),
|
|
109
|
+
}));
|
|
110
|
+
// Una raíz autorizada representa una zona física concreta. Si su destino real cambió (junction,
|
|
111
|
+
// enlace o directorio sustituido) deja de representar lo autorizado: se falla en cerrado antes de
|
|
112
|
+
// abrir nada. Es la comprobación que hacía falta en el camino de ejecución, no sólo al registrar.
|
|
113
|
+
const rootRows = registry.db.prepare(
|
|
114
|
+
`SELECT id, path, path_key FROM roots WHERE scope_kind = ? AND scope_id = ? AND state = 'authorized' ORDER BY path`,
|
|
115
|
+
);
|
|
116
|
+
for (const scope of scopes) {
|
|
117
|
+
for (const rootRow of rootRows.all(scope.kind, scope.id)) {
|
|
118
|
+
assertRootUnchanged({ path: rootRow.path, path_key: rootRow.path_key, scope_id: scope.id });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const authorized = new Set(scopes.map((scope) => scope.id));
|
|
122
|
+
const audited = new Set();
|
|
123
|
+
|
|
124
|
+
/** Deja constancia una sola vez por ámbito y operación. */
|
|
125
|
+
function recordRevocation({ revoked, added, checkpoint }) {
|
|
126
|
+
const fresh = revoked.filter((id) => !audited.has(`${id}:${checkpoint}`));
|
|
127
|
+
if (fresh.length === 0) return;
|
|
128
|
+
for (const id of fresh) audited.add(`${id}:${checkpoint}`);
|
|
129
|
+
revocations.push({ revoked: [...revoked], added: [...added], checkpoint, at: nowOf(services) });
|
|
130
|
+
appendRegistryAudit(registry.db, {
|
|
131
|
+
at: nowOf(services),
|
|
132
|
+
actor: 'host',
|
|
133
|
+
sessionId: identity.sessionId,
|
|
134
|
+
action: 'authorization.revoked',
|
|
135
|
+
target: resolved.projectId,
|
|
136
|
+
outcome: 'denied',
|
|
137
|
+
detail: { revoked, added, checkpoint, guarantee: 'sin resultados del ámbito revocado' },
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Relee la autorización real. Sin caché: lo que diga el registro en este instante es la verdad.
|
|
143
|
+
* Lanza en cerrado si la sesión, el proyecto o un ámbito dejaron de estar autorizados.
|
|
144
|
+
*/
|
|
145
|
+
function revalidate({ checkpoint = 'check', strict = true } = {}) {
|
|
146
|
+
if (signal?.aborted) throw cancelledError(checkpoint);
|
|
147
|
+
const current = currentAuthorization(registry.db, {
|
|
148
|
+
sessionId: identity.sessionId,
|
|
149
|
+
projectId: resolved.projectId,
|
|
150
|
+
// Resolver por cwd no escribe una selección: en ese caso la autorización se lee del proyecto
|
|
151
|
+
// y sus grants, no de una fila de sesión que legítimamente no existe.
|
|
152
|
+
sessionOptional: resolved.source === 'cwd',
|
|
153
|
+
});
|
|
154
|
+
if (!current.ok) {
|
|
155
|
+
appendRegistryAudit(registry.db, {
|
|
156
|
+
at: nowOf(services),
|
|
157
|
+
actor: 'host',
|
|
158
|
+
sessionId: identity.sessionId,
|
|
159
|
+
action: 'authorization.invalid',
|
|
160
|
+
target: resolved.projectId,
|
|
161
|
+
outcome: 'denied',
|
|
162
|
+
detail: { reason: current.reason, invalidReason: current.invalidReason ?? null, checkpoint },
|
|
163
|
+
});
|
|
164
|
+
throw authorizationLostError(current);
|
|
165
|
+
}
|
|
166
|
+
const { revoked, added } = diffScopes([...authorized], current.scopes);
|
|
167
|
+
if (revoked.length > 0) {
|
|
168
|
+
recordRevocation({ revoked, added, checkpoint });
|
|
169
|
+
if (strict) throw revocationError({ revoked, sessionId: identity.sessionId, reason: 'revoked-during-operation' });
|
|
170
|
+
return { ok: false, revoked, added, authorization: current };
|
|
171
|
+
}
|
|
172
|
+
return { ok: true, revoked: [], added, authorization: current };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const ctx = {
|
|
176
|
+
sessionId: identity.sessionId,
|
|
177
|
+
profileKey: key,
|
|
178
|
+
profileRoot: root,
|
|
179
|
+
registryPath: registry.path,
|
|
180
|
+
cwd,
|
|
181
|
+
resolved,
|
|
182
|
+
scopes,
|
|
183
|
+
signal,
|
|
184
|
+
openedScopes,
|
|
185
|
+
revocations,
|
|
186
|
+
/** Registro abierto del perfil: sólo para mantenimiento interno (ledger, `sync_state`). */
|
|
187
|
+
registry: registry.db,
|
|
188
|
+
/** Relee autorización; un ámbito revocado aborta la operación. */
|
|
189
|
+
revalidate,
|
|
190
|
+
/** Comprueba que este ámbito sigue autorizado justo antes de abrirlo o usarlo. */
|
|
191
|
+
assertAuthorized(scope, checkpoint = 'scope') {
|
|
192
|
+
const result = revalidate({ checkpoint: `${checkpoint}:${scope.id}`, strict: false });
|
|
193
|
+
if (!result.ok) throw revocationError({ revoked: result.revoked, sessionId: identity.sessionId });
|
|
194
|
+
if (!authorized.has(scope.id)) {
|
|
195
|
+
throw new RagError('scope-forbidden', 'el ámbito no estaba autorizado al abrir la operación', {
|
|
196
|
+
details: { reason: 'scope-not-in-snapshot', scope: scope.id },
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
},
|
|
201
|
+
/** Punto de control obligatorio antes de devolver información al consumidor. */
|
|
202
|
+
checkpoint(where = 'return') {
|
|
203
|
+
return revalidate({ checkpoint: where, strict: true });
|
|
204
|
+
},
|
|
205
|
+
/** Abre un ámbito ya autorizado. `create` sólo se usa para la escritura del proyecto. */
|
|
206
|
+
open(scope, { create = false } = {}) {
|
|
207
|
+
if (!scope || typeof scope.id !== 'string') {
|
|
208
|
+
throw new RagError('internal', 'ámbito no válido');
|
|
209
|
+
}
|
|
210
|
+
if (signal?.aborted) throw cancelledError(`open:${scope.id}`);
|
|
211
|
+
// Un handle ya abierto no es una autorización permanente: se vuelve a comprobar antes de
|
|
212
|
+
// devolverlo, porque una revocación puede haber ocurrido entre dos usos del mismo ámbito.
|
|
213
|
+
if (opened.has(scope.id)) {
|
|
214
|
+
ctx.assertAuthorized(scope, 'reopen');
|
|
215
|
+
return opened.get(scope.id);
|
|
216
|
+
}
|
|
217
|
+
ctx.assertAuthorized(scope, 'open');
|
|
218
|
+
const db = openScopeStore({ profileRoot: root, profileKey: key, scope, create, now });
|
|
219
|
+
if (db) {
|
|
220
|
+
opened.set(scope.id, db);
|
|
221
|
+
openedScopes.push({ id: scope.id, kind: scope.kind, create });
|
|
222
|
+
}
|
|
223
|
+
return db;
|
|
224
|
+
},
|
|
225
|
+
project() {
|
|
226
|
+
return scopes.find((scope) => scope.kind === 'prj') ?? null;
|
|
227
|
+
},
|
|
228
|
+
libraries() {
|
|
229
|
+
return scopes.filter((scope) => scope.kind === 'lib');
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
return await work(ctx);
|
|
234
|
+
} finally {
|
|
235
|
+
for (const db of opened.values()) closeDatabase(db);
|
|
236
|
+
closeRegistry(registry.db);
|
|
237
|
+
}
|
|
238
|
+
}
|