osuite 2.10.2 → 2.11.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.
@@ -1,5 +1,5 @@
1
- import { createHmac, timingSafeEqual } from 'node:crypto';
2
- import { canonicalJson, isObject, safeId, sha256, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
1
+ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { canonicalJson, isObject, isTransientFailure, safeId, sha256, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
3
3
 
4
4
  export const POSTURE_SCHEMA = 'osuite.runtime_posture.v1';
5
5
  const MAX_FRESHNESS_MS = 300000;
@@ -100,24 +100,91 @@ function configurationOnly(document) {
100
100
  ].map(key => [key, document[key]]));
101
101
  }
102
102
 
103
- function mac(document, config) {
104
- return createHmac('sha256', config.apiKey || '').update('osuite.posture-cache.v1\n').update(canonicalJson(document)).digest('hex');
103
+ function mac(document, config, generation = 0, rejected = false, fenceId = null) {
104
+ const hash = createHmac('sha256', config.apiKey || '').update('osuite.posture-cache.v1\n').update(canonicalJson(document));
105
+ if (generation > 0) hash.update(`\nrejection-generation:${generation}:${rejected}`);
106
+ if (fenceId !== null) hash.update(`\nrejection-fence:${fenceId}`);
107
+ return hash.digest('hex');
105
108
  }
106
109
 
107
- function cachedDocument(value, config, now) {
110
+ function cacheEntry(value, config, now) {
108
111
  try {
109
- if (!isObject(value) || !validDocument(value.document, config, now, true) || !/^[a-f0-9]{64}$/.test(value.mac)) return null;
110
- if (!timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(mac(value.document, config), 'hex'))) return null;
111
- return value.document;
112
+ if (!isObject(value)) return null;
113
+ const generation = value.generation ?? 0, rejected = value.rejected ?? false;
114
+ const fenceId = value.fenceId ?? null;
115
+ if (!Number.isSafeInteger(generation) || generation < 0 || typeof rejected !== 'boolean'
116
+ || (fenceId !== null && !safeId(fenceId))
117
+ || (rejected && generation === 0)
118
+ || (value.document !== null && !validDocument(value.document, config, now, true))
119
+ || !/^[a-f0-9]{64}$/.test(value.mac)) return null;
120
+ if (!timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(mac(value.document, config, generation, rejected, fenceId), 'hex'))) return null;
121
+ return { document: value.document, generation, rejected, fenceId };
112
122
  } catch { return null; }
113
123
  }
114
124
 
115
- function readCache(store, config, now) {
116
- try { return cachedDocument(store.read('posture'), config, now); } catch { return null; }
125
+ function signedCache(document, config, generation = 0, rejected = false, fenceId = null) {
126
+ return { document, mac: mac(document, config, generation, rejected, fenceId),
127
+ ...(generation > 0 ? { generation, rejected } : {}), ...(fenceId !== null ? { fenceId } : {}) };
128
+ }
129
+
130
+ function readEntry(store, config, now) {
131
+ try { return cacheEntry(store.read('posture'), config, now); } catch { return null; }
132
+ }
133
+
134
+ function fenceMac(id, config) {
135
+ return createHmac('sha256', config.apiKey || '').update(`osuite.posture-rejection.v1\n${id}`).digest('hex');
136
+ }
137
+
138
+ function readFence(store, config) {
139
+ try {
140
+ const value = store.read('posture-rejection');
141
+ if (value == null) return { valid: true, id: null };
142
+ if (value.schema !== 'osuite.posture-rejection.v1' || !safeId(value.id)
143
+ || !/^[a-f0-9]{64}$/.test(value.mac)
144
+ || !timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(fenceMac(value.id, config), 'hex'))) return { valid: false };
145
+ return { valid: true, id: value.id };
146
+ } catch { return { valid: false }; }
147
+ }
148
+
149
+ export function captureRejectionFence(config, store) {
150
+ try {
151
+ const fence = readFence(store, config), raw = store.read('posture');
152
+ const entry = cacheEntry(raw, config, Date.now());
153
+ return Object.freeze({ valid: fence.valid && (raw == null || entry !== null), id: fence.id,
154
+ generation: entry?.generation || 0, rejected: entry?.rejected === true || (entry?.fenceId ?? null) !== fence.id });
155
+ } catch { return Object.freeze({ valid: false, rejected: true }); }
156
+ }
157
+
158
+ export function rejectionFenceUnchanged(config, store, before) {
159
+ const current = captureRejectionFence(config, store);
160
+ return before?.valid === true && before.rejected === false && current.valid && !current.rejected
161
+ && before.id === current.id && before.generation === current.generation;
162
+ }
163
+
164
+ export function invalidatePostureCache(config, store, now = Date.now()) {
165
+ const id = randomUUID();
166
+ // Independent atomic marker survives contention on the configuration lock.
167
+ // Never delete it to recover: a fresh response must bind the current marker.
168
+ store.write('posture-rejection', { schema: 'osuite.posture-rejection.v1', id, mac: fenceMac(id, config) });
169
+ return cacheEntry(store.update('posture', value => {
170
+ const latest = cacheEntry(value, config, now);
171
+ const generation = (latest?.generation || 0) + 1;
172
+ if (!Number.isSafeInteger(generation)) throw new Error('Cache generation exhausted');
173
+ return signedCache(latest?.document || null, config, generation, true, id);
174
+ }), config, now);
117
175
  }
