berget 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.env.example +5 -0
  2. package/AGENTS.md +184 -0
  3. package/TODO.md +2 -0
  4. package/blog-post.md +176 -0
  5. package/dist/index.js +11 -8
  6. package/dist/package.json +7 -2
  7. package/dist/src/commands/api-keys.js +4 -2
  8. package/dist/src/commands/chat.js +21 -11
  9. package/dist/src/commands/code.js +1424 -0
  10. package/dist/src/commands/index.js +2 -0
  11. package/dist/src/constants/command-structure.js +12 -0
  12. package/dist/src/schemas/opencode-schema.json +1121 -0
  13. package/dist/src/services/cluster-service.js +1 -1
  14. package/dist/src/utils/default-api-key.js +2 -2
  15. package/dist/src/utils/env-manager.js +86 -0
  16. package/dist/src/utils/error-handler.js +10 -3
  17. package/dist/src/utils/markdown-renderer.js +4 -4
  18. package/dist/src/utils/opencode-validator.js +122 -0
  19. package/dist/src/utils/token-manager.js +2 -2
  20. package/dist/tests/commands/chat.test.js +20 -18
  21. package/dist/tests/commands/code.test.js +414 -0
  22. package/dist/tests/utils/env-manager.test.js +148 -0
  23. package/dist/tests/utils/opencode-validator.test.js +103 -0
  24. package/index.ts +67 -32
  25. package/opencode.json +182 -0
  26. package/package.json +7 -2
  27. package/src/client.ts +20 -20
  28. package/src/commands/api-keys.ts +93 -60
  29. package/src/commands/auth.ts +4 -2
  30. package/src/commands/billing.ts +6 -3
  31. package/src/commands/chat.ts +149 -107
  32. package/src/commands/clusters.ts +2 -2
  33. package/src/commands/code.ts +1696 -0
  34. package/src/commands/index.ts +2 -0
  35. package/src/commands/models.ts +3 -3
  36. package/src/commands/users.ts +2 -2
  37. package/src/constants/command-structure.ts +112 -58
  38. package/src/schemas/opencode-schema.json +991 -0
  39. package/src/services/api-key-service.ts +1 -1
  40. package/src/services/auth-service.ts +27 -25
  41. package/src/services/chat-service.ts +26 -23
  42. package/src/services/cluster-service.ts +5 -5
  43. package/src/services/collaborator-service.ts +3 -3
  44. package/src/services/flux-service.ts +2 -2
  45. package/src/services/helm-service.ts +2 -2
  46. package/src/services/kubectl-service.ts +3 -6
  47. package/src/types/api.d.ts +1032 -1010
  48. package/src/types/json.d.ts +3 -3
  49. package/src/utils/default-api-key.ts +54 -42
  50. package/src/utils/env-manager.ts +98 -0
  51. package/src/utils/error-handler.ts +24 -15
  52. package/src/utils/logger.ts +12 -12
  53. package/src/utils/markdown-renderer.ts +18 -18
  54. package/src/utils/opencode-validator.ts +134 -0
  55. package/src/utils/token-manager.ts +35 -23
  56. package/tests/commands/chat.test.ts +43 -31
  57. package/tests/commands/code.test.ts +505 -0
  58. package/tests/utils/env-manager.test.ts +199 -0
  59. package/tests/utils/opencode-validator.test.ts +118 -0
  60. package/tsconfig.json +8 -8
  61. package/-27b-it +0 -0
  62. package/examples/README.md +0 -95
  63. package/examples/ai-review.sh +0 -30
  64. package/examples/install-global-security-hook.sh +0 -170
  65. package/examples/security-check.sh +0 -102
  66. package/examples/smart-commit.sh +0 -26
