Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
voxpelli committed Dec 13, 2022
0 parents commit b1504b2
Show file tree
Hide file tree
Showing 19 changed files with 633 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/coverage/**/*
*.d.ts
34 changes: 34 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"root": true,
"plugins": [
"jsdoc",
"unicorn"
],
"extends": [
"@socketsecurity",
"plugin:jsdoc/recommended"
],
"settings": {
"jsdoc": {
"mode": "typescript"
}
},
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"@typescript-eslint/quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": false }],
"no-console": "warn",

"jsdoc/check-types": "off",
"jsdoc/no-undefined-types": "off",
"jsdoc/require-jsdoc": "warn",
"jsdoc/require-param-description": "off",
"jsdoc/require-property-description": "off",
"jsdoc/require-returns-description": "off",
"jsdoc/require-yields": "off",
"jsdoc/valid-types": "off",

"unicorn/expiring-todo-comments": "warn"
}
}
12 changes: 12 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
26 changes: 26 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Linting

on:
push:
branches:
- master
tags:
- '*'
pull_request:
branches:
- master

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

jobs:
linting:
name: "Linting"
uses: SocketDev/workflows/.github/workflows/reusable-base.yml@master
with:
no-lockfile: true
npm-test-script: 'check'
30 changes: 30 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Node CI

on:
push:
branches:
- master
tags:
- '*'
pull_request:
branches:
- master

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

jobs:
test:
name: "Tests"
uses: SocketDev/workflows/.github/workflows/reusable-base.yml@master
with:
no-lockfile: true
npm-test-script: 'test-ci'
node-versions: '14,16,18,19'
# We currently have some issues on Windows that will have to wait to be fixed
# os: 'ubuntu-latest,windows-latest'
os: 'ubuntu-latest'
19 changes: 19 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Basic ones
/coverage
/coverage-ts
/node_modules
/.env
/.nyc_output
/.vscode

# We're a library, so please, no lock files
/package-lock.json
/yarn.lock

# Generated types
*.d.ts
*.d.ts.map
!/lib/types/**/*.d.ts

# Library specific ones
!/.vscode/extensions.json
4 changes: 4 additions & 0 deletions .husky/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm test
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022 Socket Inc

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Socket Config

