@aithorized/core 0.2.0 → 0.4.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/dist/index.d.ts CHANGED
@@ -11,6 +11,10 @@ export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519Publ
11
11
  export type { EcP256Jwk, Ed25519Jwk, JwkThumbprintJwk } from './crypto/jwk.js';
12
12
  export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
13
13
  export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
14
+ export { explainEvaluation, simulatePolicy } from './policy/explain.js';
15
+ export type { RuleEvaluationTrace, ExplainResult, SimulationSample, SimulationTransitionSample, SimulationTransition, SimulationSummary } from './policy/explain.js';
16
+ export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './policy/packs.js';
17
+ export type { PolicyPackId, PolicyPack } from './policy/packs.js';
14
18
  export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
15
19
  export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
16
20
  export type { CommandAnalysis, CommandIntent, CommandPatternSuggestion, DetectedFile, DetectedPath, DetectedTool } from './policy/command-analyzer.js';
@@ -27,5 +31,9 @@ export { verifyDecisionBundle, keyClassCanDecide, KEY_CLASSES, DIRECTORY_DOMAIN,
27
31
  export type { RequestStatus, KeyClass, DeviceDirectoryKey, DeviceKeyDirectory, DecisionObject, DecisionSignature, DecisionBundle, EditableField, VerifyDecisionOptions, VerificationResult } from './lifecycle/verify.js';
28
32
  export { redactForPreview, REDACTED_VALUE, DEFAULT_KEY_GLOBS } from './lifecycle/redact.js';
29
33
  export type { RedactionConfig, PreviewField, RedactionResult } from './lifecycle/redact.js';
34
+ export { createUnifiedDiffPreview, runPreviewProviders } from './lifecycle/preview.js';
35
+ export type { VerifiedPreview, PreviewProvider } from './lifecycle/preview.js';
36
+ export { computeBatchHash, verifyBatchInclusion } from './lifecycle/batch.js';
37
+ export type { BatchDecision } from './lifecycle/batch.js';
30
38
  export { CoreError, JcsError, CryptoError, PolicyError, VerificationError } from './errors.js';
31
39
  export type { VerificationCode } from './errors.js';
package/dist/index.js CHANGED
@@ -10,6 +10,8 @@ export { sha256, base64urlEncode, base64urlDecode, payloadHash, feedbackHash, co
10
10
  export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519PublicKeyToKeyObject, ed25519PrivateKeyToKeyObject, keyObjectToJwk } from './crypto/jwk.js';
11
11
  export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
12
12
  export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
13
+ export { explainEvaluation, simulatePolicy } from './policy/explain.js';
14
+ export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './policy/packs.js';
13
15
  export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
14
16
  export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
15
17
  export { mergePolicies, strictnessOf } from './policy/merge.js';
@@ -19,4 +21,6 @@ export { loadPolicyYaml, parsePolicyJson, validateRules } from './policy/load.js
19
21
  export { CLOCK_SKEW_ALLOWANCE_MS, MAX_CREATE_ATTEMPTS, createLocalDeadline, shouldRetryCreate, awaitResolutionBeforeDeadline } from './lifecycle/deadline.js';
20
22
  export { verifyDecisionBundle, keyClassCanDecide, KEY_CLASSES, DIRECTORY_DOMAIN, directorySigningInput, verifyDirectory } from './lifecycle/verify.js';
21
23
  export { redactForPreview, REDACTED_VALUE, DEFAULT_KEY_GLOBS } from './lifecycle/redact.js';
24
+ export { createUnifiedDiffPreview, runPreviewProviders } from './lifecycle/preview.js';
25
+ export { computeBatchHash, verifyBatchInclusion } from './lifecycle/batch.js';
22
26
  export { CoreError, JcsError, CryptoError, PolicyError, VerificationError } from './errors.js';
@@ -0,0 +1,18 @@
1
+ export interface BatchDecision {
2
+ requestIds: string[];
3
+ payloadHashes: string[];
4
+ batchHash: string;
5
+ decision: 'APPROVE' | 'REJECT';
6
+ signature: string;
7
+ keyId: string;
8
+ signerUserId?: string;
9
+ }
10
+ /**
11
+ * Deterministic hash over a sorted list of payloadHashes for batch approvals.
12
+ */
13
+ export declare function computeBatchHash(payloadHashes: readonly string[]): string;
14
+ /**
15
+ * Verify that a specific requestId + payloadHash belongs to a batch decision
16
+ * and that the batchHash matches the canonical sorted payloadHashes.
17
+ */
18
+ export declare function verifyBatchInclusion(batch: Pick<BatchDecision, 'requestIds' | 'payloadHashes' | 'batchHash'>, requestId: string, requestPayloadHash: string): boolean;
@@ -0,0 +1,20 @@
1
+ import { jcs } from '../crypto/jcs.js';
2
+ import { base64urlEncode, sha256 } from '../crypto/hash.js';
3
+ /**
4
+ * Deterministic hash over a sorted list of payloadHashes for batch approvals.
5
+ */
6
+ export function computeBatchHash(payloadHashes) {
7
+ const canonical = jcs([...payloadHashes].sort());
8
+ return base64urlEncode(sha256(Buffer.from(canonical, 'utf8')));
9
+ }
10
+ /**
11
+ * Verify that a specific requestId + payloadHash belongs to a batch decision
12
+ * and that the batchHash matches the canonical sorted payloadHashes.
13
+ */
14
+ export function verifyBatchInclusion(batch, requestId, requestPayloadHash) {
15
+ if (!batch.requestIds.includes(requestId))
16
+ return false;
17
+ if (!batch.payloadHashes.includes(requestPayloadHash))
18
+ return false;
19
+ return computeBatchHash(batch.payloadHashes) === batch.batchHash;
20
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Client-side Verified Preview types & pluggable PreviewProvider runner.
3
+ * Previews are always computed deterministically outside the LLM.
4
+ */
5
+ export type VerifiedPreview = {
6
+ kind: 'diff';
7
+ title: string;
8
+ filePath?: string;
9
+ diff: string;
10
+ additions: number;
11
+ deletions: number;
12
+ } | {
13
+ kind: 'sql_impact';
14
+ title: string;
15
+ dialect: 'postgres' | 'mysql' | 'sqlite' | 'unknown';
16
+ estimatedRows?: number;
17
+ tables?: string[];
18
+ statementType: string;
19
+ readOnlyChecked: boolean;
20
+ } | {
21
+ kind: 'resource_delta';
22
+ title: string;
23
+ create: number;
24
+ update: number;
25
+ destroy: number;
26
+ resources: string[];
27
+ } | {
28
+ kind: 'summary';
29
+ title: string;
30
+ items: Array<{
31
+ label: string;
32
+ value: string;
33
+ }>;
34
+ };
35
+ export interface PreviewProvider {
36
+ name: string;
37
+ supports: (tool: string, args: Record<string, unknown>) => boolean;
38
+ generate: (tool: string, args: Record<string, unknown>) => Promise<VerifiedPreview | undefined>;
39
+ }
40
+ export declare function createUnifiedDiffPreview(filePath: string, before: string, after: string): VerifiedPreview;
41
+ export declare function runPreviewProviders(providers: readonly PreviewProvider[], tool: string, args: Record<string, unknown>, timeoutMs?: number): Promise<VerifiedPreview | undefined>;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Client-side Verified Preview types & pluggable PreviewProvider runner.
3
+ * Previews are always computed deterministically outside the LLM.
4
+ */
5
+ export function createUnifiedDiffPreview(filePath, before, after) {
6
+ const beforeLines = before.split('\n');
7
+ const afterLines = after.split('\n');
8
+ const lines = [`--- a/${filePath}`, `+++ b/${filePath}`];
9
+ let additions = 0;
10
+ let deletions = 0;
11
+ const maxLen = Math.max(beforeLines.length, afterLines.length);
12
+ for (let i = 0; i < maxLen; i++) {
13
+ const b = beforeLines[i];
14
+ const a = afterLines[i];
15
+ if (b === a) {
16
+ if (b !== undefined)
17
+ lines.push(` ${b}`);
18
+ }
19
+ else {
20
+ if (b !== undefined) {
21
+ lines.push(`-${b}`);
22
+ deletions += 1;
23
+ }
24
+ if (a !== undefined) {
25
+ lines.push(`+${a}`);
26
+ additions += 1;
27
+ }
28
+ }
29
+ }
30
+ return {
31
+ kind: 'diff',
32
+ title: `Diff: ${filePath}`,
33
+ filePath,
34
+ diff: lines.join('\n'),
35
+ additions,
36
+ deletions
37
+ };
38
+ }
39
+ export async function runPreviewProviders(providers, tool, args, timeoutMs = 1500) {
40
+ for (const provider of providers) {
41
+ if (!provider.supports(tool, args))
42
+ continue;
43
+ try {
44
+ const result = await Promise.race([
45
+ provider.generate(tool, args),
46
+ new Promise((resolve) => setTimeout(() => resolve(undefined), timeoutMs))
47
+ ]);
48
+ if (result)
49
+ return result;
50
+ }
51
+ catch {
52
+ return {
53
+ kind: 'summary',
54
+ title: 'Preview unavailable',
55
+ items: [{ label: 'Provider', value: `${provider.name} failed (fail-closed)` }]
56
+ };
57
+ }
58
+ }
59
+ return undefined;
60
+ }
@@ -28,6 +28,8 @@ export interface RedactionResult {
28
28
  redactedPaths: string[];
29
29
  }
30
30
  export declare const DEFAULT_KEY_GLOBS: string[];
31
+ /** High-confidence secret value patterns redacted by default in previews (PG-06). */
32
+ export declare const DEFAULT_VALUE_REGEXES: string[];
31
33
  /**
32
34
  * Build a redacted preview of a payload. The returned fields are for
33
35
  * display only; hashing must use the original payload.
@@ -12,9 +12,21 @@ export const DEFAULT_KEY_GLOBS = [
12
12
  '*secret*',
13
13
  '*token*',
14
14
  '*credential*',
15
- '*apiKey*',
15
+ '*apikey*',
16
16
  '*api_key*',
17
- '*privateKey*'
17
+ '*privatekey*',
18
+ '*private_key*',
19
+ '*authorization*',
20
+ '*cookie*'
21
+ ];
22
+ /** High-confidence secret value patterns redacted by default in previews (PG-06). */
23
+ export const DEFAULT_VALUE_REGEXES = [
24
+ '\\bAKIA[0-9A-Z]{16}\\b',
25
+ '\\bgh[pousr]_[A-Za-z0-9]{20,}\\b',
26
+ '\\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}\\b',
27
+ '\\bsk_(?:live|test)_[A-Za-z0-9]{16,}\\b',
28
+ '-----BEGIN [A-Z ]*PRIVATE KEY-----',
29
+ '\\bBearer\\s+[A-Za-z0-9._-]{20,}\\b'
18
30
  ];
19
31
  function escapePointer(segment) {
20
32
  return segment.replace(/~/g, '~0').replace(/\//g, '~1');
@@ -41,7 +53,8 @@ function stringPreview(value, maxLength) {
41
53
  return text;
42
54
  }
43
55
  function isSecretKey(segment, keyGlobs) {
44
- return keyGlobs.some((glob) => toolMatches(glob, segment));
56
+ const lower = segment.toLowerCase();
57
+ return keyGlobs.some((glob) => toolMatches(glob.toLowerCase(), lower));
45
58
  }
46
59
  /**
47
60
  * Walk the payload producing preview fields. A redacted node is emitted
@@ -83,7 +96,8 @@ function walk(value, pointer, segment, ctx) {
83
96
  export function redactForPreview(payload, config = {}) {
84
97
  let valueRegexes;
85
98
  try {
86
- valueRegexes = (config.valueRegexes ?? []).map((pattern) => new RegExp(pattern));
99
+ const patterns = [...DEFAULT_VALUE_REGEXES, ...(config.valueRegexes ?? [])];
100
+ valueRegexes = patterns.map((pattern) => new RegExp(pattern));
87
101
  }
88
102
  catch (err) {
89
103
  throw new Error(`invalid valueRegex: ${err.message}`, { cause: err });
@@ -4,6 +4,10 @@
4
4
  */
5
5
  export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
6
6
  export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
7
+ export { explainEvaluation, simulatePolicy } from './explain.js';
8
+ export type { RuleEvaluationTrace, ExplainResult, SimulationSample, SimulationTransitionSample, SimulationTransition, SimulationSummary } from './explain.js';
9
+ export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './packs.js';
10
+ export type { PolicyPackId, PolicyPack } from './packs.js';
7
11
  export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
8
12
  export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
9
13
  export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
@@ -4,6 +4,8 @@
4
4
  */
5
5
  export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
6
6
  export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
7
+ export { explainEvaluation, simulatePolicy } from './explain.js';
8
+ export { POLICY_PACKS, getPolicyPack, applyPolicyPack } from './packs.js';
7
9
  export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
8
10
  export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
9
11
  export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
@@ -32,6 +32,10 @@ export interface CommandAnalysis {
32
32
  flags: string[];
33
33
  intents: CommandIntent[];
34
34
  hasSensitiveTarget: boolean;
35
+ /** True when the command uses dynamic/obfuscated constructs (eval, unexpanded vars, pipe-to-shell, max depth, etc.). */
36
+ opaque: boolean;
37
+ /** Specific evasion/obfuscation signals detected during analysis. */
38
+ evasionSignals: string[];
35
39
  suggestions: CommandPatternSuggestion[];
36
40
  }
37
41
  /** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
@@ -41,5 +45,5 @@ export declare function splitShellSegments(command: string): {
41
45
  }[];
42
46
  /** Tokenize a single shell segment respecting quotes and escapes. */
43
47
  export declare function tokenizeSegment(segment: string): string[];
44
- /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, and intents. */
48
+ /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, intents, and evasion signals. */
45
49
  export declare function analyzeCommand(command: string, depth?: number): CommandAnalysis;