118
176
 
119
177
  export async function resolveRemotePosture(config, { api, store, now = Date.now() }) {
120
178
  const capable = config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY;
179
+ const startedFence = readFence(store, config);
180
+ if (!startedFence.valid) return { available: false, blocked: true, source: 'unavailable', posture: localPosture(config), revision: null };
181
+ // Detect existing storage failure before learning a decision we cannot retain.
182
+ // This probe is not authority and does not promise durability through later I/O failure.
183
+ try { store.write('posture-storage-probe', { schema: 'osuite.state-probe.v1', at: now }); }
184
+ catch { return { available: false, blocked: true, source: 'unavailable',
185
+ posture: offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), revision: null }; }
186
+ const startedGeneration = readEntry(store, config, now)?.generation || 0;
187
+ const rejectionFence = Object.freeze({ valid: true, id: startedFence.id, generation: startedGeneration, rejected: false });
121
188
  let acknowledged = null;
122
189
  if (capable) {
123
190
  const acknowledgement = await api.request('PUT', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture`, {
@@ -125,6 +192,9 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
125
192
  }, { timeoutMs: 2000 });
126
193
  const value = acknowledgement.body;
127
194
  if (!acknowledgement.ok || !validAcknowledgement(value, config, now)) {
195
+ if (!isTransientFailure(acknowledgement)) {
196
+ try { invalidatePostureCache(config, store, now); } catch { /* This invocation still blocks. */ }
197
+ }
128
198
  return { available: false, blocked: true, source: 'unavailable', posture: localPosture(config), revision: null };
129
199
  }
130
200
  acknowledged = value;
@@ -132,37 +202,52 @@ export async function resolveRemotePosture(config, { api, store, now = Date.now(
132
202
  const query = new URLSearchParams({ agent_id: config.agentId });
133
203
  if (config.provider) query.set('provider', config.provider);
134
204
  const response = await api.request('GET', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture?${query}`, undefined, { timeoutMs: 2000 });
135
- const rejected = [401, 403, 409].includes(response.status);
136
- let cached = readCache(store, config, now);
137
- if (response.ok && response.status === 200 && validDocument(response.body, config, now)
138
- && (!capable || matchesAcknowledgement(response.body, acknowledged)) && preservesRolloutFloor(cached, response.body)
205
+ const validResponse = response.ok && response.status === 200 && validDocument(response.body, config, now)
206
+ && (!capable || matchesAcknowledgement(response.body, acknowledged));
207
+ const rejected = !validResponse && !isTransientFailure(response);
208
+ let entry = readEntry(store, config, now), cached = entry?.document;
209
+ if (rejected) {
210
+ try {
211
+ entry = invalidatePostureCache(config, store, now);
212
+ cached = entry?.document;
213
+ } catch {
214
+ return { available: false, blocked: true, source: 'unavailable',
215
+ posture: offlinePosture(localPosture(config), cached?.posture), revision: cached?.revision || null };
216
+ }
217
+ }
218
+ if (validResponse && preservesRolloutFloor(cached, response.body)
139
219
  && (!cached || Date.parse(response.body.issued_at) >= Date.parse(cached.issued_at))) {
140
220
  const document = configurationOnly(response.body);
141
221
  try {
142
222
  // The comparison and replacement share a cross-process lock. A stale
143
223
  // response must not replace a stronger configuration published meanwhile.
144
224
  const saved = store.update('posture', value => {
145
- const latest = cachedDocument(value, config, now);
146
- return latest && (Date.parse(latest.issued_at) > Date.parse(document.issued_at) || !preservesRolloutFloor(latest, document))
147
- ? value : { document, mac: mac(document, config) };
225
+ const latest = cacheEntry(value, config, now), previous = latest?.document;
226
+ // A request that began before a rejection cannot clear that rejection.
227
+ const currentFence = readFence(store, config);
228
+ if (!currentFence.valid || currentFence.id !== startedFence.id || (latest?.generation || 0) !== startedGeneration) return value;
229
+ return previous && (Date.parse(previous.issued_at) > Date.parse(document.issued_at) || !preservesRolloutFloor(previous, document))
230
+ ? value : signedCache(document, config, startedGeneration, false, startedFence.id);
148
231
  });
149
- cached = cachedDocument(saved, config, now);
150
- if (cached && canonicalJson(cached) === canonicalJson(document)) {
232
+ entry = cacheEntry(saved, config, now); cached = entry?.document;
233
+ if (rejectionFenceUnchanged(config, store, rejectionFence) && cached && canonicalJson(cached) === canonicalJson(document)) {
151
234
  return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision,
152
- ruleRollout: document.rule_rollout, orgId: document.org_id };
235
+ ruleRollout: document.rule_rollout, orgId: document.org_id, rejectionFence };
153
236
  }
154
237
  } catch {
155
- const posture = offlinePosture(offlinePosture(localPosture(config), readCache(store, config, now)?.posture), document.posture);
156
- return { available: false, blocked: capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
238
+ const posture = offlinePosture(offlinePosture(localPosture(config), readEntry(store, config, now)?.document?.posture), document.posture);
239
+ return { available: false, blocked: true, source: 'unavailable', posture, revision: cached?.revision || null };
157
240
  }
158
241
  }
159
242
  const posture = offlinePosture(localPosture(config), cached?.posture);
160
- // Revocation and explicit scope rejection invalidate cached authority immediately.
161
- if (!rejected && !(capable && response.ok) && cached && Date.parse(cached.valid_until) > now
243
+ // Rejection is retained across requests; a fresh valid response must clear it.
244
+ const fenced = !rejectionFenceUnchanged(config, store, rejectionFence);
245
+ if (!rejected && !entry?.rejected && !fenced && !(capable && response.ok) && cached && Date.parse(cached.valid_until) > now
162
246
  && validNegotiation(cached, config, now)) {
163
247
  if (capable && !matchesAcknowledgement(cached, acknowledged)) return { available: false, blocked: true, source: 'unavailable', posture, revision: cached.revision };
164
248
  return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision,
165
- ruleRollout: cached.rule_rollout, orgId: cached.org_id };
249
+ ruleRollout: cached.rule_rollout, orgId: cached.org_id, rejectionFence };
166
250
  }
167
- return { available: false, blocked: rejected || capable || posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
251
+ return { available: false, blocked: rejected || fenced || entry?.rejected === true || capable || posture.mode !== 'observe',
252
+ source: 'unavailable', posture, revision: cached?.revision || null, rejectionFence };
168
253
  }
@@ -6,6 +6,21 @@ export const isObject = value => value !== null && typeof value === 'object' &&
6
6
  export const sha256 = value => createHash('sha256').update(value).digest('hex');
7
7
  export const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,199}$/.test(value) && !value.includes('..');