@@ -0,0 +1,118 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ validateOpenCodeConfig,
4
+ fixOpenCodeConfig,
5
+ } from '../../src/utils/opencode-validator'
6
+ import { readFileSync } from 'fs'
7
+
8
+ describe('OpenCode Validator', () => {
9
+ it('should validate a correct OpenCode configuration', () => {
10
+ const validConfig = {
11
+ $schema: 'https://opencode.ai/config.json',
12
+ username: 'test-user',
13
+ model: 'gpt-4',
14
+ agent: {
15
+ test: {
16
+ model: 'gpt-4',
17
+ temperature: 0.7,
18
+ prompt: 'Test agent',
19
+ permission: {
20
+ edit: 'allow',
21
+ bash: 'allow',
22
+ webfetch: 'allow',
23
+ },
24
+ },
25
+ },
26
+ }
27
+
28
+ const result = validateOpenCodeConfig(validConfig)
29
+ expect(result.valid).toBe(true)
30
+ expect(result.errors).toBeUndefined()
31
+ })
32
+
33
+ it('should reject invalid configuration', () => {
34
+ const invalidConfig = {
35
+ username: 123, // Should be string
36
+ model: 'gpt-4',
37
+ agent: {
38
+ test: {
39
+ model: 'gpt-4',
40
+ temperature: 'high', // Should be number
41
+ prompt: 'Test agent',
42
+ permission: {
43
+ edit: 'invalid', // Should be enum value
44
+ bash: 'allow',
45
+ webfetch: 'allow',
46
+ },
47
+ },
48
+ },
49
+ }
50
+
51
+ const result = validateOpenCodeConfig(invalidConfig)
52
+ expect(result.valid).toBe(false)
53
+ expect(result.errors).toBeDefined()
54
+ expect(result.errors!.length).toBeGreaterThan(0)
55
+ })
56
+
57
+ it('should fix common configuration issues', () => {
58
+ const configWithIssues = {
59
+ username: 'test-user',
60
+ model: 'gpt-4',
61
+ tools: {
62
+ compact: { threshold: 80000 }, // Should be boolean
63
+ },
64
+ maxTokens: 4000, // Invalid property
65
+ provider: {
66
+ berget: {
67
+ models: {
68
+ 'test-model': {
69
+ name: 'Test Model',
70
+ maxTokens: 4000, // Should be moved to limit.context
71
+ contextWindow: 8000, // Should be moved to limit.context
72
+ },
73
+ },
74
+ },
75
+ },
76
+ }
77
+
78
+ const fixed = fixOpenCodeConfig(configWithIssues)
79
+
80
+ // tools.compact should be boolean
81
+ expect(typeof fixed.tools.compact).toBe('boolean')
82
+
83
+ // maxTokens should be removed
84
+ expect(fixed.maxTokens).toBeUndefined()
85
+
86
+ // maxTokens and contextWindow should be moved to limit.context
87
+ expect(fixed.provider.berget.models['test-model'].limit).toBeDefined()
88
+ expect(fixed.provider.berget.models['test-model'].limit.context).toBe(8000)
89
+ expect(fixed.provider.berget.models['test-model'].maxTokens).toBeUndefined()
90
+ expect(
91
+ fixed.provider.berget.models['test-model'].contextWindow,
92
+ ).toBeUndefined()
93
+ })
94
+
95
+ it('should validate the current opencode.json file', () => {
96
+ try {
97
+ const currentConfig = JSON.parse(readFileSync('opencode.json', 'utf8'))
98
+
99
+ // Apply fixes to handle common issues
100
+ const fixedConfig = fixOpenCodeConfig(currentConfig)
101
+
102
+ // Validate the fixed config
103
+ const result = validateOpenCodeConfig(fixedConfig)
104
+
105
+ // The fixed config should be valid according to the JSON Schema
106
+ expect(result.valid).toBe(true)
107
+
108
+ if (!result.valid) {
109
+ console.log('Fixed opencode.json validation errors:')
110
+ result.errors?.forEach((err) => console.log(` - ${err}`))
111
+ }
112
+ } catch (error) {
113
+ // If we can't read the file, that's ok for this test
114
+ console.log('Could not read opencode.json for testing:', error)
115
+ expect.fail('Should be able to read opencode.json')
116
+ }
117
+ })
118
+ })
package/tsconfig.json CHANGED
@@ -11,7 +11,7 @@
11
11
  // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
12
 
13
13
  /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
14
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
15
  // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
16
  // "jsx": "preserve", /* Specify what JSX code is generated. */
17
17
  // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
@@ -25,7 +25,7 @@
25
25
  // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
26
 
27
27
  /* Modules */
