Repository navigation
feat(platform): org-configurable session idle timeout (#1502) - #1819
Conversation
Add a `session_idle_timeout` governance policy so org admins can tighten the deployment-wide SESSION_IDLE_TIMEOUT_MINUTES backstop from Settings → Security. The env var stays the server-side sliding-window control and the hard cap an org may only shorten, never extend; the per-org window drives the client idle watchdog. - resolveEffectiveIdleMinutes() combines env backstop × org policy (pure, shared by the watchdog and Convex; unit-tested). - sessionIdleTimeoutConfigSchema + policy type (shared + convex schema in sync); upsertPolicy validates it and audit-logs the change as before. - Policy is member-readable so the watchdog can size its window. - SessionIdleTimeoutEditor mounted in Settings → Security with preload. - Watchdog resolves its window from org policy × env instead of env alone. - i18n en/de/fr; resolver, watchdog, and editor tests.
📝 WalkthroughWalkthroughThis PR implements per-organization session idle timeout governance, allowing org admins to tighten (but not loosen) the server-wide environment timeout. The implementation adds: (1) core resolution logic combining org policy with env backstop via min-tightening semantics; (2) governance schema extensions and backend validation/access control; (3) client-side watchdog updates to apply effective timeouts; (4) UI editor component for policy configuration; and (5) full localization and route integration. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Billing warning: we have not been able to collect payment for this subscription for more than 72 hours. Please update the payment method or pay any pending invoices in Billing to avoid service interruption. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx`:
- Around line 62-67: The test in session-idle-timeout-editor.test.tsx asserts
the heading by an English literal which breaks i18n; update the spec that uses
setLoaded(), render(<SessionIdleTimeoutEditor ... />) and
screen.getByRole('heading', ...) to either resolve the expected label via the
translation helper used in tests (e.g., call the same i18n/t function or import
the session idle timeout key) and assert against that translated string, or
remove the language dependency and assert structure only (e.g.,
getByRole('heading') with a positional/semantic check or getByRole + within(...)
to verify children/components) so the assertion no longer pins the English text.
- Around line 22-29: The test fixture types are too broad: replace the cast on
state.config (currently "as Record<string, unknown> | undefined") with the
concrete SessionIdleTimeoutConfig type so the fixture matches what
SessionIdleTimeoutEditor expects; change the hoisted state declaration to type
state.config as SessionIdleTimeoutConfig | undefined and annotate the literal
using "satisfies SessionIdleTimeoutConfig" for the initial object (enabled +
idleTimeoutMinutes) to catch shape drift and remove the broad Record<string,
unknown> | undefined assertion.
In
`@services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx`:
- Around line 77-93: The Zod schema for idleTimeoutMinutes currently only
localizes .min/.max errors so empty or non-numeric inputs produce default
English messages; update the schema inside useMemo (the schema constant that
defines idleTimeoutMinutes) to pass the localized message to z.number() and to
.int() as well (use t('sessionIdleTimeout.invalid')) so all validation failures
— non-number, non-int, too small, too large — produce the translated message;
ensure you keep references to SESSION_IDLE_TIMEOUT_MIN_MINUTES and
SESSION_IDLE_TIMEOUT_MAX_MINUTES unchanged.
In `@services/platform/app/hooks/use-session-idle-watchdog.tsx`:
- Around line 61-82: When organizationId is set we must not fall back to
envMinutes while the org policy query is still loading: update the useMemo that
computes minutes (the block that references
useConvexQuery/api.governance.queries.getPolicy, policyRow,
resolveEffectiveIdleMinutes) so that if organizationId is present and policyRow
is strictly undefined (query unresolved) the memo returns null (or otherwise
short-circuits) instead of computing from envMinutes; once policyRow is resolved
(null or a value) continue to parse with sessionIdleTimeoutConfigSchema and call
resolveEffectiveIdleMinutes as before. Ensure the logic only treats policyRow
=== undefined as loading and does not change behavior when policyRow is null (no
policy).
In `@services/platform/convex/governance/mutations.ts`:
- Around line 239-246: The session_idle_timeout branch validates args.config
with sessionIdleTimeoutConfigSchema.safeParse but still persists the raw
args.config; change the code to persist the normalized parsed.data instead:
after const parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config) (and
after the success check) use parsed.data wherever the code currently writes
config (e.g., the write/update that sets config and newState.config) so defaults
and validated fields (enabled, idleTimeoutMinutes) are stored and unknown keys
are excluded.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 03ee20f1-2ed3-4d96-aed9-b674c8afaf1d
📒 Files selected for processing (14)
services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsxservices/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsxservices/platform/app/hooks/use-session-idle-watchdog.test.tsxservices/platform/app/hooks/use-session-idle-watchdog.tsxservices/platform/app/routes/dashboard/$id/settings/governance/security-monitoring.tsxservices/platform/convex/governance/mutations.tsservices/platform/convex/governance/queries.tsservices/platform/convex/governance/schema.tsservices/platform/lib/shared/schemas/governance.tsservices/platform/lib/shared/session-idle.test.tsservices/platform/lib/shared/session-idle.tsservices/platform/messages/de.jsonservices/platform/messages/en.jsonservices/platform/messages/fr.json
| const { state } = vi.hoisted(() => ({ | ||
| state: { | ||
| isLoading: false, | ||
| config: { enabled: true, idleTimeoutMinutes: 30 } as | ||
| | Record<string, unknown> | ||
| | undefined, | ||
| }, | ||
| })); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx"
if [ ! -f "$FILE" ]; then
echo "Missing file: $FILE"
exit 1
fi
echo "=== File head (first 140 lines) ==="
nl -ba "$FILE" | sed -n '1,140p'
echo
echo "=== Extract lines 15-45 ==="
nl -ba "$FILE" | sed -n '15,45p'
echo
echo "=== Find occurrences of 'vi.hoisted' in file ==="
rg -n "vi\.hoisted" "$FILE" || true
echo
echo "=== Find occurrences of 'idleTimeoutMinutes' in file ==="
rg -n "idleTimeoutMinutes" "$FILE" || true
echo
echo "=== Find occurrences of 'as Record<string, unknown>' in repo (scoped) ==="
rg -n "as\s+Record<string,\s*unknown>\s*\|\s*undefined" "$FILE" || true
echo
echo "=== Find TypeScript 'state' typing context in file ==="
rg -n "type .*State|interface .*State|const state|state\s*:" "$FILE" || trueRepository: tale-project/tale
Length of output: 159
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx"
if [ ! -f "$FILE" ]; then
echo "Missing file: $FILE"
exit 1
fi
echo "=== File head (first 160 lines) ==="
cat -n "$FILE" | sed -n '1,160p'
echo
echo "=== Extract lines 15-55 ==="
cat -n "$FILE" | sed -n '15,55p'
echo
echo "=== Find occurrences of 'vi.hoisted' in file ==="
rg -n "vi\.hoisted" "$FILE" || true
echo
echo "=== Find occurrences of 'idleTimeoutMinutes' in file ==="
rg -n "idleTimeoutMinutes" "$FILE" || true
echo
echo "=== Find occurrences of the specific cast pattern in file ==="
rg -n "as\s+Record<string,\s*unknown>\s*\|\s*undefined" "$FILE" || true
echo
echo "=== Find TypeScript typing context for state in file ==="
rg -n "type .*State|interface .*State|const state|state\s*:" "$FILE" || trueRepository: tale-project/tale
Length of output: 6239
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Search for idleTimeoutMinutes definitions/usages (limit output) ==="
rg -n "idleTimeoutMinutes" . --hidden --glob '!.git/*' | head -n 80
echo
echo "=== Search for governance policy config typing ==="
rg -n "enabled:\s*true|enabled:\s*false|config\s*:\s*{|\bconfig\b" services/platform/app/features/settings/governance -S --hidden --glob '!.git/*' | head -n 120
echo
echo "=== Locate SessionIdleTimeoutEditor and related types ==="
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx"
if [ -f "$FILE" ]; then
echo "Found $FILE"
sed -n '1,220p' "$FILE"
else
echo "Missing $FILE"
fi
echo
echo "=== Search queries hook return type ==="
rg -n "useGovernancePolicy" services/platform/app/features/settings/governance -S --hidden --glob '!.git/*' | head -n 80Repository: tale-project/tale
Length of output: 3629
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the component with nearby relevant types/usages
COMP="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx"
echo "=== Component: $COMP (relevant sections) ==="
if [ -f "$COMP" ]; then
# Print first 260 lines (file is likely small); if too big, we’ll narrow later.
cat -n "$COMP" | sed -n '1,260p'
else
echo "Missing $COMP"
fi
echo
echo "=== Shared policy types: services/platform/lib/shared/session-idle.ts (around policy typing) ==="
SHARED="services/platform/lib/shared/session-idle.ts"
if [ -f "$SHARED" ]; then
rg -n "policy\s*:\s*|idleTimeoutMinutes" "$SHARED"
cat -n "$SHARED" | sed -n '110,190p'
fi
echo
echo "=== Shared governance schema: services/platform/lib/shared/schemas/governance.ts (around idleTimeoutMinutes) ==="
SCHEMA="services/platform/lib/shared/schemas/governance.ts"
if [ -f "$SCHEMA" ]; then
rg -n "idleTimeoutMinutes" "$SCHEMA"
cat -n "$SCHEMA" | sed -n '320,420p'
fi
echo
echo "=== Queries hook: services/platform/app/features/settings/governance/hooks/queries.* (find useGovernancePolicy) ==="
# find likely file(s)
fd -e ts -e tsx -e js -e jsx "queries" services/platform/app/features/settings/governance -t f || true
# Then search for useGovernancePolicy
rg -n "useGovernancePolicy" services/platform/app/features/settings/governance -S || trueRepository: tale-project/tale
Length of output: 24998
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect useGovernancePolicy implementation + return typing
QFILE="services/platform/app/features/settings/governance/hooks/queries.ts"
echo "=== queries.ts: first 220 lines ==="
cat -n "$QFILE" | sed -n '1,220p'
echo
echo "=== queries.ts: around useGovernancePolicy function ==="
# Find line of export function useGovernancePolicy
LINE=$(rg -n "export function useGovernancePolicy" "$QFILE" | cut -d: -f1 | head -n 1)
echo "useGovernancePolicy line: $LINE"
START=$((LINE-40))
END=$((LINE+120))
cat -n "$QFILE" | sed -n "${START},${END}p"
echo
echo "=== Look for governance policy type definitions in this folder (limit) ==="
rg -n "type .*Policy|interface .*Policy|config:" services/platform/app/features/settings/governance/hooks -S || true
echo
echo "=== Find any useGovernancePolicy return type helpers referenced ==="
rg -n "ReturnType<typeof useGovernancePolicy>|policyType|governance" services/platform/app/features/settings/governance/hooks/queries.ts -S || true
echo
echo "=== Search other governance editor tests for 'satisfies' usage in fixtures ==="
rg -n "satisfies .*SessionIdleTimeoutConfig|satisfies .*Policy|as .*Record<string, unknown>" services/platform/app/features/settings/governance/components -S || trueRepository: tale-project/tale
Length of output: 18533
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Locate getPolicy query in convex governance schema ==="
# Find where api.governance.queries.getPolicy is defined/typed
rg -n "getPolicy" services/platform/convex -S --hidden --glob '!.git/*' | head -n 80
echo
echo "=== Inspect services/platform/convex/governance/schema.* around policy/config typing ==="
# likely files
fd -e ts -e tsx -e js -e cts -e mts "schema" services/platform/convex/governance -t f --max-results 20 || true
# show likely governance schema file content around GOVERNANCE_POLICY_TYPES and config
SCHEMAFILE=$(rg -l "GOVERNANCE_POLICY_TYPES" services/platform/convex/governance --hidden --glob '!.git/*' | head -n 1 || true)
echo "Schema file: $SCHEMAFILE"
if [ -n "$SCHEMAFILE" ] && [ -f "$SCHEMAFILE" ]; then
cat -n "$SCHEMAFILE" | sed -n '1,220p'
fi
echo
echo "=== Search for 'config:' type on governance policy rows ==="
rg -n "config\s*:\s*|config\?\s*:" services/platform/convex/governance -S --hidden --glob '!.git/*' | head -n 120
echo
echo "=== Search for SessionIdleTimeoutConfig in convex side ==="
rg -n "SessionIdleTimeoutConfig|sessionIdleTimeoutConfigSchema" services/platform/convex/governance -S --hidden --glob '!.git/*' | head -n 80Repository: tale-project/tale
Length of output: 24489
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Search for SessionIdleTimeoutConfig in repo (limit) ==="
rg -n "SessionIdleTimeoutConfig" services/platform/app/features/settings/governance/components --hidden --glob '!.git/*' | head -n 80
echo
echo "=== Search for 'satisfies .*SessionIdleTimeoutConfig' ==="
rg -n "satisfies\s+SessionIdleTimeoutConfig" . --hidden --glob '!.git/*' | head -n 80
echo
echo "=== Inspect a similar test that avoids/uses satisfies for config types ==="
# pick pii-config.test.tsx which likely uses satisfies or casts
for f in \
services/platform/app/features/settings/governance/components/personalization-policy-editor.test.tsx \
services/platform/app/features/settings/governance/components/password-policy-editor.test.tsx \
services/platform/app/features/settings/governance/components/pii-config.test.tsx \
services/platform/app/features/settings/governance/components/login-policy-editor.test.tsx \
; do
if [ -f "$f" ]; then
echo "--- $f (head 80 lines) ---"
cat -n "$f" | sed -n '1,90p'
fi
doneRepository: tale-project/tale
Length of output: 16216
Fix the session-idle-timeout test fixture typing (remove the broad cast).
In services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx (lines 22-28), state.config is initialized with as Record<string, unknown> | undefined, but SessionIdleTimeoutEditor parses/depends on the specific SessionIdleTimeoutConfig shape (enabled + idleTimeoutMinutes). Type the fixture as SessionIdleTimeoutConfig | undefined (and use satisfies SessionIdleTimeoutConfig for the initial object) so fixture drift is caught and you don’t rely on the unknown/broad record assertion.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx`
around lines 22 - 29, The test fixture types are too broad: replace the cast on
state.config (currently "as Record<string, unknown> | undefined") with the
concrete SessionIdleTimeoutConfig type so the fixture matches what
SessionIdleTimeoutEditor expects; change the hoisted state declaration to type
state.config as SessionIdleTimeoutConfig | undefined and annotate the literal
using "satisfies SessionIdleTimeoutConfig" for the initial object (enabled +
idleTimeoutMinutes) to catch shape drift and remove the broad Record<string,
unknown> | undefined assertion.
| it('renders the section heading (static text, always real)', () => { | ||
| setLoaded(); | ||
| render(<SessionIdleTimeoutEditor organizationId="org-1" />); | ||
| expect( | ||
| screen.getByRole('heading', { name: /session idle timeout/i }), | ||
| ).toBeInTheDocument(); |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Stop asserting this heading against an English literal.
Both heading checks hardcode the current English copy. That makes the test brittle across locales and violates the i18n rule for tests. Resolve the expected label through the translation layer, or assert the section structure without pinning the English text.
As per coding guidelines, "Every user-facing string goes through the translation layer — never compare against an English literal in code, tests, stories, or comments."
Also applies to: 93-98
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx`
around lines 62 - 67, The test in session-idle-timeout-editor.test.tsx asserts
the heading by an English literal which breaks i18n; update the spec that uses
setLoaded(), render(<SessionIdleTimeoutEditor ... />) and
screen.getByRole('heading', ...) to either resolve the expected label via the
translation helper used in tests (e.g., call the same i18n/t function or import
the session idle timeout key) and assert against that translated string, or
remove the language dependency and assert structure only (e.g.,
getByRole('heading') with a positional/semantic check or getByRole + within(...)
to verify children/components) so the assertion no longer pins the English text.
| const schema = useMemo( | ||
| () => | ||
| z.object({ | ||
| idleTimeoutMinutes: z | ||
| .number() | ||
| .int() | ||
| .min( | ||
| SESSION_IDLE_TIMEOUT_MIN_MINUTES, | ||
| t('sessionIdleTimeout.invalid'), | ||
| ) | ||
| .max( | ||
| SESSION_IDLE_TIMEOUT_MAX_MINUTES, | ||
| t('sessionIdleTimeout.invalid'), | ||
| ), | ||
| }), | ||
| [t], | ||
| ); |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Zod 4.3.6 z.number({ error: ... }) invalid type error syntax int({ error: ... })
💡 Result:
In Zod 4.3.6, the way you customize error messages has been unified under a single error parameter [1]. The Zod 3 approach of using specific keys like invalid_type_error or errorMap has been replaced by this unified error function [1]. For z.number, you can customize errors by passing an error parameter to the schema constructor, and for specific constraints like.int, you pass the custom error directly to that method [2][1]. Examples of this syntax in Zod 4.3.6: // Customizing the base number type error const schema = z.number({ error: (issue) => issue.input === undefined? "Required": "Must be a number" }); // Customizing the.int constraint error const intSchema = z.number.int("Must be an integer"); Key changes to note for Zod 4.x: 1. Unified Error Parameter: The error parameter now accepts a function that receives an issue object, allowing you to access details like issue.code, issue.input, and issue.path to return dynamic or custom messages [3][1]. 2. Method-Specific Customization: Constraints (like.int,.min, or.max) now accept a string or an error function directly as an argument, which overrides the default error for that specific validation step [2][4][1]. 3. Global Customization: If you need to set a default error message format globally, you can use z.config({ customError:... }) [2][5]. This system is designed to be more explicit and flexible than the previous Zod 3 errorMap approach [2]. If you want to return a simple string for an error, you can just provide the string directly to the method, and Zod will handle it as the message [2].
Citations:
- 1: https://zod.dev/v4
- 2: [v4] error behaves different than errorMap no longer give us a default error message colinhacks/zod#4893
- 3: https://zod.dev/error-customization?id=the-error-param
- 4: https://github.com/colinhacks/zod/blob/9575cfecbabeb149a4991f931cf24f685ea8c55e/README.md
- 5: [V4] Confusing error message with
zod.numberandInfinitycolinhacks/zod#5186
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate and print relevant parts of the file
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx"
if [ -f "$FILE" ]; then
echo "== File exists: $FILE =="
sed -n '1,220p' "$FILE" | nl -ba | sed -n '1,220p'
else
echo "== File not found: $FILE =="
fi
# Find where Zod is configured or customError/customErrorMap is set
rg -n "zod\.|z\.config|customError|errorMap|setErrorMap|z\.setErrorMap|custom error" services/platform -S || true
# Find any global translation usage for zod errors
rg -n "sessionIdleTimeout\.invalid|idleTimeoutMinutes|SESSION_IDLE_TIMEOUT" services/platform/app/features/settings/governance -S || true
# Search for Zod schema wrappers used for forms, error formatting, or translation
rg -n "zodResolver|`@hookform/resolvers`|schemaResolver|safeParse|parseAsync|issue\.message|issue\.code" services/platform/app -S || trueRepository: tale-project/tale
Length of output: 235
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx"
if [ -f "$FILE" ]; then
echo "== File exists: $FILE =="
sed -n '1,260p' "$FILE" | nl -ba
else
echo "== File not found: $FILE =="
fi
# Look for any global Zod error customization that could already localize non-numeric errors
rg -n "z\.config\\(|customError|setErrorMap|errorMap" services/platform -S || true
# Find all uses of the validation key to see how messages are handled elsewhere
rg -n "sessionIdleTimeout\\.invalid|idleTimeoutMinutes|SESSION_IDLE_TIMEOUT" services/platform/app/features/settings/governance -S || true
# Check form/Zod resolver wiring to see how issue messages are displayed
rg -n "zodResolver|`@hookform/resolvers`|safeParse\\(|parse\\(|issue\\.message|issue\\.code" services/platform/app -S || trueRepository: tale-project/tale
Length of output: 235
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx"
if [ -f "$FILE" ]; then
echo "== File exists: $FILE =="
sed -n '1,260p' "$FILE" | cat -n
else
echo "== File not found: $FILE =="
fi
echo "== Zod global customization search =="
rg -n "z\.config\\(|customError|setErrorMap|errorMap|z\.setErrorMap" services/platform -S || true
echo "== Form/zod resolver wiring search =="
rg -n "zodResolver|`@hookform/resolvers`|safeParse\\(|parseAsync\\(|issue\\.message|issue\\.code" services/platform/app -S || true
echo "== This feature: translation key usage =="
rg -n "sessionIdleTimeout\\.invalid|idleTimeoutMinutes|SESSION_IDLE_TIMEOUT" services/platform/app/features/settings/governance -S || trueRepository: tale-project/tale
Length of output: 26338
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the form editor wrapper to see how zod errors are mapped to react-hook-form errors/messages
EDITOR_FILE="services/platform/app/components/ui/editor/use-form-editor.ts"
if [ -f "$EDITOR_FILE" ]; then
echo "== $EDITOR_FILE =="
sed -n '1,220p' "$EDITOR_FILE" | cat -n
fi
# Inspect Input component to see how errorMessage is rendered
INPUT_FILE="services/platform/app/components/ui/forms/input.tsx"
if [ -f "$INPUT_FILE" ]; then
echo "== $INPUT_FILE =="
sed -n '1,220p' "$INPUT_FILE" | cat -n
else
# fallback: find input component
fd -a "input.tsx" services/platform/app/components/ui/forms 2>/dev/null || true
fd -a "Input" services/platform/app/components/ui/forms 2>/dev/null || true
fi
# Inspect this feature's test file for expectations around invalid/non-numeric errors
TEST_FILE="services/platform/app/features/settings/governance/components/session-idle-timeout-editor.test.tsx"
if [ -f "$TEST_FILE" ]; then
echo "== $TEST_FILE =="
sed -n '1,220p' "$TEST_FILE" | cat -n
fiRepository: tale-project/tale
Length of output: 23385
🏁 Script executed:
#!/bin/bash
set -euo pipefail
node <<'NODE'
const { z } = require('zod');
function show(label, schema, value) {
const result = schema.safeParse({ idleTimeoutMinutes: value });
if (result.success) {
console.log(label, 'SUCCESS', value);
return;
}
const issues = result.error.issues;
console.log('\n' + label);
console.log('value:', value, 'typeof:', typeof value);
for (const i of issues) {
console.log({
code: i.code,
path: i.path,
message: i.message,
received: i.received,
expected: i.expected,
input: i.input,
});
}
}
const MIN=1, MAX=60;
const tInvalid = 'sessionIdleTimeout.invalid'; // stand-in for t(...)
const current = z.object({
idleTimeoutMinutes: z
.number()
.int()
.min(MIN, tInvalid)
.max(MAX, tInvalid),
});
show('current: NaN', current, NaN);
show('current: empty string', current, '');
show('current: undefined', current, undefined);
show('current: null', current, null);
const proposed = z.object({
idleTimeoutMinutes: z
.number({ error: tInvalid })
.int({ error: tInvalid })
.min(MIN, tInvalid)
.max(MAX, tInvalid),
});
show('proposed: NaN', proposed, NaN);
show('proposed: empty string', proposed, '');
show('proposed: undefined', proposed, undefined);
show('proposed: null', proposed, null);
let intArgForms = [];
try {
intArgForms.push({ label: "int({error})", schema: z.number().int({ error: tInvalid }) });
} catch (e) {
console.log('\nint({error}) threw:', e.message);
}
try {
intArgForms.push({ label: "int(string)", schema: z.number().int(tInvalid) });
} catch (e) {
console.log('\nint(string) threw:', e.message);
}
try {
intArgForms.push({ label: "int({message})", schema: z.number().int({ message: tInvalid }) });
} catch (e) {
console.log('\nint({message}) threw:', e.message);
}
for (const f of intArgForms) {
const s = z.object({ idleTimeoutMinutes: f.schema });
show('proposed form: ' + f.label + ': NaN', s, NaN);
}
NODERepository: tale-project/tale
Length of output: 913
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n "z\\.number\\(\\{[^}]*error" services/platform -S || true
rg -n "\\.int\\(\\{[^}]*error" services/platform -S || true
rg -n "\\.int\\(" services/platform/app -S | head -n 50 || true
# also check for other zod error customization patterns
rg -n "customError|errorMap|issue\\.message|z\\.config\\(" services/platform -S || trueRepository: tale-project/tale
Length of output: 1358
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n "z\\.number\\(\\{[^}]*error" services/platform -S || true
rg -n "\\.int\\(\\{[^}]*error" services/platform -S || true
rg -n "\\.int\\([^)]*error" services/platform -S || true
rg -n "\\.int\\([\"']" services/platform -S || true
rg -n "customError|errorMap|z\\.config\\(|setErrorMap" services/platform -S || trueRepository: tale-project/tale
Length of output: 193
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show how other code customizes Zod int errors
sed -n '1,120p' services/platform/app/features/settings/governance/data-subject-requests/extend-deadline-dialog.tsx | cat -n
echo "----"
sed -n '1,140p' services/platform/app/features/settings/governance/components/login-policy-editor.tsx | cat -n | sed -n '90,150p' || true
echo "----"
sed -n '60,120p' services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx | cat -n
echo "----"
sed -n '60,120p' services/platform/app/features/settings/governance/components/password-policy-editor.tsx | cat -nRepository: tale-project/tale
Length of output: 11052
Translate NaN/non-numeric validation errors for idleTimeoutMinutes
register('idleTimeoutMinutes', { valueAsNumber: true })turns an empty field intoNaN, but the schema only localizes the.min/.maxbranches; Zod’s basez.number()/.int()failures will use the default (English) message inerrors.idleTimeoutMinutes?.messageinstead oft('sessionIdleTimeout.invalid')(session-idle-timeout-editor.tsx ~77-93, also applies to input at ~197).
Suggested fix
const schema = useMemo(
() =>
z.object({
idleTimeoutMinutes: z
.number({ message: t('sessionIdleTimeout.invalid') })
.int(t('sessionIdleTimeout.invalid'))
.min(SESSION_IDLE_TIMEOUT_MIN_MINUTES, t('sessionIdleTimeout.invalid'))
.max(SESSION_IDLE_TIMEOUT_MAX_MINUTES, t('sessionIdleTimeout.invalid')),
}),
[t],
);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@services/platform/app/features/settings/governance/components/session-idle-timeout-editor.tsx`
around lines 77 - 93, The Zod schema for idleTimeoutMinutes currently only
localizes .min/.max errors so empty or non-numeric inputs produce default
English messages; update the schema inside useMemo (the schema constant that
defines idleTimeoutMinutes) to pass the localized message to z.number() and to
.int() as well (use t('sessionIdleTimeout.invalid')) so all validation failures
— non-number, non-int, too small, too large — produce the translated message;
ensure you keep references to SESSION_IDLE_TIMEOUT_MIN_MINUTES and
SESSION_IDLE_TIMEOUT_MAX_MINUTES unchanged.
| const { data: policyRow } = useConvexQuery( | ||
| api.governance.queries.getPolicy, | ||
| organizationId | ||
| ? { organizationId, policyType: 'session_idle_timeout' as const } | ||
| : 'skip', | ||
| ); | ||
|
|
||
| // Effective minutes drive a primitive effect dep, so the listeners/timer are | ||
| // rebuilt only when the resolved window actually changes (e.g. an admin | ||
| // edits the policy live) — not on every render. | ||
| const minutes = useMemo(() => { | ||
| const envRaw = getEnv('SESSION_IDLE_TIMEOUT_MINUTES'); | ||
| const envMinutes = | ||
| typeof envRaw === 'number' && Number.isFinite(envRaw) && envRaw > 0 | ||
| ? envRaw | ||
| : null; | ||
| const parsed = policyRow?.config | ||
| ? sessionIdleTimeoutConfigSchema.safeParse(policyRow.config) | ||
| : null; | ||
| const policy = parsed?.success ? parsed.data : null; | ||
| return resolveEffectiveIdleMinutes({ policy, envMinutes }); | ||
| }, [policyRow]); |
There was a problem hiding this comment.
Wait for the org policy query before arming the watchdog.
When organizationId is present but getPolicy is still loading, policyRow is undefined, so this path falls back to the env cap and starts the longer timer immediately. That means a member who is already past the org's tighter timeout can stay signed in until the query returns, which breaks the new per-org window on first load. Return null while the policy lookup is unresolved, or plumb loading state through useConvexQuery and only resolve minutes once the org policy is known.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@services/platform/app/hooks/use-session-idle-watchdog.tsx` around lines 61 -
82, When organizationId is set we must not fall back to envMinutes while the org
policy query is still loading: update the useMemo that computes minutes (the
block that references useConvexQuery/api.governance.queries.getPolicy,
policyRow, resolveEffectiveIdleMinutes) so that if organizationId is present and
policyRow is strictly undefined (query unresolved) the memo returns null (or
otherwise short-circuits) instead of computing from envMinutes; once policyRow
is resolved (null or a value) continue to parse with
sessionIdleTimeoutConfigSchema and call resolveEffectiveIdleMinutes as before.
Ensure the logic only treats policyRow === undefined as loading and does not
change behavior when policyRow is null (no policy).
| if (args.policyType === 'session_idle_timeout') { | ||
| const parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config); | ||
| if (!parsed.success) { | ||
| throw new Error( | ||
| `Invalid session idle timeout configuration: ${parsed.error.message}`, | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="services/platform/convex/governance/mutations.ts"
echo "== session_idle_timeout validation branch =="
sed -n '236,248p' "$file"
echo
echo "== configEnabled extraction and persistence =="
sed -n '343,367p' "$file"Repository: tale-project/tale
Length of output: 1313
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
# try to locate the schema definition
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas/governance.ts services/platform/lib/shared/schemas -g"*.ts" || true
# print surrounding lines where it is defined
python3 - <<'PY'
import subprocess, re, os, textwrap, sys, pathlib, json
paths = [
"services/platform/lib/shared/schemas/governance.ts"
]
# fallback: rg already told us; but we will just cat around the definition line for governance.ts if present
path="services/platform/lib/shared/schemas/governance.ts"
if os.path.exists(path):
# find line number
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
m=re.search(r":(\d+):",out)
if m:
ln=int(m.group(1))
start=max(1,ln-20); end=ln+60
subprocess.run(["sed","-n",f"{start},{end}p",path],check=False)
PY
echo
echo "== mutations write path around configEnabled/enabled/config =="
sed -n '300,390p' services/platform/convex/governance/mutations.tsRepository: tale-project/tale
Length of output: 4479
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas/governance.ts services/platform/lib/shared/schemas -g"*.ts" || true
python3 - <<'PY'
import subprocess, re, os
path="services/platform/lib/shared/schemas/governance.ts"
if os.path.exists(path):
try:
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
except subprocess.CalledProcessError:
sys_exit=False
PY
PYRepository: tale-project/tale
Length of output: 1080
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas -g"*.ts" || true
echo
echo "== governance.ts snippet around sessionIdleTimeoutConfigSchema =="
python3 - <<'PY'
import subprocess, re, os, sys
path="services/platform/lib/shared/schemas/governance.ts"
if not os.path.exists(path):
sys.exit(0)
try:
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
except subprocess.CalledProcessError:
sys.exit(0)
m=re.search(r":(\d+):",out)
if not m:
sys.exit(0)
ln=int(m.group(1))
start=max(1,ln-20); end=ln+80
subprocess.run(["sed","-n",f"{start},{end}p",path],check=False)
PY
echo
echo "== mutations write path around configEnabled/enabled/config =="
sed -n '320,390p' services/platform/convex/governance/mutations.tsRepository: tale-project/tale
Length of output: 3216
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas -g"*.ts" || true
echo
echo "== governance.ts snippet around sessionIdleTimeoutConfigSchema =="
python3 - <<'PY'
import subprocess, re, os, sys
path="services/platform/lib/shared/schemas/governance.ts"
if not os.path.exists(path):
sys.exit(0)
try:
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
except subprocess.CalledProcessError:
sys.exit(0)
m=re.search(r":(\d+):",out)
if not m:
sys.exit(0)
ln=int(m.group(1))
start=max(1,ln-20); end=ln+80
subprocess.run(["sed","-n",f"{start},{end}p",path],check=False)
PY
echo
echo "== mutations write path around configEnabled/enabled/config =="
sed -n '320,390p' services/platform/convex/governance/mutations.tsRepository: tale-project/tale
Length of output: 3216
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas -g"*.ts" || true
echo
echo "== governance.ts snippet around sessionIdleTimeoutConfigSchema =="
python3 - <<'PY'
import subprocess, re, os, sys
path="services/platform/lib/shared/schemas/governance.ts"
if not os.path.exists(path):
sys.exit(0)
try:
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
except subprocess.CalledProcessError:
sys.exit(0)
m=re.search(r":(\d+):",out)
if not m:
sys.exit(0)
ln=int(m.group(1))
start=max(1,ln-20); end=ln+80
subprocess.run(["sed","-n",f"{start},{end}p",path],check=False)
PY
echo
echo "== mutations write path around configEnabled/enabled/config =="
sed -n '320,390p' services/platform/convex/governance/mutations.tsRepository: tale-project/tale
Length of output: 3216
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== governance shared schema for sessionIdleTimeoutConfigSchema =="
rg -n "sessionIdleTimeoutConfigSchema" -S services/platform/lib/shared/schemas -g"*.ts" || true
echo
echo "== governance.ts snippet around sessionIdleTimeoutConfigSchema =="
python3 - <<'PY'
import subprocess, re, os, sys
path="services/platform/lib/shared/schemas/governance.ts"
if not os.path.exists(path):
sys.exit(0)
try:
out=subprocess.check_output(["rg","-n","sessionIdleTimeoutConfigSchema",path],text=True)
except subprocess.CalledProcessError:
sys.exit(0)
m=re.search(r":(\d+):",out)
if not m:
sys.exit(0)
ln=int(m.group(1))
start=max(1,ln-20); end=ln+80
subprocess.run(["sed","-n",f"{start},{end}p",path],check=False)
PY
echo
echo "== mutations write path around configEnabled/enabled/config =="
sed -n '320,390p' services/platform/convex/governance/mutations.tsRepository: tale-project/tale
Length of output: 3216
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="services/platform/lib/shared/schemas/governance.ts"
echo "== sessionIdleTimeoutConfigSchema definition =="
sed -n '340,410p' "$file"
echo
echo "== any nearby helper/test about sessionIdleTimeoutConfigSchema =="
sed -n '410,470p' "$file"Repository: tale-project/tale
Length of output: 4877
Persist normalized sessionIdleTimeoutConfigSchema output (parsed.data) instead of raw args.config.
In services/platform/convex/governance/mutations.ts, the session_idle_timeout branch validates with sessionIdleTimeoutConfigSchema.safeParse(args.config) but discards the result; since the schema provides defaults (enabled and idleTimeoutMinutes), safeParse can succeed for inputs like { enabled: true } while the later write still stores config: args.config and records newState.config: args.config. This can leave persisted policy config without idleTimeoutMinutes (and with any unknown keys), diverging from the shared schema contract.
Suggested fix
if (args.policyType === 'session_idle_timeout') {
const parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config);
if (!parsed.success) {
throw new Error(
`Invalid session idle timeout configuration: ${parsed.error.message}`,
);
}
+ args.config = parsed.data;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (args.policyType === 'session_idle_timeout') { | |
| const parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config); | |
| if (!parsed.success) { | |
| throw new Error( | |
| `Invalid session idle timeout configuration: ${parsed.error.message}`, | |
| ); | |
| } | |
| } | |
| if (args.policyType === 'session_idle_timeout') { | |
| const parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config); | |
| if (!parsed.success) { | |
| throw new Error( | |
| `Invalid session idle timeout configuration: ${parsed.error.message}`, | |
| ); | |
| } | |
| args.config = parsed.data; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@services/platform/convex/governance/mutations.ts` around lines 239 - 246, The
session_idle_timeout branch validates args.config with
sessionIdleTimeoutConfigSchema.safeParse but still persists the raw args.config;
change the code to persist the normalized parsed.data instead: after const
parsed = sessionIdleTimeoutConfigSchema.safeParse(args.config) (and after the
success check) use parsed.data wherever the code currently writes config (e.g.,
the write/update that sets config and newState.config) so defaults and validated
fields (enabled, idleTimeoutMinutes) are stored and unknown keys are excluded.
- Watchdog: don't arm on the (looser) env window while the org policy query is still loading — a member already past the org's tighter timeout would otherwise linger until the query resolves. Wait for the policy (`policyRow === undefined` = in-flight) before resolving the effective window. - upsertPolicy: persist the normalized `session_idle_timeout` config (`parsed.data`, schema defaults applied) instead of the raw input. - Editor test: type the fixture as SessionIdleTimeoutConfig (not a broad Record cast); assert the section heading structurally instead of pinning the English literal (i18n rule). - Add a watchdog test for the loading-state no-op.
|
CodeRabbit findings addressed in the follow-up commit:
|
What
Adds a
session_idle_timeoutgovernance policy so org admins can configure the inactivity window from Settings → Security, closing the acceptance gap on #1502 (the merged work — #1808/#1810 — was deployment-env-var only).Architecture (per maintainer decision: per-org policy + env backstop):
SESSION_IDLE_TIMEOUT_MINUTESstays the server-side sliding-window control (unchanged Better Auth static config, covers all session types) and is the hard cap — an org may only tighten it, never extend past it.org policy × env backstopinstead of env alone.Changes
resolveEffectiveIdleMinutes()— pure resolver combining env backstop × org policy; shared by the watchdog and Convex, unit-tested.sessionIdleTimeoutConfigSchema+session_idle_timeoutpolicy type (shared + Convex schema kept in sync).upsertPolicyvalidates it and audit-logs the change via the existing path.SessionIdleTimeoutEditormounted in Settings → Security (mirrorsLoginPolicyEditor), with loader preload.Tests
bun run check: format + lint + typecheck clean; full test suite green except 3 pre-existing concurrent-load timeouts in unrelated suites (pass 30/30 in isolation).Notes
Server-side enforcement intentionally stays on the env backstop (the trusted-headers session-creation path lacks cheap org context); per-org tightening is delivered client-side. True per-request per-org server enforcement was considered and declined to preserve the JWT fast path.
Part of the #1803 security/compliance epic.
Summary by CodeRabbit
Release Notes
New Features
Tests
Localization