File size: 18,064 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 | /**
* Policy Limits Service
*
* Fetches organization-level policy restrictions from the API and uses them
* to disable CLI features. Follows the same patterns as remote managed settings
* (fail open, ETag caching, background polling, retry logic).
*
* Eligibility:
* - Console users (API key): All eligible
* - OAuth users (Claude.ai): Only Team and Enterprise/C4E subscribers are eligible
* - API fails open (non-blocking) - if fetch fails, continues without restrictions
* - API returns empty restrictions for users without policy limits
*/
import axios from 'axios'
import { createHash } from 'crypto'
import { readFileSync as fsReadFileSync } from 'fs'
import { unlink, writeFile } from 'fs/promises'
import { join } from 'path'
import {
CLAUDE_AI_INFERENCE_SCOPE,
getOauthConfig,
OAUTH_BETA_HEADER,
} from '../../constants/oauth.js'
import {
checkAndRefreshOAuthTokenIfNeeded,
getAnthropicApiKeyWithSource,
getClaudeAIOAuthTokens,
} from '../../utils/auth.js'
import { registerCleanup } from '../../utils/cleanupRegistry.js'
import { logForDebugging } from '../../utils/debug.js'
import { getClaudeConfigHomeDir } from '../../utils/envUtils.js'
import { classifyAxiosError } from '../../utils/errors.js'
import { safeParseJSON } from '../../utils/json.js'
import {
getAPIProvider,
isFirstPartyAnthropicBaseUrl,
} from '../../utils/model/providers.js'
import { isEssentialTrafficOnly } from '../../utils/privacyLevel.js'
import { sleep } from '../../utils/sleep.js'
import { jsonStringify } from '../../utils/slowOperations.js'
import { getClaudeCodeUserAgent } from '../../utils/userAgent.js'
import { getRetryDelay } from '../api/withRetry.js'
import {
type PolicyLimitsFetchResult,
type PolicyLimitsResponse,
PolicyLimitsResponseSchema,
} from './types.js'
function isNodeError(e: unknown): e is NodeJS.ErrnoException {
return e instanceof Error
}
// Constants
const CACHE_FILENAME = 'policy-limits.json'
const FETCH_TIMEOUT_MS = 10000 // 10 seconds
const DEFAULT_MAX_RETRIES = 5
const POLLING_INTERVAL_MS = 60 * 60 * 1000 // 1 hour
// Background polling state
let pollingIntervalId: ReturnType<typeof setInterval> | null = null
let cleanupRegistered = false
// Promise that resolves when initial policy limits loading completes
let loadingCompletePromise: Promise<void> | null = null
let loadingCompleteResolve: (() => void) | null = null
// Timeout for the loading promise to prevent deadlocks
const LOADING_PROMISE_TIMEOUT_MS = 30000 // 30 seconds
// Session-level cache for policy restrictions
let sessionCache: PolicyLimitsResponse['restrictions'] | null = null
/**
* Test-only sync reset. clearPolicyLimitsCache() does file I/O and is too
* expensive for preload beforeEach; this only clears the module-level
* singleton so downstream tests in the same shard see a clean slate.
*/
export function _resetPolicyLimitsForTesting(): void {
stopBackgroundPolling()
sessionCache = null
loadingCompletePromise = null
loadingCompleteResolve = null
}
/**
* Initialize the loading promise for policy limits
* This should be called early (e.g., in init.ts) to allow other systems
* to await policy limits loading even if loadPolicyLimits() hasn't been called yet.
*
* Only creates the promise if the user is eligible for policy limits.
* Includes a timeout to prevent deadlocks if loadPolicyLimits() is never called.
*/
export function initializePolicyLimitsLoadingPromise(): void {
if (loadingCompletePromise) {
return
}
if (isPolicyLimitsEligible()) {
loadingCompletePromise = new Promise(resolve => {
loadingCompleteResolve = resolve
setTimeout(() => {
if (loadingCompleteResolve) {
logForDebugging(
'Policy limits: Loading promise timed out, resolving anyway',
)
loadingCompleteResolve()
loadingCompleteResolve = null
}
}, LOADING_PROMISE_TIMEOUT_MS)
})
}
}
/**
* Get the path to the policy limits cache file
*/
function getCachePath(): string {
return join(getClaudeConfigHomeDir(), CACHE_FILENAME)
}
/**
* Get the policy limits API endpoint
*/
function getPolicyLimitsEndpoint(): string {
return `${getOauthConfig().BASE_API_URL}/api/claude_code/policy_limits`
}
/**
* Recursively sort all keys in an object for consistent hashing
*/
function sortKeysDeep(obj: unknown): unknown {
if (Array.isArray(obj)) {
return obj.map(sortKeysDeep)
}
if (obj !== null && typeof obj === 'object') {
const sorted: Record<string, unknown> = {}
for (const [key, value] of Object.entries(obj).sort(([a], [b]) =>
a.localeCompare(b),
)) {
sorted[key] = sortKeysDeep(value)
}
return sorted
}
return obj
}
/**
* Compute a checksum from restrictions content for HTTP caching
*/
function computeChecksum(
restrictions: PolicyLimitsResponse['restrictions'],
): string {
const sorted = sortKeysDeep(restrictions)
const normalized = jsonStringify(sorted)
const hash = createHash('sha256').update(normalized).digest('hex')
return `sha256:${hash}`
}
/**
* Check if the current user is eligible for policy limits.
*
* IMPORTANT: This function must NOT call getSettings() or any function that calls
* getSettings() to avoid circular dependencies during settings loading.
*/
export function isPolicyLimitsEligible(): boolean {
// 3p provider users should not hit the policy limits endpoint
if (getAPIProvider() !== 'firstParty') {
return false
}
// Custom base URL users should not hit the policy limits endpoint
if (!isFirstPartyAnthropicBaseUrl()) {
return false
}
// Console users (API key) are eligible if we can get the actual key
try {
const { key: apiKey } = getAnthropicApiKeyWithSource({
skipRetrievingKeyFromApiKeyHelper: true,
})
if (apiKey) {
return true
}
} catch {
// No API key available - continue to check OAuth
}
// For OAuth users, check if they have Claude.ai tokens
const tokens = getClaudeAIOAuthTokens()
if (!tokens?.accessToken) {
return false
}
// Must have Claude.ai inference scope
if (!tokens.scopes?.includes(CLAUDE_AI_INFERENCE_SCOPE)) {
return false
}
// Only Team and Enterprise OAuth users are eligible — these orgs have
// admin-configurable policy restrictions (e.g. allow_remote_sessions)
if (
tokens.subscriptionType !== 'enterprise' &&
tokens.subscriptionType !== 'team'
) {
return false
}
return true
}
/**
* Wait for the initial policy limits loading to complete
* Returns immediately if user is not eligible or loading has already completed
*/
export async function waitForPolicyLimitsToLoad(): Promise<void> {
if (loadingCompletePromise) {
await loadingCompletePromise
}
}
/**
* Get auth headers for policy limits without calling getSettings()
* Supports both API key and OAuth authentication
*/
function getAuthHeaders(): {
headers: Record<string, string>
error?: string
} {
// Try API key first (for Console users)
try {
const { key: apiKey } = getAnthropicApiKeyWithSource({
skipRetrievingKeyFromApiKeyHelper: true,
})
if (apiKey) {
return {
headers: {
'x-api-key': apiKey,
},
}
}
} catch {
// No API key available - continue to check OAuth
}
// Fall back to OAuth tokens (for Claude.ai users)
const oauthTokens = getClaudeAIOAuthTokens()
if (oauthTokens?.accessToken) {
return {
headers: {
Authorization: `Bearer ${oauthTokens.accessToken}`,
'anthropic-beta': OAUTH_BETA_HEADER,
},
}
}
return {
headers: {},
error: 'No authentication available',
}
}
/**
* Fetch policy limits with retry logic and exponential backoff
*/
async function fetchWithRetry(
cachedChecksum?: string,
): Promise<PolicyLimitsFetchResult> {
let lastResult: PolicyLimitsFetchResult | null = null
for (let attempt = 1; attempt <= DEFAULT_MAX_RETRIES + 1; attempt++) {
lastResult = await fetchPolicyLimits(cachedChecksum)
if (lastResult.success) {
return lastResult
}
if (lastResult.skipRetry) {
return lastResult
}
if (attempt > DEFAULT_MAX_RETRIES) {
return lastResult
}
const delayMs = getRetryDelay(attempt)
logForDebugging(
`Policy limits: Retry ${attempt}/${DEFAULT_MAX_RETRIES} after ${delayMs}ms`,
)
await sleep(delayMs)
}
return lastResult!
}
/**
* Fetch policy limits (single attempt, no retries)
*/
async function fetchPolicyLimits(
cachedChecksum?: string,
): Promise<PolicyLimitsFetchResult> {
try {
await checkAndRefreshOAuthTokenIfNeeded()
const authHeaders = getAuthHeaders()
if (authHeaders.error) {
return {
success: false,
error: 'Authentication required for policy limits',
skipRetry: true,
}
}
const endpoint = getPolicyLimitsEndpoint()
const headers: Record<string, string> = {
...authHeaders.headers,
'User-Agent': getClaudeCodeUserAgent(),
}
if (cachedChecksum) {
headers['If-None-Match'] = `"${cachedChecksum}"`
}
const response = await axios.get(endpoint, {
headers,
timeout: FETCH_TIMEOUT_MS,
validateStatus: status =>
status === 200 || status === 304 || status === 404,
})
// Handle 304 Not Modified - cached version is still valid
if (response.status === 304) {
logForDebugging('Policy limits: Using cached restrictions (304)')
return {
success: true,
restrictions: null, // Signal that cache is valid
etag: cachedChecksum,
}
}
// Handle 404 Not Found - no policy limits exist or feature not enabled
if (response.status === 404) {
logForDebugging('Policy limits: No restrictions found (404)')
return {
success: true,
restrictions: {},
etag: undefined,
}
}
const parsed = PolicyLimitsResponseSchema().safeParse(response.data)
if (!parsed.success) {
logForDebugging(
`Policy limits: Invalid response format - ${parsed.error.message}`,
)
return {
success: false,
error: 'Invalid policy limits format',
}
}
logForDebugging('Policy limits: Fetched successfully')
return {
success: true,
restrictions: parsed.data.restrictions,
}
} catch (error) {
// 404 is handled above via validateStatus, so it won't reach here
const { kind, message } = classifyAxiosError(error)
switch (kind) {
case 'auth':
return {
success: false,
error: 'Not authorized for policy limits',
skipRetry: true,
}
case 'timeout':
return { success: false, error: 'Policy limits request timeout' }
case 'network':
return { success: false, error: 'Cannot connect to server' }
default:
return { success: false, error: message }
}
}
}
/**
* Load restrictions from cache file
*/
// sync IO: called from sync context (getRestrictionsFromCache -> isPolicyAllowed)
function loadCachedRestrictions(): PolicyLimitsResponse['restrictions'] | null {
try {
const content = fsReadFileSync(getCachePath(), 'utf-8')
const data = safeParseJSON(content, false)
const parsed = PolicyLimitsResponseSchema().safeParse(data)
if (!parsed.success) {
return null
}
return parsed.data.restrictions
} catch {
return null
}
}
/**
* Save restrictions to cache file
*/
async function saveCachedRestrictions(
restrictions: PolicyLimitsResponse['restrictions'],
): Promise<void> {
try {
const path = getCachePath()
const data: PolicyLimitsResponse = { restrictions }
await writeFile(path, jsonStringify(data, null, 2), {
encoding: 'utf-8',
mode: 0o600,
})
logForDebugging(`Policy limits: Saved to ${path}`)
} catch (error) {
logForDebugging(
`Policy limits: Failed to save - ${error instanceof Error ? error.message : 'unknown error'}`,
)
}
}
/**
* Fetch and load policy limits with file caching
* Fails open - returns null if fetch fails and no cache exists
*/
async function fetchAndLoadPolicyLimits(): Promise<
PolicyLimitsResponse['restrictions'] | null
> {
if (!isPolicyLimitsEligible()) {
return null
}
const cachedRestrictions = loadCachedRestrictions()
const cachedChecksum = cachedRestrictions
? computeChecksum(cachedRestrictions)
: undefined
try {
const result = await fetchWithRetry(cachedChecksum)
if (!result.success) {
if (cachedRestrictions) {
logForDebugging('Policy limits: Using stale cache after fetch failure')
sessionCache = cachedRestrictions
return cachedRestrictions
}
return null
}
// Handle 304 Not Modified
if (result.restrictions === null && cachedRestrictions) {
logForDebugging('Policy limits: Cache still valid (304 Not Modified)')
sessionCache = cachedRestrictions
return cachedRestrictions
}
const newRestrictions = result.restrictions || {}
const hasContent = Object.keys(newRestrictions).length > 0
if (hasContent) {
sessionCache = newRestrictions
await saveCachedRestrictions(newRestrictions)
logForDebugging('Policy limits: Applied new restrictions successfully')
return newRestrictions
}
// Empty restrictions (404 response) - delete cached file if it exists
sessionCache = newRestrictions
try {
await unlink(getCachePath())
logForDebugging('Policy limits: Deleted cached file (404 response)')
} catch (e) {
if (isNodeError(e) && e.code !== 'ENOENT') {
logForDebugging(
`Policy limits: Failed to delete cached file - ${e.message}`,
)
}
}
return newRestrictions
} catch {
if (cachedRestrictions) {
logForDebugging('Policy limits: Using stale cache after error')
sessionCache = cachedRestrictions
return cachedRestrictions
}
return null
}
}
/**
* Policies that default to denied when essential-traffic-only mode is active
* and the policy cache is unavailable. Without this, a cache miss or network
* timeout would silently re-enable these features for HIPAA orgs.
*/
const ESSENTIAL_TRAFFIC_DENY_ON_MISS = new Set(['allow_product_feedback'])
/**
* Check if a specific policy is allowed
* Returns true if the policy is unknown, unavailable, or explicitly allowed (fail open).
* Exception: policies in ESSENTIAL_TRAFFIC_DENY_ON_MISS fail closed when
* essential-traffic-only mode is active and the cache is unavailable.
*/
export function isPolicyAllowed(policy: string): boolean {
const restrictions = getRestrictionsFromCache()
if (!restrictions) {
if (
isEssentialTrafficOnly() &&
ESSENTIAL_TRAFFIC_DENY_ON_MISS.has(policy)
) {
return false
}
return true // fail open
}
const restriction = restrictions[policy]
if (!restriction) {
return true // unknown policy = allowed
}
return restriction.allowed
}
/**
* Get restrictions synchronously from session cache or file
*/
function getRestrictionsFromCache():
| PolicyLimitsResponse['restrictions']
| null {
if (!isPolicyLimitsEligible()) {
return null
}
if (sessionCache) {
return sessionCache
}
const cachedRestrictions = loadCachedRestrictions()
if (cachedRestrictions) {
sessionCache = cachedRestrictions
return cachedRestrictions
}
return null
}
/**
* Load policy limits during CLI initialization
* Fails open - if fetch fails, continues without restrictions
* Also starts background polling to pick up changes mid-session
*/
export async function loadPolicyLimits(): Promise<void> {
if (isPolicyLimitsEligible() && !loadingCompletePromise) {
loadingCompletePromise = new Promise(resolve => {
loadingCompleteResolve = resolve
})
}
try {
await fetchAndLoadPolicyLimits()
if (isPolicyLimitsEligible()) {
startBackgroundPolling()
}
} finally {
if (loadingCompleteResolve) {
loadingCompleteResolve()
loadingCompleteResolve = null
}
}
}
/**
* Refresh policy limits asynchronously (for auth state changes)
* Used when login occurs
*/
export async function refreshPolicyLimits(): Promise<void> {
await clearPolicyLimitsCache()
if (!isPolicyLimitsEligible()) {
return
}
await fetchAndLoadPolicyLimits()
logForDebugging('Policy limits: Refreshed after auth change')
}
/**
* Clear all policy limits (session, persistent, and stop polling)
*/
export async function clearPolicyLimitsCache(): Promise<void> {
stopBackgroundPolling()
sessionCache = null
loadingCompletePromise = null
loadingCompleteResolve = null
try {
await unlink(getCachePath())
} catch {
// Ignore errors (including ENOENT when file doesn't exist)
}
}
/**
* Background polling callback
*/
async function pollPolicyLimits(): Promise<void> {
if (!isPolicyLimitsEligible()) {
return
}
const previousCache = sessionCache ? jsonStringify(sessionCache) : null
try {
await fetchAndLoadPolicyLimits()
const newCache = sessionCache ? jsonStringify(sessionCache) : null
if (newCache !== previousCache) {
logForDebugging('Policy limits: Changed during background poll')
}
} catch {
// Don't fail closed for background polling
}
}
/**
* Start background polling for policy limits
*/
export function startBackgroundPolling(): void {
if (pollingIntervalId !== null) {
return
}
if (!isPolicyLimitsEligible()) {
return
}
pollingIntervalId = setInterval(() => {
void pollPolicyLimits()
}, POLLING_INTERVAL_MS)
pollingIntervalId.unref()
if (!cleanupRegistered) {
cleanupRegistered = true
registerCleanup(async () => stopBackgroundPolling())
}
}
/**
* Stop background polling for policy limits
*/
export function stopBackgroundPolling(): void {
if (pollingIntervalId !== null) {
clearInterval(pollingIntervalId)
pollingIntervalId = null
}
}
|