Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/codeql/codeql-config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name: GoodServer CodeQL config
paths-ignore:
# vendored third-party Flow library definitions (not our code, and not valid plain JS)
- flow-typed/**
1 change: 1 addition & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs:
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
config-file: ./.github/codeql/codeql-config.yml

- name: Autobuild
uses: github/codeql-action/autobuild@v4
Expand Down
17 changes: 17 additions & 0 deletions docs/security-triage-2026-11-15.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,20 @@ Alert line numbers refer to old commits; mapped to current code below.
4. Replace `@gooddollar/kms-ethereum-signing` with a viem implementation (closes both critical alerts and ~13 packages).
5. Replace `axelarjs-sdk` with a direct API call (closes 10 high protobufjs alerts).
6. `@sentry/node` upgrade; `lint-staged` / `nodemon` upgrades; `visitorsCounter` -> `Map`; `sanitizeFilter`.

## Follow-up (after the `switch-to-viem` merge)

Re-scanned on `master` (3902ec3a): 38 code-scanning and 60 Dependabot alerts were open.

### Code scanning
- **Fixed in code:** log injection (`sanitizeLog` helper strips line breaks from user-provided values before logging), `last_claim` / `methodToInvoke` useless assignments, always-true conditionals (`!code`, `alreadyIndexed`), duplicate `resolve` key in `webpack.dev.config.js`, dead functions in `scripts/docs.js` plus shell-quoting of file names passed to `exec`.
- **Flow type imports:** CodeQL cannot see Flow annotations, so `Router`, `UserRecord`, `IdScanRequest`, ... looked unused. They are now `import type`.
- **Vendored `flow-typed/`:** excluded through `.github/codeql/codeql-config.yml`.
- **NoSQL injection (#3, #48, #49, #97):** inputs are validated with `assertString` and now also passed through `String()` at the query site.
- **False positive:** #64 (`/goodid/certificate/verify` `if (!certificate)` is a missing-input check; the certificate itself is cryptographically verified).

### Dependabot
- **Fixed:** `@axelar-network/axelarjs-sdk` 0.22; overrides for `protobufjs`, `toml`, `zod`, `esbuild`.
- **Waiting for `@gooddollar/kms-ethereum-signing`** (still depends on `web3` 1.x, latest 1.0.4): `tar`, `request`, `form-data`, `qs`, `tough-cookie`, `uuid`, `ws`, `decode-uri-component`, `bn.js`, `web3-core-subscriptions`. All come in through `web3-bzz` / `swarm-js` (Swarm support, never used by signing).
- **No patched version / major upgrade needed:** `stream-json` 1.x via `jayson` (patched 3.x is ESM-only and moves the sub-paths `jayson` requires), `elliptic`, `deepmerge`, `cookie` via `@sentry/node` 5.
- **Dev tooling only** (apidoc, documentation, mock-express-response, eslint/jest): `bootstrap`, `markdown-it`, `linkify-it`, `vue-template-compiler`, `send`, `cookie`, `minimatch`.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"@aws-sdk/client-rekognition": "~3.1167.0",
"@aws-sdk/client-s3": "^3.1102.0",
"@aws-sdk/client-ses": "~3.1167.0",
"@axelar-network/axelarjs-sdk": "^0.21.0",
"@axelar-network/axelarjs-sdk": "^0.22.0",
"@gooddollar/goodprotocol": "^2.3.4",
"@gooddollar/kms-ethereum-signing": "^1.0.4",
"@goodwidget/core": "^0.1.5",
Expand Down
447 changes: 204 additions & 243 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ overrides:
'@aws-sdk/client-rekognition': 3.1167.0
mongoose: 8.24.8
'nodemon@>=2 <3': 3.1.14
# security: patched versions of transitive deps (see docs/security-triage-2026-11-15.md)
'protobufjs@<7': 7.6.3
'toml@<5': 5.0.1
'zod@<4': 4.6.6
'esbuild@<0.25': 0.25.0
81 changes: 12 additions & 69 deletions scripts/docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,6 @@ const isValidFile = async filePath => {
}
}

/**
* Removes all empty docs and returns a list with actual documentation
* @param {[string]} docs
*/
async function filterEmptyDocs(docs) {
const emptyDoc = await whenEmptyFileString
return docs.filter(doc => {
if (!doc.mdFile) {
console.log('no mdFile', doc)
return false
}
const data = fs.readFileSync(doc.mdFile)
const docString = data.toString()

return docString !== emptyDoc
})
}