28
- "module": "commonjs", /* Specify what module code is generated. */
28
+ "module": "commonjs" /* Specify what module code is generated. */,
29
29
  // "rootDir": "./", /* Specify the root folder within your source files. */
30
30
  // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
@@ -39,7 +39,7 @@
39
39
  // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
40
  // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
41
  // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
- "resolveJsonModule": true, /* Enable importing .json files. */
42
+ "resolveJsonModule": true /* Enable importing .json files. */,
43
43
  // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
44
  // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
45
 
@@ -55,7 +55,7 @@
55
55
  // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
56
  // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
57
  // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
- "outDir": "./dist/", /* Specify an output folder for all emitted files. */
58
+ "outDir": "./dist/" /* Specify an output folder for all emitted files. */,
59
59
  // "removeComments": true, /* Disable emitting comments. */
60
60
  // "noEmit": true, /* Disable emitting files from a compilation. */
61
61
  // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
@@ -77,12 +77,12 @@
77
77
  // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
78
  // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
79
  // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
80
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
81
81
  // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
82
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
83
83
 
84
84
  /* Type Checking */
85
- "strict": true, /* Enable all strict type-checking options. */
85
+ "strict": true /* Enable all strict type-checking options. */,
86
86
  // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
87
  // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
88
  // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
@@ -104,6 +104,6 @@
104
104
 
105
105
  /* Completeness */
106
106
  // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
107
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
108
  }
109
109
  }