8
8
 
9
+ export const isTransientFailure = response => response?.ok === false && (
10
+ (response.status === 0 && ['timeout', 'transport_failure'].includes(response.error))
11
+ || (response.error === 'http_error' && [500, 502, 503, 504].includes(response.status))
12
+ );
13
+
14
+ const transientCodes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT',
15
+ 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_SOCKET']);
16
+ function transientTransport(error) {
17
+ const cause = error?.cause || error;
18
+ if (cause?.errors !== undefined) return Array.isArray(cause.errors) && cause.errors.length > 0
19
+ && cause.errors.length <= 32 && (cause.code === undefined || transientCodes.has(cause.code))
20
+ && cause.errors.every(item => transientCodes.has(item?.code) && item.errors === undefined);
21
+ return transientCodes.has(cause?.code);
22
+ }
23
+
9
24
  export function canonicalJson(value) {
10
25
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
11
26
  if (isObject(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
@@ -33,6 +48,10 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
33
48
  const baseUrl = validatedBaseUrl(config.baseUrl, config);
34
49
  if (!baseUrl) return { ok: false, status: 0, error: 'invalid_base_url' };
35
50
  if (!config.apiKey) return { ok: false, status: 0, error: 'not_configured' };
51
+ if (typeof config.apiKey !== 'string' || !/^[\x21-\x7e]+$/.test(config.apiKey)
52
+ || !['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].includes(method)) {
53
+ return { ok: false, status: 0, error: 'invalid_request' };
54
+ }
36
55
  if (typeof endpoint !== 'string' || !endpoint.startsWith('/') || endpoint.startsWith('//')) {
37
56
  return { ok: false, status: 0, error: 'invalid_endpoint' };
38
57
  }
@@ -88,13 +107,14 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
88
107
  chunks.push(Buffer.from(value));
89
108
  }
90
109
  let parsed;
91
- try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch {
110
+ try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch {
92
111
  return { ok: false, status, error: 'invalid_response' };
93
112
  }
94
113
  if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
95
114
  return { ok: true, status, body: parsed };
96
- } catch {
97
- return { ok: false, status, error: controller.signal.aborted ? 'timeout' : 'transport_failure' };
115
+ } catch (error) {
116
+ return { ok: false, status, error: status ? 'invalid_response' : controller.signal.aborted ? 'timeout'
117
+ : transientTransport(error) ? 'transport_failure' : 'request_failed' };
98
118
  } finally { clearTimeout(timer); }
99
119
  },
100
120
  };