Skip to content

Commit

Permalink
feat: 检验请求签名
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Jan 30, 2024
1 parent 91e2fc8 commit fff774d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {Tail} from 'tail'
import {fileURLToPath} from 'url'
import {validateFile} from './file.js'
import MeasureRoute from './measure.route.js'
import {hashToFilename} from './util.js'
import {checkSign, hashToFilename} from './util.js'

interface IFileList {
files: {path: string; hash: string; size: number}[]
Expand Down Expand Up @@ -161,6 +161,11 @@ export class Cluster {
app.get('/download/:hash(\\w+)', async (req: Request, res: Response, next: NextFunction) => {
try {
const hash = req.params.hash.toLowerCase()
const signValid = checkSign(hash, this.clusterSecret, req.query as NodeJS.Dict<string>)
if (!signValid) {
return res.status(403).send('invalid sign')
}

const path = join(this.cacheDir, hashToFilename(hash))
if (!await fse.pathExists(path)) {
await this.downloadFile(hash)
Expand Down
13 changes: 13 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import {createHash} from 'crypto'
import {join} from 'path'

export function hashToFilename(hash: string): string {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
return join(hash.substring(0, 2), hash)
}

export function checkSign(hash: string, secret: string, query: NodeJS.Dict<string>): boolean {
const {s, e} = query
if (!s || !e) return false
const sha1 = createHash('sha1')
const toSign = [secret, hash, e]
for (const str of toSign) {
sha1.update(str)
}
const sign = sha1.digest('base64url')
return sign === s && Date.now() < parseInt(e, 36)
}

0 comments on commit fff774d

Please sign in to comment.