[![npm version](https://img.shields.io/npm/v/@socketsecurity/config.svg?style=flat)](https://www.npmjs.com/package/@socketsecurity/config)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/SocketDev/eslint-config)
[![Types in JS](https://img.shields.io/badge/types_in_js-yes-brightgreen)](https://github.com/voxpelli/types-in-js)
[![Follow @SocketSecurity](https://img.shields.io/twitter/follow/SocketSecurity?style=social)](https://twitter.com/SocketSecurity)

Reader/parser/validator tool for [Socket.dev](https://socket.dev/)'s [`socket.yml`](https://docs.socket.dev/docs/socket-yml) configuration files

## Usage

```bash
npm install @socketsecurity/config
```

```javascript
import { readSocketConfig } from '@socketsecurity/config'

const config = await readSocketConfig('socket.yml')
```

## Exports

### `readSocketConfig(<path-to-config-file>)`

Returns a `Promise` that resolves to the parsed config file or, if no such file was found, it fails silently and returns `undefined`.

If the config file can't be read, then the `Promise` will be rejected with an error.

The read file is parsed using `parseSocketConfig`and the `Promise` from there is what is ultimately returned when no rejection or resolve has been made already.

### `parseSocketConfig(<content-of-config-file>)`

Returns a `Promise` that resolves to the parsed config.

If the config content can't be parsed or it is invalid, then the `Promise` will be rejected with an error.

Any additional parameters that does not conform to the schema will be silently dropped. Also: Input data will be coerced into its intended shape when possible.

### `socketYmlSchema`

A JSON Schema object typed with [`JSONSchemaType<SocketYml>`](https://ajv.js.org/guide/typescript.html) from Ajv

### `SocketValidationError`

Error thrown when the parsed data doesn't conform to the JSON Schema definition (see `socketYmlSchema`).

Exposes an array of [Ajv's `ErrorObject`](https://ajv.js.org/api.html#error-objects) at `.validationErrors`, allowing a consumer to present a user friendly error.

## Type exports

This module has full type coverage through a [types in js](https://github.com/voxpelli/types-in-js) where TypeScript validates JSDoc annotated javascript and exports it as standard type definition files.

### `SocketYml`

A TypeScript type representing the shape of the parsed `socket.yml` config

## Used by

* [`@socketsecurity/cli`](https://github.com/SocketDev/socket-cli-js) - our CLI uses this to parse the Socket config

## See also

* [Socket.yml reference](https://docs.socket.dev/docs/socket-yml) - the config parsed by this module
14 changes: 14 additions & 0 deletions declaration.tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

{
"extends": "./tsconfig",
"exclude": [
"test/**/*.js"
],
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"noEmit": false,
"removeComments": true
}
}
143 changes: 143 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
'use strict'

const { readFile } = require('node:fs/promises')

const { default: Ajv } = require('ajv')
const { ErrorWithCause } = require('pony-cause')
const { parse: yamlParse } = require('yaml')

/**
* @typedef SocketYmlGitHub
* @property {boolean} [beta] beta opt in field
* @property {boolean} [enabled] enable/disable the Socket.dev GitHub app entirely
* @property {boolean} [projectReportsEnabled] enable/disable Github app project report checks
* @property {boolean} [pullRequestAlertsEnabled] enable/disable GitHub app pull request alert checks
*/

/**
* @typedef SocketYml
* @property {2} version
* @property {string[]} [projectIgnorePaths]
* @property {{ [issueName: string]: boolean }} [issueRules]
* @property {SocketYmlGitHub} [githubApp]
*/

/** @type {import('ajv').JSONSchemaType<SocketYml>} */
const socketYmlSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
version: { type: 'integer' },
projectIgnorePaths: {
type: 'array',
items: { type: 'string' },
nullable: true,
},
issueRules: {
type: 'object',
nullable: true,
required: [],
additionalProperties: { type: 'boolean' },
},
githubApp: {
type: 'object',
nullable: true,
properties: {
beta: { type: 'boolean', nullable: true },
enabled: { type: 'boolean', nullable: true },
projectReportsEnabled: { type: 'boolean', nullable: true },
pullRequestAlertsEnabled: { type: 'boolean', nullable: true },
},
required: [],
additionalProperties: false,
},
},
required: ['version'],
additionalProperties: false,
}

const ajv = new Ajv({
allErrors: true,
coerceTypes: 'array',
logger: false,
removeAdditional: 'failing',
})

const validate = ajv.compile(socketYmlSchema)

/**
* @param {string} filePath
* @returns {Promise<SocketYml|undefined>}
* @throws {SocketValidationError}
*/
async function readSocketConfig (filePath) {
/** @type {string} */
let fileContent

try {
fileContent = await readFile(filePath, 'utf8')
} catch (err) {
if (isErrnoException(err) && err.code === 'ENOENT') {
return
}
throw new ErrorWithCause('Error when reading socket.yml config file', { cause: err })
}

return parseSocketConfig(fileContent)
}

/**
* @param {string} fileContent
* @returns {Promise<SocketYml>}
* @throws {SocketValidationError}
*/
async function parseSocketConfig (fileContent) {
/** @type {unknown} */
let parsedContent

try {
parsedContent = yamlParse(fileContent)
} catch (err) {
throw new ErrorWithCause('Error when parsing socket.yml config', { cause: err })
}

if (!validate(parsedContent)) {
throw new SocketValidationError('Invalid config definition', validate.errors || [])
}

return parsedContent
}

/**
* @param {unknown} value
* @returns {value is NodeJS.ErrnoException}
*/
function isErrnoException (value) {
if (!(value instanceof Error)) {
return false
}

const errnoException = /** @type NodeJS.ErrnoException} */ (value)

return errnoException.code !== undefined
}

class SocketValidationError extends Error {
/**
* @param {string} message
* @param {import('ajv').ErrorObject[]} validationErrors
*/
constructor (message, validationErrors) {
super(message)

/** @type {import('ajv').ErrorObject[]} */
this.validationErrors = validationErrors
}
}

module.exports = {
parseSocketConfig,
readSocketConfig,
SocketValidationError,
socketYmlSchema,
}
Loading

0 comments on commit b1504b2

Please sign in to comment.