function promiseFromChildProcess(child) {
return new Promise(function(resolve, reject) {
child.addListener('error', e => {
Expand All @@ -72,61 +54,23 @@ function promiseFromChildProcess(child) {
})
}

// single-quotes a value so file names read from disk cannot inject shell syntax
const shellQuote = value => `'${String(value).replace(/'/g, `'\\''`)}'`

function execPromise(toExec) {
return promiseFromChildProcess(exec(toExec)).catch(e => console.log('Failed exec', toExec))
}

async function generateAPIDocs() {
await execPromise('apidoc -i src/server/ -o apidoc/')
await execPromise(`apidoc-markdown -p apidoc -o ${BASE_DOCS_FOLDER}/README.md`)
await execPromise(`apidoc-markdown -p apidoc -o ${shellQuote(`${BASE_DOCS_FOLDER}/README.md`)}`)
await execPromise('rm -rf apidoc')
}

async function doGenerateToc(docs, { baseFolder, relativeToToc, level }) {
relativeToToc = relativeToToc || ''
let outputString = ''
const currentLevel = level || 0
if (!docs || docs.length <= 0) return outputString
const padding = ' '.repeat(currentLevel * 3)
const results = await Promise.all(
await docs.map(async doc => {
let addedOutput = ''

if (doc.mdFile) {
const path = doc.mdFile.replace(baseFolder, relativeToToc)
console.log('TOC path:', { md: doc.mdFile, path })
addedOutput += `${padding + padding}- [${doc.src.replace(baseFolder, relativeToToc)}](/${doc.mdFile})\n`
}

if (doc.childrenDocs && doc.childrenDocs.length > 0) {
if (doc.childrenDocs.filter(child => child.mdFile).length > 0) {
const path = doc.src.replace(baseFolder, relativeToToc)
addedOutput += `${padding}- ${path}\n`
}
addedOutput += await doGenerateToc(doc.childrenDocs, { baseFolder, relativeToToc, level: currentLevel + 1 })
}

return addedOutput
})
)
return results.join('')
}

async function generateToc(docs) {
console.log('Generating TOC', docs)
const baseFolder = BASE_DOCS_FOLDER + '/'
await execPromise(`mkdir -p ${baseFolder}`)

const title = '\n### GoodServer\n\n'

const outputString = title + (await doGenerateToc(docs, { baseFolder }))
fs.writeFileSync(`${baseFolder}/README.md`, outputString)
}

async function insertSourceLink(mdFile, srcFile) {
const link = BASE_SRC_URL + '/' + srcFile
// console.log('insert line', { link, mdFile })
return await execPromise(`echo "## Source\n[${link}](${link})\n" >> ${mdFile}`)
return await execPromise(`echo ${shellQuote(`## Source\n[${link}](${link})\n`)} >> ${shellQuote(mdFile)}`)
}

async function generateDocs(baseFolder, deep, perFile = true) {
Expand All @@ -141,7 +85,7 @@ async function generateDocs(baseFolder, deep, perFile = true) {
if (fs.lstatSync(filePath).isDirectory() && perFile) {
const outputFolder = camelCaseToDash(`${filePath.replace(baseFolder, BASE_DOCS_FOLDER)}/`)
console.log('creating docs folder:', outputFolder)
await execPromise(`mkdir -p ${outputFolder}`)
await execPromise(`mkdir -p ${shellQuote(outputFolder)}`)
//adding '*.js' causes documentation to not be generated for sub folders
const childrenDocs = await doGenerateDocs(filePath, deep - 1)
const newDoc = { src: filePath, childrenDocs }
Expand All @@ -151,7 +95,7 @@ async function generateDocs(baseFolder, deep, perFile = true) {
const outputFolder = `${folder.replace(baseFolder, BASE_DOCS_FOLDER)}/`
const mdFile = camelCaseToDash(`${outputFolder + file.replace('.js', '')}.md`)
// const mdFile = `${outputFolder + file.replace('.js', '')}.md`
const toExec = `documentation build ${filePath} -f md -o ${mdFile} --shallow`
const toExec = `documentation build ${shellQuote(filePath)} -f md -o ${shellQuote(mdFile)} --shallow`
console.log('Generating docs for:', { filePath, mdFile, toExec })
await execPromise(toExec)
const newDoc = { src: folder + '/' + file }
Expand All @@ -165,16 +109,16 @@ async function generateDocs(baseFolder, deep, perFile = true) {
// //generate recursively for all subfolders when reaching last level
// else if (fs.lstatSync(filePath).isDirectory() && deep == 0) {
// const outputFolder = `${folder.replace(baseFolder, BASE_DOCS_FOLDER)}/`
// await execPromise(`mkdir -p ${outputFolder}`)
// await execPromise(`mkdir -p ${shellQuote(outputFolder)}`)

// const mdFile = camelCaseToDash(`${outputFolder + file}.md`)
// const toExec = `documentation build ${filePath} -f md -o ${mdFile} --shallow`
// const toExec = `documentation build ${shellQuote(filePath)} -f md -o ${shellQuote(mdFile)} --shallow`
// return execPromise(toExec).then(r => ({ mdFile, folder: outputFolder + file }))
// }
// //generate docs only for direct source files for non last level directory
// else if (fs.lstatSync(filePath).isDirectory()) {
// const outputFolder = `${folder.replace(baseFolder, BASE_DOCS_FOLDER)}/`
// await execPromise(`mkdir -p ${outputFolder}`)
// await execPromise(`mkdir -p ${shellQuote(outputFolder)}`)
// //adding '*.js' causes documentation to not be generated for sub folders
// const mdFile = camelCaseToDash(`${outputFolder + file}.md`)
// const toExec = `documentation build ${filePath}/*.js -f md -o ${mdFile} --shallow`
Expand All @@ -197,9 +141,8 @@ async function generateDocs(baseFolder, deep, perFile = true) {
console.log('Generating docs...')

await execPromise('rm -rf docs/*')
const childrenDocs = await doGenerateDocs(baseFolder, deep)
//currently let gitbook handle TOC
//generateToc(childrenDocs)
// gitbook handles the TOC
await doGenerateDocs(baseFolder, deep)

if (DELETE_EMPTY_DOCS) {
console.log('Deleting empty docs...')
Expand Down
2 changes: 1 addition & 1 deletion src/server/crm/api.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @flow
import { fromPairs } from 'lodash'

import { UserRecord } from '../../imports/types'
import type { UserRecord } from '../../imports/types'

const fieldsMap = {
firstName: 'first_name',
Expand Down
17 changes: 12 additions & 5 deletions src/server/db/mongo/user-privat-provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class UserPrivate {
assertString('identifier', user.identifier)

try {
await model.updateOne({ identifier: user.identifier }, { $set: user }, { upsert: true })
await model.updateOne({ identifier: String(user.identifier) }, { $set: user }, { upsert: true })

return true
} catch (ex) {
Expand Down Expand Up @@ -109,14 +109,21 @@ class UserPrivate {
async getByIdentifier(identifier) {
assertString('identifier', identifier)

return await this.model.findOne({ identifier }).lean()
return await this.model.findOne({ identifier: String(identifier) }).lean()
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}

async getByIdentifierHash(identifier) {
assertString('identifier', identifier)

return await this.model
.find({ $or: [{ email: identifier }, { walletAddress: identifier }, { mobile: identifier }, { identifier }] })
.find({
$or: [
{ email: String(identifier) },
{ walletAddress: String(identifier) },
{ mobile: String(identifier) },
{ identifier: String(identifier) }
]
})
.lean()
}
/**
Expand Down Expand Up @@ -165,7 +172,7 @@ class UserPrivate {
async getUsersByEmail(email: string): Promise<UserRecord> {
assertString('email', email)

return await this.model.find({ email }).lean()
return await this.model.find({ email: String(email) }).lean()
}

/**
Expand All @@ -178,7 +185,7 @@ class UserPrivate {
async getUsersByMobile(mobile: string): Promise<UserRecord> {
assertString('mobile', mobile)

return await this.model.find({ mobile }).lean()
return await this.model.find({ mobile: String(mobile) }).lean()
}

/**
Expand Down
9 changes: 5 additions & 4 deletions src/server/goodid/goodid-middleware.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow

import { Router } from 'express'
import type { Router } from 'express'
import passport from 'passport'
import { getClientIp } from '../utils/clientIp'
import { get, isEmpty } from 'lodash'
Expand All @@ -15,6 +15,7 @@
import MultiWallet from '../blockchain/MultiWallet'

import { wrapAsync } from '../utils/helpers'
import { sanitizeLog } from '../utils/sanitizeLog'
import requestRateLimiter from '../utils/requestRateLimiter'
import config from '../server.config'
import { retry as retryAttempt } from '../utils/async'
Expand Down Expand Up @@ -204,9 +205,9 @@
} catch (exception) {
const { message } = exception

log.error('Failed to issue identity ceritifate:', message, exception, {
enrollmentIdentifier,
fvSigner
log.error('Failed to issue identity ceritifate:', sanitizeLog(message), exception, {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
sirpy marked this conversation as resolved.
Dismissed
enrollmentIdentifier: sanitizeLog(enrollmentIdentifier),
fvSigner: sanitizeLog(fvSigner)
})

res.status(400).json({ success: false, error: message })
Expand Down
8 changes: 6 additions & 2 deletions src/server/login/login-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import passport from 'passport'
import { Strategy as AnonymousStrategy } from 'passport-anonymous'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { Router } from 'express'
import type { Router } from 'express'
import { defaults } from 'lodash'
import { AxelarQueryAPI } from '@axelar-network/axelarjs-sdk'
import * as ethers from 'ethers'

import logger from '../../imports/logger'
import { wrapAsync } from '../utils/helpers'
import { sanitizeLog } from '../utils/sanitizeLog'
import UserDBPrivate from '../db/mongo/user-privat-provider'
import Config from '../server.config.js'
import { hashString, recoverPublickey, verifyIdentifier } from '../utils/eth'
Expand Down Expand Up @@ -226,7 +227,10 @@

res.json({ token })
} catch (e) {
log.error('/auth/fv2 failed', e.message, e, { account, fvsig })
log.error('/auth/fv2 failed', sanitizeLog(e.message), e, {
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Comment thread
sirpy marked this conversation as resolved.
Dismissed
account: sanitizeLog(account),
fvsig: sanitizeLog(fvsig)
})
throw e
}
})
Expand Down
3 changes: 2 additions & 1 deletion src/server/server-middlewares.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @flow
import express, { Router } from 'express'
import express from 'express'
import type { Router } from 'express'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import cors from 'cors'
Expand Down
15 changes: 8 additions & 7 deletions src/server/storage/storageAPI.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// @flow
import moment from 'moment'
import { Router } from 'express'
import type { Router } from 'express'
import passport from 'passport'
import fetch from 'cross-fetch'
import { first, get, toLower, values } from 'lodash'
import { getAddress } from 'viem'

import { type StorageAPI, UserRecord } from '../../imports/types'
import type { StorageAPI, UserRecord } from '../../imports/types'
import { wrapAsync, onlyInEnv } from '../utils/helpers'
import { sanitizeLog } from '../utils/sanitizeLog'
import { withTimeout } from '../utils/async'
import OnGage from '../crm/ongage'
import conf from '../server.config'
Expand Down Expand Up @@ -72,8 +73,8 @@ const setup = (app: Router, storage: StorageAPI) => {
log.trace(`/user/* ${req.baseUrl} auth:`, { user, body })

if (loggedInAs !== identifier) {
log.warn(`Trying to update other user data! ${loggedInAs}!==${identifier}`)
throw new Error(`Trying to update other user data! ${loggedInAs}!==${identifier}`)
log.warn(`Trying to update other user data! ${sanitizeLog(loggedInAs)}!==${sanitizeLog(identifier)}`)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
throw new Error(`Trying to update other user data! ${sanitizeLog(loggedInAs)}!==${sanitizeLog(identifier)}`)
} else next()
})
)
Expand Down Expand Up @@ -388,7 +389,7 @@ const setup = (app: Router, storage: StorageAPI) => {
'/user/claim',
onlyInEnv('production', 'staging'),
wrapAsync(async (req, res) => {
let { last_claim, claim_counter } = req.body
const { claim_counter } = req.body
const { log: logger, user } = req

if (!user.crmId) {
Expand All @@ -400,7 +401,7 @@ const setup = (app: Router, storage: StorageAPI) => {
}

// format date according to OnGage date format
last_claim = moment().format('YYYY/MM/DD')
const last_claim = moment().format('YYYY/MM/DD')

updatesQueue.push({ id: user.crmId, last_claim, claim_counter })
if (updatesQueue.length > 100) {
Expand Down Expand Up @@ -766,7 +767,7 @@ const setup = (app: Router, storage: StorageAPI) => {
let result = {}
const identifier = body.identifier || hashString(getAddress(body.account))
if (identifier) result = await storage.updateUser({ identifier, ageVerified: true })
log.info('admin age verify', body, result)
log.info('admin age verify', { identifier: sanitizeLog(identifier), result })
res.json({ ok: 1, result })
})
)
Expand Down
13 changes: 13 additions & 0 deletions src/server/utils/__tests__/sanitizeLog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { sanitizeLog } from '../sanitizeLog'

describe('sanitizeLog', () => {
test('replaces line breaks so values cannot forge log entries', () => {
expect(sanitizeLog('abc\nINFO fake entry\r\nmore')).toBe('abcINFO fake entrymore')
})

test('leaves plain strings untouched and stringifies other values', () => {
expect(sanitizeLog('plain')).toBe('plain')
expect(sanitizeLog(5)).toBe('5')
expect(sanitizeLog(undefined)).toBe('undefined')
})
})
9 changes: 9 additions & 0 deletions src/server/utils/sanitizeLog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// @flow

/**
* Converts a user-provided value to a string and replaces its line breaks before it is written to the logs, so a
* caller cannot forge additional log entries (log injection).
*/
export const sanitizeLog = (value: any): string => String(value).replace(/\n|\r/g, '')

export default sanitizeLog
Loading
Loading