package/-27b-it DELETED
File without changes
@@ -1,95 +0,0 @@
1
- # Berget CLI Examples
2
-
3
- This folder contains practical examples of how you can use Berget CLI for various automation tasks.
4
-
5
- ## Scripts
6
-
7
- ### smart-commit.sh
8
- Automatic generation of conventional commit messages based on git diff.
9
-
10
- ```bash
11
- # Make the script executable
12
- chmod +x examples/smart-commit.sh
13
-
14
- # Use it
15
- git add .
16
- ./examples/smart-commit.sh
17
- ```
18
-
19
- ### ai-review.sh
20
- AI-driven code review that analyzes files for quality, bugs, and security aspects.
21
-
22
- ```bash
23
- # Make the script executable
24
- chmod +x examples/ai-review.sh
25
-
26
- # Review a file
27
- ./examples/ai-review.sh src/main.js
28
- ```
29
-
30
- ### security-check.sh
31
- Security review of git commits that blocks commits with critical security risks.
32
-
33
- ```bash
34
- # Make the script executable
35
- chmod +x examples/security-check.sh
36
-
37
- # Run security check
38
- git add .
39
- ./examples/security-check.sh
40
- ```
41
-
42
- ## Installation
43
-
44
- To use these scripts:
45
-
46
- 1. Copy them to your `~/bin` folder or another location in your PATH
47
- 2. Make them executable with `chmod +x`
48
- 3. Make sure you have Berget CLI installed and configured
49
-
50
- ```bash
51
- # Copy to ~/bin
52
- cp examples/*.sh ~/bin/
53
-
54
- # Make them executable
55
- chmod +x ~/bin/smart-commit.sh ~/bin/ai-review.sh ~/bin/security-check.sh
56
- ```
57
-
58
- ## Global Security Hook
59
-
60
- For maximum security, you can install a global git hook that automatically runs security checks before every push:
61
-
62
- ```bash
63
- # Install the global security hook
64
- chmod +x examples/install-global-security-hook.sh
65
- ./examples/install-global-security-hook.sh
66
- ```
67
-
68
- This will:
69
- - Create a global pre-push hook that runs on all repositories
70
- - Automatically analyze commits for security vulnerabilities using OWASP Top 20
71
- - Block pushes with critical security issues
72
- - Warn about medium-risk issues and allow you to choose
73
-
74
- The hook will run automatically before every `git push`. To bypass it temporarily (not recommended):
75
- ```bash
76
- git push --no-verify
77
- ```
78
-
79
- ## Git Aliases
80
-
81
- You can also add these as git aliases:
82
-
83
- ```bash
84
- git config --global alias.ai-commit '!~/bin/smart-commit.sh'
85
- git config --global alias.ai-review '!~/bin/ai-review.sh'
86
- git config --global alias.security-check '!~/bin/security-check.sh'
87
- ```
88
-
89
- Then you can use:
90
-
91
- ```bash
92
- git ai-commit
93
- git ai-review src/main.js
94
- git security-check
95
- ```
@@ -1,30 +0,0 @@
1
- #!/bin/bash
2
- # AI code review using Berget AI
3
- # Usage: ./ai-review.sh <filename>
4
- set -e
5
-
6
- if [[ $# -eq 0 ]]; then
7
- echo "Usage: ai-review <file>"
8
- exit 1
9
- fi
10
-
11
- FILE="$1"
12
-
13
- if [[ ! -f "$FILE" ]]; then
14
- echo "Error: File '$FILE' does not exist"
15
- exit 1
16
- fi
17
-
18
- echo "🔍 Reviewing $FILE with AI..."
19
- echo "================================"
20
-
21
- cat "$FILE" | npx berget chat run openai/gpt-oss "
22
- Review this code and provide feedback on:
23
- 1. Code quality and readability
24
- 2. Potential bugs or issues
25
- 3. Performance improvements
26
- 4. Best practices
27
- 5. Security aspects
28
-
29
- Provide concrete suggestions for improvements:
30
- "
@@ -1,170 +0,0 @@
1
- #!/bin/bash
2
- # Install global git security hook
3
- # This script sets up a global pre-push hook that runs security checks on all repositories
4
-
5
- set -e
6
-
7
- echo "🔧 Installing global git security hook..."
8
-
9
- # Create global git hooks directory
10
- GLOBAL_HOOKS_DIR="$HOME/.git-hooks"
11
- mkdir -p "$GLOBAL_HOOKS_DIR"
12
-
13
- # Create the pre-push hook
14
- cat > "$GLOBAL_HOOKS_DIR/pre-push" << 'EOF'
15
- #!/bin/bash
16
- # Global pre-push security hook using Berget AI
17
- # This hook runs automatically before every git push
18
-
19
- set -e
20
-
21
- # Colors for output
22
- RED='\033[0;31m'
23
- GREEN='\033[0;32m'
24
- YELLOW='\033[1;33m'
25
- BLUE='\033[0;34m'
26
- NC='\033[0m' # No Color
27
-
28
- echo -e "${BLUE}🔒 Running security check before push...${NC}"
29
-
30
- # Check if we're in a git repository
31
- if ! git rev-parse --git-dir > /dev/null 2>&1; then
32
- echo -e "${RED}Error: Not in a git repository${NC}"
33
- exit 1
34
- fi
35
-
36
- # Check if there are any commits to push
37
- if [[ -z $(git log @{u}.. --oneline 2>/dev/null) ]]; then
38
- echo -e "${GREEN}✅ No new commits to push${NC}"
39
- exit 0
40
- fi
41
-
42
- # Get the diff of commits being pushed
43
- DIFF=$(git diff @{u}.. 2>/dev/null || git diff HEAD~1)
44
-
45
- if [[ -z "$DIFF" ]]; then
46
- echo -e "${GREEN}✅ No changes to analyze${NC}"
47
- exit 0
48
- fi
49
-
50
- echo -e "${BLUE}Analyzing security risks in commits being pushed...${NC}"
51
-
52
- # Check if Berget CLI is available
53
- if ! command -v npx > /dev/null 2>&1; then
54
- echo -e "${YELLOW}⚠️ npx not found. Skipping security check.${NC}"
55
- echo -e "${YELLOW}Install Node.js and npm to enable security checks.${NC}"
56
- exit 0
57
- fi
58
-
59
- # Run security analysis
60
- SECURITY_REPORT=$(echo "$DIFF" | npx berget chat run openai/gpt-oss "
61
- Analyze this git diff for security vulnerabilities using OWASP Top 20 Code Review recommendations:
62
-
63
- **OWASP Top 20 Security Categories to Check:**
64
-
65
- 1. **A01 - Broken Access Control**: Authorization bypasses, privilege escalation, insecure direct object references
66
- 2. **A02 - Cryptographic Failures**: Weak encryption, hardcoded keys, insecure random number generation, plain text storage
67
- 3. **A03 - Injection**: SQL injection, NoSQL injection, command injection, LDAP injection, XSS
68
- 4. **A04 - Insecure Design**: Missing security controls, threat modeling gaps, insecure architecture patterns
69
- 5. **A05 - Security Misconfiguration**: Default credentials, unnecessary features enabled, verbose error messages
70
- 6. **A06 - Vulnerable Components**: Outdated dependencies, known vulnerable libraries, unpatched components
71
- 7. **A07 - Authentication Failures**: Weak passwords, session management flaws, credential stuffing vulnerabilities
72
- 8. **A08 - Software Integrity Failures**: Unsigned code, insecure CI/CD pipelines, auto-update without verification
73
- 9. **A09 - Logging Failures**: Insufficient logging, sensitive data in logs, log injection
74
- 10. **A10 - Server-Side Request Forgery**: SSRF vulnerabilities, unvalidated URLs, internal service access
75
-
76
- **Additional Critical Areas:**
77
- 11. **Input Validation**: Insufficient sanitization, buffer overflows, format string vulnerabilities
78
- 12. **Output Encoding**: XSS prevention, content type validation, encoding bypasses
79
- 13. **File Operations**: Path traversal, file upload vulnerabilities, insecure file permissions
80
- 14. **Network Security**: Insecure protocols, certificate validation, CSRF protection
81
- 15. **Session Management**: Session fixation, insecure cookies, session timeout issues
82
- 16. **Error Handling**: Information disclosure, stack traces in production, verbose error messages
83
- 17. **Business Logic**: Race conditions, workflow bypasses, price manipulation
84
- 18. **API Security**: Rate limiting, input validation, authentication on all endpoints
85
- 19. **Mobile Security**: Insecure data storage, weak encryption, certificate pinning
86
- 20. **Cloud Security**: Misconfigured permissions, exposed storage, insecure defaults
87
-
88
- **Assessment Criteria:**
89
- - 🟢 SAFE: No security risks identified according to OWASP guidelines
90
- - 🟡 WARNING: Minor security risks that should be addressed (OWASP Medium risk)
91
- - 🔴 CRITICAL: Serious security risks that MUST be addressed immediately (OWASP High/Critical risk)
92
-
93
- **Required Response Format:**
94
- **SECURITY ASSESSMENT: [🟢/🟡/🔴] [SAFE/WARNING/CRITICAL]**
95
-
96
- **OWASP CATEGORIES AFFECTED:**
97
- - [List specific OWASP categories if any vulnerabilities found]
98
-
99
- **IDENTIFIED RISKS:**
100
- - [List specific vulnerabilities with OWASP category references]
101
-
102
- **RECOMMENDATIONS:**
103
- - [Concrete remediation steps following OWASP secure coding practices]
104
-
105
- **COMPLIANCE NOTES:**
106
- - [Any additional security considerations or compliance requirements]
107
-
108
- Diff to analyze:
109
- \`\`\`diff
110
- $DIFF
111
- \`\`\`
112
- " 2>/dev/null)
113
-
114
- if [[ $? -ne 0 ]] || [[ -z "$SECURITY_REPORT" ]]; then
115
- echo -e "${YELLOW}⚠️ Security analysis failed or unavailable. Proceeding with push.${NC}"
116
- echo -e "${YELLOW}Make sure you have BERGET_API_KEY set or are logged in with 'npx berget auth login'${NC}"
117
- exit 0
118
- fi
119
-
120
- echo "$SECURITY_REPORT"
121
- echo ""
122
-
123
- # Extract security level from report
124
- if echo "$SECURITY_REPORT" | grep -q "🔴.*CRITICAL"; then
125
- echo -e "${RED}❌ CRITICAL security risks identified!${NC}"
126
- echo -e "${RED}Push blocked. Address security issues before pushing.${NC}"
127
- echo ""
128
- echo -e "${YELLOW}To bypass this check (NOT RECOMMENDED):${NC}"
129
- echo -e "${YELLOW}git push --no-verify${NC}"
130
- exit 1
131
- elif echo "$SECURITY_REPORT" | grep -q "🟡.*WARNING"; then
132
- echo -e "${YELLOW}⚠️ Security warnings identified.${NC}"
133
- read -p "Do you want to continue with push despite warnings? (y/N): " -n 1 -r
134
- echo
135
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
136
- echo -e "${YELLOW}Push cancelled. Address security issues first.${NC}"
137
- echo ""
138
- echo -e "${YELLOW}To bypass this check (NOT RECOMMENDED):${NC}"
139
- echo -e "${YELLOW}git push --no-verify${NC}"
140
- exit 1
141
- fi
142
- elif echo "$SECURITY_REPORT" | grep -q "🟢.*SAFE"; then
143
- echo -e "${GREEN}✅ No security risks identified. Safe to push!${NC}"
144
- else
145
- echo -e "${YELLOW}⚠️ Could not determine security status. Proceeding with caution.${NC}"
146
- fi
147
-
148
- echo -e "${GREEN}Security check complete. Proceeding with push...${NC}"
149
- EOF
150
-
151
- # Make the hook executable
152
- chmod +x "$GLOBAL_HOOKS_DIR/pre-push"
153
-
154
- # Configure git to use the global hooks directory
155
- git config --global core.hooksPath "$GLOBAL_HOOKS_DIR"
156
-
157
- echo -e "${GREEN}✅ Global security hook installed successfully!${NC}"
158
- echo ""
159
- echo -e "${BLUE}The security hook will now run automatically before every 'git push' in all repositories.${NC}"
160
- echo ""
161
- echo -e "${YELLOW}Requirements:${NC}"
162
- echo -e " • Node.js and npm installed"
163
- echo -e " • Berget CLI configured (npx berget auth login or BERGET_API_KEY set)"
164
- echo ""
165
- echo -e "${YELLOW}To disable the hook temporarily:${NC}"
166
- echo -e " git push --no-verify"
167
- echo ""
168
- echo -e "${YELLOW}To uninstall the global hook:${NC}"
169
- echo -e " git config --global --unset core.hooksPath"
170
- echo -e " rm -rf $GLOBAL_HOOKS_DIR"
@@ -1,102 +0,0 @@
1
- #!/bin/bash
2
- # Security check for git commits using Berget AI
3
- # Usage: ./security-check.sh
4
- set -e
5
-
6
- echo "🔒 Security review of commits..."
7
- echo "===================================="
8
-
9
- # Check if there are staged changes
10
- if [[ -z $(git diff --cached) ]]; then
11
- echo "No staged changes found. Run 'git add' first."
12
- exit 1
13
- fi
14
-
15
- # Get diff for security review
16
- DIFF=$(git diff --cached)
17
-
18
- echo "Analyzing security risks in staged changes..."
19
-
20
- SECURITY_REPORT=$(echo "$DIFF" | npx berget chat run openai/gpt-oss "
21
- Analyze this git diff for security vulnerabilities using OWASP Top 20 Code Review recommendations:
22
-
23
- **OWASP Top 20 Security Categories to Check:**
24
-
25
- 1. **A01 - Broken Access Control**: Authorization bypasses, privilege escalation, insecure direct object references
26
- 2. **A02 - Cryptographic Failures**: Weak encryption, hardcoded keys, insecure random number generation, plain text storage
27
- 3. **A03 - Injection**: SQL injection, NoSQL injection, command injection, LDAP injection, XSS
28
- 4. **A04 - Insecure Design**: Missing security controls, threat modeling gaps, insecure architecture patterns
29
- 5. **A05 - Security Misconfiguration**: Default credentials, unnecessary features enabled, verbose error messages
30
- 6. **A06 - Vulnerable Components**: Outdated dependencies, known vulnerable libraries, unpatched components
31
- 7. **A07 - Authentication Failures**: Weak passwords, session management flaws, credential stuffing vulnerabilities
32
- 8. **A08 - Software Integrity Failures**: Unsigned code, insecure CI/CD pipelines, auto-update without verification
33
- 9. **A09 - Logging Failures**: Insufficient logging, sensitive data in logs, log injection
34
- 10. **A10 - Server-Side Request Forgery**: SSRF vulnerabilities, unvalidated URLs, internal service access
35
-
36
- **Additional Critical Areas:**
37
- 11. **Input Validation**: Insufficient sanitization, buffer overflows, format string vulnerabilities
38
- 12. **Output Encoding**: XSS prevention, content type validation, encoding bypasses
39
- 13. **File Operations**: Path traversal, file upload vulnerabilities, insecure file permissions
40
- 14. **Network Security**: Insecure protocols, certificate validation, CSRF protection
41
- 15. **Session Management**: Session fixation, insecure cookies, session timeout issues
42
- 16. **Error Handling**: Information disclosure, stack traces in production, verbose error messages
43
- 17. **Business Logic**: Race conditions, workflow bypasses, price manipulation
44
- 18. **API Security**: Rate limiting, input validation, authentication on all endpoints
45
- 19. **Mobile Security**: Insecure data storage, weak encryption, certificate pinning
46
- 20. **Cloud Security**: Misconfigured permissions, exposed storage, insecure defaults
47
-
48
- **Assessment Criteria:**
49
- - 🟢 SAFE: No security risks identified according to OWASP guidelines
50
- - 🟡 WARNING: Minor security risks that should be addressed (OWASP Medium risk)
51
- - 🔴 CRITICAL: Serious security risks that MUST be addressed immediately (OWASP High/Critical risk)
52
-
53
- **Required Response Format:**
54
- **SECURITY ASSESSMENT: [🟢/🟡/🔴] [SAFE/WARNING/CRITICAL]**
55
-
56
- **OWASP CATEGORIES AFFECTED:**
57
- - [List specific OWASP categories if any vulnerabilities found]
58
-
59
- **IDENTIFIED RISKS:**
60
- - [List specific vulnerabilities with OWASP category references]
61
-
62
- **RECOMMENDATIONS:**
63
- - [Concrete remediation steps following OWASP secure coding practices]
64
-
65
- **COMPLIANCE NOTES:**
66
- - [Any additional security considerations or compliance requirements]
67
-
68
- Diff to analyze:
69
- \`\`\`diff
70
- $DIFF
71
- \`\`\`
72
- ")
73
-
74
- echo "$SECURITY_REPORT"
75
- echo ""
76
-
77
- # Extract security level from report
78
- if echo "$SECURITY_REPORT" | grep -q "🔴.*CRITICAL"; then
79
- echo "❌ CRITICAL security risks identified!"
80
- echo "Commit blocked. Address security issues before continuing."
81
- exit 1
82
- elif echo "$SECURITY_REPORT" | grep -q "🟡.*WARNING"; then
83
- echo "⚠️ Security warnings identified."
84
- read -p "Do you want to continue with commit despite warnings? (y/N): " -n 1 -r
85
- echo
86
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
87
- echo "Commit cancelled. Address security issues first."
88
- exit 1
89
- fi
90
- elif echo "$SECURITY_REPORT" | grep -q "🟢.*SAFE"; then
91
- echo "✅ No security risks identified. Safe to continue!"
92
- else
93
- echo "⚠️ Could not determine security status. Review manually."
94
- read -p "Do you want to continue with commit? (y/N): " -n 1 -r
95
- echo
96
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
97
- echo "Commit cancelled."
98
- exit 1
99
- fi
100
- fi
101
-
102
- echo "Security review complete. You can now run 'git commit'."
@@ -1,26 +0,0 @@
1
- #!/bin/bash
2
- # Smart commit generator using Berget AI
3
- # Usage: ./smart-commit.sh
4
- set -e
5
-
6
- # Check if there are staged changes
7
- if [[ -z $(git diff --cached) ]]; then
8
- echo "No staged changes found. Run 'git add' first."
9
- exit 1
10
- fi
11
-
12
- # Generate commit message
13
- COMMIT_MSG=$(git diff --cached | npx berget chat run openai/gpt-oss "Generate a conventional commit message for this staged diff. Reply with only the commit message, nothing else:")
14
-
15
- echo "Suggested commit message:"
16
- echo " $COMMIT_MSG"
17
- echo
18
-
19
- read -p "Do you want to use this message? (y/N): " -n 1 -r
20
- echo
21
- if [[ $REPLY =~ ^[Yy]$ ]]; then
22
- git commit -m "$COMMIT_MSG"
23
- echo "✅ Commit created!"
24
- else
25
- echo "❌ Commit cancelled"
26
- fi