Compare commits
145 Commits
egg
...
snyk-fix-6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33b7a21049 | ||
|
|
522ad11124 | ||
|
|
6be1a198c2 | ||
|
|
19563f5851 | ||
|
|
d5ba93ac0d | ||
|
|
92b72169a8 | ||
|
|
4540845046 | ||
|
|
8e2367ee16 | ||
|
|
96369037f9 | ||
|
|
9da2c494f3 | ||
|
|
be05886452 | ||
|
|
f084ebae21 | ||
|
|
dba5c90114 | ||
|
|
ea46399265 | ||
|
|
dd19a606fb | ||
|
|
8d572169b7 | ||
|
|
3ffe576916 | ||
|
|
585f55bbcc | ||
|
|
2cb43c3e33 | ||
|
|
581925db97 | ||
|
|
c385f9d97f | ||
|
|
da2f9640b8 | ||
|
|
754c74ca61 | ||
|
|
b094f5692f | ||
|
|
0c59791e50 | ||
|
|
7f0c141ac2 | ||
|
|
79fb163a3b | ||
|
|
c0ba12960e | ||
|
|
be00b65573 | ||
|
|
316e722a2e | ||
|
|
65bca46f3c | ||
|
|
35b3cef918 | ||
|
|
807187ebeb | ||
|
|
72b5a97cde | ||
|
|
f9d4858862 | ||
|
|
f7e9670025 | ||
|
|
99c4c3fe35 | ||
|
|
444b5d125c | ||
|
|
4b57c118a0 | ||
|
|
d0c3f1b19e | ||
|
|
b395c666be | ||
|
|
03d7215d6c | ||
|
|
8a2f744749 | ||
|
|
e2fc613c98 | ||
|
|
9bdb695375 | ||
|
|
8bd0a2d491 | ||
|
|
769af76c73 | ||
|
|
93d5def8ac | ||
|
|
6a8434e0ca | ||
|
|
a4a25f9e38 | ||
|
|
300e0e676a | ||
|
|
4a3a851256 | ||
|
|
6226ad8050 | ||
|
|
90580a72e5 | ||
|
|
3497bae2b9 | ||
|
|
2073127796 | ||
|
|
d889ebafbd | ||
|
|
ad2d341d2c | ||
|
|
688da2d94b | ||
|
|
25a9030047 | ||
|
|
938a14d0a1 | ||
|
|
3be0a3261e | ||
|
|
017af69cce | ||
|
|
842c0316ed | ||
|
|
82d3ba777f | ||
|
|
9b8491b736 | ||
|
|
364817481c | ||
|
|
fc799304d8 | ||
|
|
68ef6983fb | ||
|
|
3c20267b22 | ||
|
|
26d7147562 | ||
|
|
3141437a42 | ||
|
|
5149aa5a1e | ||
|
|
bd87907b69 | ||
|
|
fc07a38bde | ||
|
|
17f8b6648b | ||
|
|
92acbcedcc | ||
|
|
d1fe6cede7 | ||
|
|
c95cd95593 | ||
|
|
8fbad397f3 | ||
|
|
533c27fa78 | ||
|
|
0121de31a3 | ||
|
|
53343751f7 | ||
|
|
070fd46f36 | ||
|
|
e61c7fa32b | ||
|
|
84a3037d90 | ||
|
|
34d3a1eabe | ||
|
|
1f60a0136c | ||
|
|
6f656a0736 | ||
|
|
e8f66657b4 | ||
|
|
1b30146e94 | ||
|
|
4210b7bdf8 | ||
|
|
5e264beba9 | ||
|
|
56c945740f | ||
|
|
820ae23454 | ||
|
|
bfb29f82c9 | ||
|
|
95aa035a27 | ||
|
|
6c69a38a50 | ||
|
|
43ffa995cb | ||
|
|
6c019de514 | ||
|
|
9a11df5688 | ||
|
|
6b223f887a | ||
|
|
9195e0966b | ||
|
|
47a436afb3 | ||
|
|
ab2d269957 | ||
|
|
ebc84b5a70 | ||
|
|
35a2d4e996 | ||
|
|
73117d826d | ||
|
|
df3c9fa822 | ||
|
|
a0f63fddfb | ||
|
|
1b53463a82 | ||
|
|
fc0fedcadd | ||
|
|
ee79a80fc0 | ||
|
|
ee9bf331c4 | ||
|
|
5b63dbe514 | ||
|
|
32434b22dc | ||
|
|
bb77186bbc | ||
|
|
d52259f2ee | ||
|
|
da70d1ecf8 | ||
|
|
e73b22d6d3 | ||
|
|
10c8a1ecf0 | ||
|
|
9b48106943 | ||
|
|
49bb2a81f5 | ||
|
|
65c0ad8eb8 | ||
|
|
345d6d5dfc | ||
|
|
9656111ef4 | ||
|
|
c9395b983c | ||
|
|
ccd05af9d0 | ||
|
|
0e5586f4f4 | ||
|
|
00fc931291 | ||
|
|
81ce21bfbf | ||
|
|
707bf663e5 | ||
|
|
abfd997d0c | ||
|
|
358b41bc0f | ||
|
|
d984cd9177 | ||
|
|
90b5368a05 | ||
|
|
842bb7fa11 | ||
|
|
f55c6ba1c6 | ||
|
|
cd21e800fa | ||
|
|
8cf3344b68 | ||
|
|
373b535bc5 | ||
|
|
2daa34faab | ||
|
|
10170537dd | ||
|
|
598dc08ef6 | ||
|
|
f0238f6063 |
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -29,3 +29,4 @@ coverage/
|
||||
config/web_readme.md
|
||||
.tmp/
|
||||
*.sqlite
|
||||
|
||||
|
||||
10
.snyk
Normal file
10
.snyk
Normal file
@@ -0,0 +1,10 @@
|
||||
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
|
||||
version: v1.13.5
|
||||
ignore: {}
|
||||
# patches apply the minimum changes required to fix a vulnerability
|
||||
patch:
|
||||
SNYK-JS-HTTPSPROXYAGENT-469131:
|
||||
- urllib > proxy-agent > https-proxy-agent:
|
||||
patched: '2019-10-04T23:56:43.938Z'
|
||||
- urllib > proxy-agent > pac-proxy-agent > https-proxy-agent:
|
||||
patched: '2019-10-04T23:56:43.938Z'
|
||||
@@ -1,9 +1,8 @@
|
||||
sudo: false
|
||||
language: node_js
|
||||
node_js:
|
||||
- '4'
|
||||
- '6'
|
||||
- '7'
|
||||
- '8'
|
||||
- '10'
|
||||
addons:
|
||||
- postgresql: '9.3'
|
||||
script: 'make test-travis-all'
|
||||
|
||||
28
Dockerfile
Normal file
28
Dockerfile
Normal file
@@ -0,0 +1,28 @@
|
||||
FROM node:12
|
||||
MAINTAINER Bono Lv <lvscar {aT} gmail.com>
|
||||
|
||||
# Working enviroment
|
||||
ENV \
|
||||
CNPM_DIR="/var/app/cnpmjs.org" \
|
||||
CNPM_DATA_DIR="/var/data/cnpm_data"
|
||||
|
||||
RUN mkdir -p ${CNPM_DIR}
|
||||
|
||||
WORKDIR ${CNPM_DIR}
|
||||
|
||||
COPY package.json ${CNPM_DIR}
|
||||
|
||||
RUN npm set registry https://registry.npm.taobao.org
|
||||
|
||||
RUN npm install --production
|
||||
|
||||
COPY . ${CNPM_DIR}
|
||||
COPY docs/dockerize/config.js ${CNPM_DIR}/config/
|
||||
|
||||
EXPOSE 7001/tcp 7002/tcp
|
||||
|
||||
VOLUME ["/var/data/cnpm_data"]
|
||||
|
||||
# Entrypoint
|
||||
CMD ["node", "dispatch.js"]
|
||||
|
||||
54
History.md
54
History.md
@@ -1,4 +1,56 @@
|
||||
|
||||
3.0.0-alpha.8 / 2017-06-15
|
||||
==================
|
||||
|
||||
* fix: should remove unpublished version on ModuleAbbreviated too (#1192)
|
||||
* docs: Dockerized cnpmjs.org configuration with installation guide (#1191)
|
||||
|
||||
3.0.0-alpha.7 / 2017-06-01
|
||||
==================
|
||||
|
||||
* fix: add missing publish_time property on package list api (#1185)
|
||||
|
||||
3.0.0-alpha.6 / 2017-05-18
|
||||
==================
|
||||
|
||||
* feat: add globalHook on config (#1177)
|
||||
* fix: TypeError caused by invalid engines property (#1151)
|
||||
* test: add new test for application/vnd.npm.install-v1+json request
|
||||
|
||||
3.0.0-alpha.5 / 2017-04-14
|
||||
==================
|
||||
|
||||
* fix: should auto sync missing deprecated property (#1167)
|
||||
|
||||
3.0.0-alpha.4 / 2017-04-12
|
||||
==================
|
||||
|
||||
* fix: add missing deprecated on abbreviated meta (#1165)
|
||||
|
||||
3.0.0-alpha.2 / 2017-03-27
|
||||
==================
|
||||
|
||||
* fix: only get from package_readme table
|
||||
|
||||
3.0.0-alpha.1 / 2017-03-27
|
||||
==================
|
||||
|
||||
* chore: start 3.x
|
||||
* fix: ignore sync npm registry status 502
|
||||
* feat: remove readme from package
|
||||
* feat: [BREAKING_CHANGE] support abbreviated meta
|
||||
|
||||
2.19.4 / 2017-03-26
|
||||
==================
|
||||
|
||||
* feat: need to sync sourceNpmRegistry also (#1153)
|
||||
* docs: change user.json to utf8mb4
|
||||
|
||||
2.19.3 / 2017-02-22
|
||||
==================
|
||||
|
||||
* fix: should get package from orginal registry when package is unpublished (#1130)
|
||||
|
||||
2.19.2 / 2017-01-05
|
||||
==================
|
||||
|
||||
@@ -983,7 +1035,7 @@
|
||||
* npm publish dont contains .jshint*
|
||||
* npm test run jshint
|
||||
* Add jshint check: $ make jshint
|
||||
* use `yield* next` instead of `yield next`
|
||||
* use `yield next` instead of `yield next`
|
||||
* replace dist.u.qiniudn.com with cnpmjs.org/dist
|
||||
|
||||
0.3.5 / 2014-03-05
|
||||
|
||||
15
Makefile
15
Makefile
@@ -1,6 +1,6 @@
|
||||
TESTS = $(shell ls -S `find test -type f -name "*.test.js" -print`)
|
||||
REPORTER = spec
|
||||
TIMEOUT = 30000
|
||||
TIMEOUT = 60000
|
||||
MOCHA_OPTS =
|
||||
DB = sqlite
|
||||
|
||||
@@ -8,7 +8,7 @@ jshint:
|
||||
@node_modules/.bin/jshint .
|
||||
|
||||
init-database:
|
||||
@node test/init_db.js
|
||||
@NODE_ENV=test node test/init_db.js
|
||||
|
||||
init-mysql:
|
||||
@mysql -uroot -e 'DROP DATABASE IF EXISTS cnpmjs_test;'
|
||||
@@ -22,8 +22,8 @@ test: init-database
|
||||
@NODE_ENV=test DB=${DB} node_modules/.bin/mocha \
|
||||
--reporter $(REPORTER) \
|
||||
--timeout $(TIMEOUT) \
|
||||
--require intelli-espower-loader \
|
||||
--require should \
|
||||
--require should-http \
|
||||
--require thunk-mocha \
|
||||
--require ./test/init.js \
|
||||
$(MOCHA_OPTS) \
|
||||
@@ -47,8 +47,8 @@ test-cov cov: init-database
|
||||
-- -u exports \
|
||||
--reporter $(REPORTER) \
|
||||
--timeout $(TIMEOUT) \
|
||||
--require intelli-espower-loader \
|
||||
--require should \
|
||||
--require should-http \
|
||||
--require thunk-mocha \
|
||||
--require ./test/init.js \
|
||||
$(MOCHA_OPTS) \
|
||||
@@ -68,8 +68,8 @@ test-travis: init-database
|
||||
-- -u exports \
|
||||
--reporter dot \
|
||||
--timeout $(TIMEOUT) \
|
||||
--require intelli-espower-loader \
|
||||
--require should \
|
||||
--require should-http \
|
||||
--require thunk-mocha \
|
||||
--require ./test/init.js \
|
||||
$(MOCHA_OPTS) \
|
||||
@@ -96,9 +96,10 @@ contributors:
|
||||
|
||||
autod:
|
||||
@node_modules/.bin/autod -w \
|
||||
--prefix "~" \
|
||||
--registry https://r.cnpmjs.org \
|
||||
--prefix "^" \
|
||||
--exclude public,view,docs,backup,coverage \
|
||||
--dep mysql \
|
||||
--keep should,supertest,should-http,chunkstream,mm,pedding
|
||||
--keep should,supertest,chunkstream,mm,pedding
|
||||
|
||||
.PHONY: test
|
||||
|
||||
124
README.md
124
README.md
@@ -1,10 +1,9 @@
|
||||
cnpmjs.org
|
||||
=======
|
||||
|
||||
[![NPM version][npm-image]][npm-url]
|
||||
[![npm version][npm-image]][npm-url]
|
||||
[![build status][travis-image]][travis-url]
|
||||
[![Test coverage][codecov-image]][codecov-url]
|
||||
[![David deps][david-image]][david-url]
|
||||
[![Known Vulnerabilities][snyk-image]][snyk-url]
|
||||
[![npm download][download-image]][download-url]
|
||||
|
||||
@@ -14,8 +13,6 @@ cnpmjs.org
|
||||
[travis-url]: https://travis-ci.org/cnpm/cnpmjs.org
|
||||
[codecov-image]: https://codecov.io/gh/cnpm/cnpmjs.org/branch/master/graph/badge.svg
|
||||
[codecov-url]: https://codecov.io/gh/cnpm/cnpmjs.org
|
||||
[david-image]: https://img.shields.io/david/cnpm/cnpmjs.org.svg?style=flat-square
|
||||
[david-url]: https://david-dm.org/cnpm/cnpmjs.org
|
||||
[snyk-image]: https://snyk.io/test/npm/cnpmjs.org/badge.svg?style=flat-square
|
||||
[snyk-url]: https://snyk.io/test/npm/cnpmjs.org
|
||||
[download-image]: https://img.shields.io/npm/dm/cnpmjs.org.svg?style=flat-square
|
||||
@@ -23,65 +20,57 @@ cnpmjs.org
|
||||
|
||||

|
||||
|
||||
## What is this?
|
||||
## Description
|
||||
|
||||
Private npm registry and web for Enterprise, base on [koa](http://koajs.com/),
|
||||
MySQL and [Simple Store Service](https://github.com/cnpm/cnpmjs.org/wiki/NFS-Guide).
|
||||
|
||||
Our goal is to provide a low cost maintenance and easy to use solution for private npm.
|
||||
Our goal is to provide a low cost maintenance, easy to use, and easy to scale solution for private npm.
|
||||
|
||||
## What can you do with `cnpmjs.org`
|
||||
## What can you do with `cnpmjs.org`?
|
||||
|
||||
* Build a private npm for your own enterprise. ([alibaba](http://www.alibaba.com/) is using `cnpmjs.org` now)
|
||||
* Build a mirror NPM. (we use it to build a mirror in China: [cnpmjs.org](http://cnpmjs.org/))
|
||||
* Build a completely independent NPM registry to store whatever you like.
|
||||
* Build a npm mirror. (we use it to build a mirror in China: [https://npm.taobao.org/](https://npm.taobao.org/))
|
||||
|
||||
## Features
|
||||
|
||||
* **Support "scoped" packages**: [npm/npm#5239](https://github.com/npm/npm/issues/5239)
|
||||
* **Support [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)**
|
||||
* **Simple to deploy**: only need `mysql` and a [simple store system](https://github.com/cnpm/cnpmjs.org/wiki/NFS-Guide).
|
||||
You can get the source code through `npm` or `git`.
|
||||
* **Low cost and easy maintenance**: `package.json` info store in MySQL, MariaDB, SQLite or PostgreSQL databases,
|
||||
tarball(tgz file) store in CDN or other store systems.
|
||||
* **Automatic synchronization**: automatic synchronization from any registry specified, support two sync modes:
|
||||
- Sync all modules from a specified registry, like [npm registry](http://registry.npmjs.org).
|
||||
- Only sync the modules that exists in your own registry.
|
||||
* **Manual synchronization**: automatic synchronization may has little delay, but you can syn immediately by manually.
|
||||
* **Low cost and easy maintenance**: `package.json` info can store in MySQL, MariaDB, SQLite or PostgreSQL.
|
||||
tarball(tgz file) can store in Amazon S3 or other object storage service.
|
||||
* **Automatic synchronization**: automatically sync from any registry specified. support two sync modes:
|
||||
- Sync all modules from upstream
|
||||
- Only sync the modules after first access.
|
||||
* **Manual synchronization**: automatic synchronization may has little delay. you can sync manually on web page.
|
||||
* **Customized client**: we provide a client [cnpm](https://github.com/cnpm/cnpm)
|
||||
to extend `npm` with more features(`sync` command, [gzip](https://github.com/npm/npm-registry-client/pull/40) support).
|
||||
And it easy to wrap for your own registry which build with `cnpmjs.org`.
|
||||
* **Compatible with NPM client**: you can use the origin NPM client with `cnpmjs.org`,
|
||||
only need to change the registry in config. Even include manual synchronization (through `install` command).
|
||||
* **Version badge**: base on [shields.io](http://shields.io/) 
|
||||
* **Support http_proxy**: if you're behind firewall, need to request through http proxy
|
||||
And it is easy to wrap for your own registry which build with `cnpmjs.org`.
|
||||
* **Compatible with npm client**: you can use the official npm client with `cnpmjs.org`.
|
||||
you only need to change the registry in client config.
|
||||
* **Support http_proxy**: if you're behind a firewall, you can provide a http proxy for cnpmjs.org.
|
||||
|
||||
**PROTIP** Be sure to read [Migrating from 1.x to 2.x](https://github.com/cnpm/cnpmjs.org/wiki/Migrating-from-1.x-to-2.x)
|
||||
as well as [New features in 2.x](https://github.com/cnpm/cnpmjs.org/wiki/New-features-in-2.x).
|
||||
## Docs
|
||||
|
||||
## Getting Start
|
||||
|
||||
* [Deploy a private npm registry in 5 minutes](https://github.com/cnpm/cnpmjs.org/wiki/Deploy-a-private-npm-registry-in-5-minutes)
|
||||
* @[dead-horse](https://github.com/dead-horse): [What is cnpm?](http://deadhorse.me/slides/cnpmjs.html)
|
||||
* install and deploy cnpmjs.org through npm: [examples](https://github.com/cnpm/custom-cnpm-example)
|
||||
* Mirror NPM in China: [cnpmjs.org](http://cnpmjs.org)
|
||||
* [How to deploy](https://github.com/cnpm/cnpmjs.org/wiki/Deploy)
|
||||
* cnpm client: [cnpm](https://github.com/cnpm/cnpm), `npm install -g cnpm`
|
||||
* [How to deploy cnpmjs.org](https://github.com/cnpm/cnpmjs.org/wiki/Deploy)
|
||||
* [Sync packages through `http_proxy`](https://github.com/cnpm/cnpmjs.org/wiki/Sync-packages-through-http_proxy)
|
||||
* [Migrating from 1.x to 2.x](https://github.com/cnpm/cnpmjs.org/wiki/Migrating-from-1.x-to-2.x)
|
||||
* [New features in 2.x](https://github.com/cnpm/cnpmjs.org/wiki/New-features-in-2.x).
|
||||
* [wiki](https://github.com/cnpm/cnpmjs.org/wiki)
|
||||
|
||||
## Develop on your local machine
|
||||
|
||||
### Dependencies
|
||||
|
||||
* [node](http://nodejs.org) >= 4.3.1
|
||||
* [node](http://nodejs.org) >= 8.0.0
|
||||
* Databases: only required one type
|
||||
* [sqlite3](https://npm.taobao.org/package/sqlite3) >= 3.0.2, we use `sqlite3` by default
|
||||
* [MySQL](http://dev.mysql.com/downloads/) >= 0.5.0, include `mysqld` and `mysql cli`. I test on `mysql@5.6.16`.
|
||||
* [MySQL](http://dev.mysql.com/downloads/) >= 5.6.16, include `mysqld` and `mysql cli`. I test on `mysql@5.6.16`.
|
||||
* MariaDB
|
||||
* PostgreSQL
|
||||
|
||||
### Clone codes and run test
|
||||
### Clone code and run test
|
||||
|
||||
```bash
|
||||
# clone from git
|
||||
@@ -103,6 +92,61 @@ $ make autod
|
||||
$ make dev
|
||||
```
|
||||
|
||||
### Dockerized cnpmjs.org Installation Guide
|
||||
|
||||
Cnpmjs.org shipped with a simple but pragmatic Docker Compose configuration.With the configuration, you can set up a MySQL backend cnpmjs.org instance by executing just one command on Docker installed environment.
|
||||
|
||||
#### Preparation
|
||||
|
||||
* [Install Docker](https://www.docker.com/community-edition)
|
||||
* [Install Docker Compose](https://docs.docker.com/compose/install/) (Docker for Mac, Docker for Windows include Docker Compose, so most Mac and Windows users do not need to install Docker Compose separately)
|
||||
* (Optional) Speed up Docker images downloading by setting up [Docker images download accelerator](https://yq.aliyun.com/articles/29941)
|
||||
|
||||
|
||||
#### Dockerized cnpmjs.org control command
|
||||
|
||||
Make sure your current working directory is the root of this GitHub repository.
|
||||
|
||||
##### Run dockerized cnpmjs.org
|
||||
|
||||
```bash
|
||||
$docker-compose up
|
||||
```
|
||||
|
||||
This command will build a Docker image using the current code of repository. Then set up a dockerized MySQL instance with data initialized. After Docker container running, you can access your cnpmjs.org web portal at http://127.0.0.1:7002 and npm register at http://127.0.0.1:7001.
|
||||
|
||||
#### Run cnpmjs.org in the backend
|
||||
|
||||
```bash
|
||||
$docker-compose up -d
|
||||
```
|
||||
|
||||
#### Rebuild cnpmjs.org Docker image
|
||||
|
||||
```bash
|
||||
$docker-compose build
|
||||
```
|
||||
|
||||
#### Remove current dockerized cnpmjs.org instance
|
||||
|
||||
The current configuration set 2 named Docker Volume for your persistent data. If you haven't change the repository directory name, them will be "cnpmjsorg_cnpm-files-volume" & "cnpmjsorg_cnpm-db-volume".
|
||||
|
||||
Be Careful, the following commands will remove them.
|
||||
|
||||
```bash
|
||||
$docker-compose rm
|
||||
$docker volume rm cnpmjsorg_cnpm-files-volume
|
||||
$docker volume rm cnpmjsorg_cnpm-db-volume
|
||||
```
|
||||
|
||||
You can get more information about your data volumes using the below commands:
|
||||
|
||||
```bash
|
||||
$docker volume ls // list all of your Docker volume
|
||||
$docker volume inspect cnpmjsorg_cnpm-files-volume
|
||||
$docker volume inspect cnpmjsorg_cnpm-db-volume
|
||||
```
|
||||
|
||||
## How to contribute
|
||||
|
||||
* Clone the project
|
||||
@@ -112,10 +156,22 @@ $ make dev
|
||||
|
||||
Tips: make sure your code is following the [node-style-guide](https://github.com/felixge/node-style-guide).
|
||||
|
||||
## Top contributors
|
||||
|
||||
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/0)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/1)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/2)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/3)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/4)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/5)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/6)
|
||||
[](https://sourcerer.io/fame/fengmk2/cnpm/cnpmjs.org/links/7)
|
||||
|
||||
|
||||
## Sponsors
|
||||
|
||||
- [](http://click.aliyun.com/m/4288/) (2016.2 - now)
|
||||
- [](http://www.ucloud.cn?sem=sdk-CNPMJS) (2015.3 - 2016.3)
|
||||
|
||||
## License
|
||||
|
||||
|
||||
86
bin/cli.js
86
bin/cli.js
@@ -48,52 +48,59 @@ program.parse(process.argv);
|
||||
|
||||
|
||||
function start(options) {
|
||||
stop(options);
|
||||
var dataDir = options.dataDir || path.join(process.env.HOME, '.cnpmjs.org');
|
||||
mkdirp.sync(dataDir);
|
||||
stop(options)
|
||||
// wait for "stop" method to remove the pid file
|
||||
.then(function () {
|
||||
var dataDir = options.dataDir || path.join(process.env.HOME, '.cnpmjs.org');
|
||||
mkdirp.sync(dataDir);
|
||||
|
||||
var configfile = path.join(dataDir, 'config.json');
|
||||
var config = {};
|
||||
if (fs.existsSync(configfile)) {
|
||||
try {
|
||||
config = require(configfile);
|
||||
} catch (err) {
|
||||
console.warn('load old %s error: %s', configfile, err);
|
||||
}
|
||||
}
|
||||
// config.enableCluster = !!options.cluster;
|
||||
if (options.admins) {
|
||||
config.admins = {};
|
||||
for (var i = 0; i < options.admins.length; i++) {
|
||||
config.admins[options.admins[i]] = options.admins[i] + '@localhost.com';
|
||||
}
|
||||
}
|
||||
if (options.scopes) {
|
||||
config.scopes = options.scopes.map(function (name) {
|
||||
if (name[0] !== '@') {
|
||||
name = '@' + name;
|
||||
var configfile = path.join(dataDir, 'config.json');
|
||||
var config = {};
|
||||
if (fs.existsSync(configfile)) {
|
||||
try {
|
||||
config = require(configfile);
|
||||
} catch (err) {
|
||||
console.warn('load old %s error: %s', configfile, err);
|
||||
}
|
||||
}
|
||||
return name;
|
||||
// config.enableCluster = !!options.cluster;
|
||||
if (options.admins) {
|
||||
config.admins = {};
|
||||
for (var i = 0; i < options.admins.length; i++) {
|
||||
config.admins[options.admins[i]] = options.admins[i] + '@localhost.com';
|
||||
}
|
||||
}
|
||||
if (options.scopes) {
|
||||
config.scopes = options.scopes.map(function (name) {
|
||||
if (name[0] !== '@') {
|
||||
name = '@' + name;
|
||||
}
|
||||
return name;
|
||||
});
|
||||
}
|
||||
|
||||
var configJSON = JSON.stringify(config, null, 2);
|
||||
fs.writeFileSync(configfile, configJSON);
|
||||
|
||||
debug('save config %s to %s', configJSON, configfile);
|
||||
|
||||
// if sqlite db file not exists, init first
|
||||
initDatabase(function() {
|
||||
require('../dispatch');
|
||||
});
|
||||
|
||||
fs.writeFileSync(path.join(dataDir, 'pid'), process.pid + '');
|
||||
});
|
||||
}
|
||||
|
||||
var configJSON = JSON.stringify(config, null, 2);
|
||||
fs.writeFileSync(configfile, configJSON);
|
||||
|
||||
debug('save config %s to %s', configJSON, configfile);
|
||||
|
||||
// if sqlite db file not exists, init first
|
||||
initDatabase(function() {
|
||||
require('../dispatch');
|
||||
});
|
||||
|
||||
fs.writeFileSync(path.join(dataDir, 'pid'), process.pid + '');
|
||||
}
|
||||
|
||||
function stop(options) {
|
||||
var dataDir = options.dataDir || path.join(process.env.HOME, '.cnpmjs.org');
|
||||
var pidfile = path.join(dataDir, 'pid');
|
||||
if (fs.existsSync(pidfile)) {
|
||||
return new Promise(function (resolve) {
|
||||
if (!fs.existsSync(pidfile)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
var pid = Number(fs.readFileSync(pidfile, 'utf8'));
|
||||
treekill(pid, function (err) {
|
||||
if (err) {
|
||||
@@ -102,8 +109,9 @@ function stop(options) {
|
||||
}
|
||||
console.log('cnpmjs.org server:%d stop', pid);
|
||||
fs.unlinkSync(pidfile);
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initDatabase(callback) {
|
||||
|
||||
16
common/cache.js
Normal file
16
common/cache.js
Normal file
@@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
|
||||
const debug = require('debug')('cnpmjs.org:cache');
|
||||
const Redis = require('ioredis');
|
||||
const config = require('../config');
|
||||
|
||||
let client;
|
||||
|
||||
if (config.redisCache.enable) {
|
||||
client = new Redis(config.redisCache.connectOptions);
|
||||
client.on('ready', () => {
|
||||
debug('connect ready, getBuiltinCommands: %j', client.getBuiltinCommands());
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = client;
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - common/mail.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var nodemailer = require('nodemailer');
|
||||
var utility = require('utility');
|
||||
var os = require('os');
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - common/markdown.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var xss = require('xss');
|
||||
var MarkdownIt = require('markdown-it');
|
||||
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - common/sequelize.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var Sequelize = require('sequelize');
|
||||
var DataTypes = require('sequelize/lib/data-types');
|
||||
var config = require('../config');
|
||||
@@ -35,6 +21,7 @@ if (config.mysqlServers && config.database.dialect === 'sqlite') {
|
||||
|
||||
console.warn('[WARNNING] your config.js was too old, please @see https://github.com/cnpm/cnpmjs.org/wiki/Migrating-from-1.x-to-2.x');
|
||||
var server = config.mysqlServers[0];
|
||||
var dialectOptions = config.database && config.database.dialectOptions;
|
||||
config.database = {
|
||||
db: config.mysqlDatabase,
|
||||
username: server.user,
|
||||
@@ -45,10 +32,13 @@ if (config.mysqlServers && config.database.dialect === 'sqlite') {
|
||||
pool: {
|
||||
maxConnections: config.mysqlMaxConnections || 10,
|
||||
minConnections: 0,
|
||||
maxIdleTime: 30000
|
||||
maxIdleTime: 30000,
|
||||
},
|
||||
logging: !!process.env.SQL_DEBUG,
|
||||
};
|
||||
if (dialectOptions) {
|
||||
config.database.dialectOptions = dialectOptions;
|
||||
}
|
||||
}
|
||||
|
||||
var database = config.database;
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - common/urllib.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var urlparse = require('url').parse;
|
||||
var urllib = require('urllib');
|
||||
var HttpAgent = require('agentkeepalive');
|
||||
|
||||
@@ -5,6 +5,7 @@ var copy = require('copy-to');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var os = require('os');
|
||||
var utility = require('utility');
|
||||
|
||||
var version = require('../package.json').version;
|
||||
|
||||
@@ -28,6 +29,8 @@ var config = {
|
||||
registryPort: 7001,
|
||||
webPort: 7002,
|
||||
bindingHost: '127.0.0.1', // only binding on 127.0.0.1 for local access
|
||||
// default is ctx.protocol
|
||||
protocol: '',
|
||||
|
||||
// debug mode
|
||||
// if in debug mode, some middleware like limit wont load
|
||||
@@ -46,6 +49,20 @@ var config = {
|
||||
// web page viewCache
|
||||
viewCache: false,
|
||||
|
||||
// registry http response cache control header
|
||||
// if you are using CDN, can set it to 'max-age=0, s-maxage=10, must-revalidate'
|
||||
// it meaning cache 10s on CDN server and no cache on client side.
|
||||
registryCacheControlHeader: '',
|
||||
// if you are using CDN, can set it to 'Accept, Accept-Encoding'
|
||||
registryVaryHeader: '',
|
||||
// disable package search
|
||||
disableSearch: false,
|
||||
|
||||
// view files directory
|
||||
viewDir: path.join(root, 'view', 'web'),
|
||||
|
||||
customRegistryMiddlewares: [],
|
||||
|
||||
// config for koa-limit middleware
|
||||
// for limit download rates
|
||||
limit: {
|
||||
@@ -120,11 +137,19 @@ var config = {
|
||||
maxIdleTime: 30000
|
||||
},
|
||||
|
||||
dialectOptions: {
|
||||
// if your server run on full cpu load, please set trace to false
|
||||
trace: true,
|
||||
},
|
||||
|
||||
// the storage engine for 'sqlite'
|
||||
// default store into ~/.cnpmjs.org/data.sqlite
|
||||
storage: path.join(dataDir, 'data.sqlite'),
|
||||
|
||||
logging: !!process.env.SQL_DEBUG,
|
||||
|
||||
// enable proxy npm audits request or not
|
||||
enableNpmAuditsProxy: true,
|
||||
},
|
||||
|
||||
// package tarball store in local filesystem by default
|
||||
@@ -133,6 +158,8 @@ var config = {
|
||||
}),
|
||||
// if set true, will 302 redirect to `nfs.url(dist.key)`
|
||||
downloadRedirectToNFS: false,
|
||||
// don't check database and just download tgz from nfs
|
||||
downloadTgzDontCheckModule: false,
|
||||
|
||||
// registry url name
|
||||
registryHost: 'r.cnpmjs.org',
|
||||
@@ -169,6 +196,7 @@ var config = {
|
||||
// If you want to directly sync from official npm's registry
|
||||
// please drop them an email first
|
||||
sourceNpmRegistry: 'https://registry.npm.taobao.org',
|
||||
sourceNpmWeb: 'https://npm.taobao.org',
|
||||
|
||||
// upstream registry is base on cnpm/cnpmjs.org or not
|
||||
// if your upstream is official npm registry, please turn it off
|
||||
@@ -197,14 +225,36 @@ var config = {
|
||||
|
||||
// sync devDependencies or not, default is false
|
||||
syncDevDependencies: false,
|
||||
// try to remove all deleted versions from original registry
|
||||
syncDeletedVersions: true,
|
||||
|
||||
// changes streaming sync
|
||||
syncChangesStream: false,
|
||||
syncDownloadOptions: {
|
||||
// formatRedirectUrl: function (url, location)
|
||||
},
|
||||
handleSyncRegistry: 'http://127.0.0.1:7001',
|
||||
|
||||
// badge subject on http://shields.io/
|
||||
badgePrefixURL: 'https://img.shields.io/badge',
|
||||
// default badge subject
|
||||
badgeSubject: 'cnpm',
|
||||
// defautl use https://badgen.net/
|
||||
badgeService: {
|
||||
url: function(subject, status, options) {
|
||||
options = options || {};
|
||||
let url = `https://badgen.net/badge/${utility.encodeURIComponent(subject)}/${utility.encodeURIComponent(status)}`;
|
||||
if (options.color) {
|
||||
url += `/${utility.encodeURIComponent(options.color)}`;
|
||||
}
|
||||
if (options.icon) {
|
||||
url += `?icon=${utility.encodeURIComponent(options.icon)}`;
|
||||
}
|
||||
return url;
|
||||
},
|
||||
},
|
||||
|
||||
packagephobiaURL: 'https://packagephobia.now.sh',
|
||||
packagephobiaSupportPrivatePackage: false,
|
||||
packagephobiaMinDownloadCount: 1000,
|
||||
|
||||
// custom user service, @see https://github.com/cnpm/cnpmjs.org/wiki/Use-Your-Own-User-Authorization
|
||||
// when you not intend to ingegrate with your company's user system, then use null, it would
|
||||
@@ -221,8 +271,36 @@ var config = {
|
||||
|
||||
// snyk.io root url
|
||||
snykUrl: 'https://snyk.io',
|
||||
|
||||
// https://github.com/cnpm/cnpmjs.org/issues/1149
|
||||
// if enable this option, must create module_abbreviated and package_readme table in database
|
||||
enableAbbreviatedMetadata: false,
|
||||
|
||||
// global hook function: function* (envelope) {}
|
||||
// envelope format please see https://github.com/npm/registry/blob/master/docs/hooks/hooks-payload.md#payload
|
||||
globalHook: null,
|
||||
|
||||
opensearch: {
|
||||
host: '',
|
||||
},
|
||||
|
||||
// redis cache
|
||||
redisCache: {
|
||||
enable: false,
|
||||
connectOptions: null,
|
||||
},
|
||||
};
|
||||
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
config.enableAbbreviatedMetadata = true;
|
||||
config.customRegistryMiddlewares.push(() => {
|
||||
return function* (next) {
|
||||
this.set('x-custom-middleware', 'true');
|
||||
yield next;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
var customConfig;
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/deprecate.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../../../services/package');
|
||||
|
||||
module.exports = deprecateVersions;
|
||||
@@ -37,9 +23,10 @@ function* deprecateVersions() {
|
||||
if (!row) {
|
||||
// some version not exists
|
||||
this.status = 400;
|
||||
const error = '[version_error] Some versions: ' + JSON.stringify(Object.keys(body.versions)) + ' not found';
|
||||
this.body = {
|
||||
error: 'version_error',
|
||||
reason: 'Some versions: ' + JSON.stringify(Object.keys(body.versions)) + ' not found'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -51,10 +38,10 @@ function* deprecateVersions() {
|
||||
}
|
||||
yield updateTasks;
|
||||
// update last modified
|
||||
yield* packageService.updateModuleLastModified(name);
|
||||
yield packageService.updateModuleLastModified(name);
|
||||
|
||||
this.status = 201;
|
||||
this.body = {
|
||||
ok: true
|
||||
ok: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ exports.index = function* () {
|
||||
exports.save = function* () {
|
||||
var name = this.params.name || this.params[0];
|
||||
yield packageService.removeModuleTags(name);
|
||||
yield* exports.update.call(this);
|
||||
yield exports.update.call(this);
|
||||
};
|
||||
|
||||
// POST /-/package/:pkg/dist-tags -- Add/modify dist-tags from provided object body (merge)
|
||||
@@ -49,9 +49,10 @@ exports.set = function* () {
|
||||
var pkg = yield packageService.getModule(name, version);
|
||||
if (!pkg) {
|
||||
this.status = 400;
|
||||
const error = '[version_error] ' + name + '@' + version + ' not exists';
|
||||
this.body = {
|
||||
error: 'version_error',
|
||||
reason: name + '@' + version + ' not exists'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -67,9 +68,10 @@ exports.destroy = function* () {
|
||||
var tag = this.params.tag || this.params[1];
|
||||
if (tag === 'latest') {
|
||||
this.status = 400;
|
||||
const error = '[dist_tag_error] Can\'t not delete latest tag';
|
||||
this.body = {
|
||||
error: 'dist_tag_error',
|
||||
reason: 'Can\'t not delete latest tag',
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
/**!
|
||||
* Copyright(c) cnpm and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:download');
|
||||
var mime = require('mime');
|
||||
var utility = require('utility');
|
||||
@@ -25,37 +13,51 @@ var packageService = require('../../../services/package');
|
||||
var downloadTotalService = require('../../../services/download_total');
|
||||
var config = require('../../../config');
|
||||
|
||||
var _downloads = {};
|
||||
let globalDownloads = new Map();
|
||||
|
||||
module.exports = function* download(next) {
|
||||
var name = this.params.name || this.params[0];
|
||||
var filename = this.params.filename || this.params[1];
|
||||
var version = filename.slice(name.length + 1, -4);
|
||||
var row = yield packageService.getModule(name, version);
|
||||
// can not get dist
|
||||
var url = null;
|
||||
|
||||
var query = this.query || {};
|
||||
// allow download from specific store bucket
|
||||
var options = query.bucket ? { bucket: query.bucket } : null;
|
||||
|
||||
if (typeof nfs.url === 'function') {
|
||||
if (is.generatorFunction(nfs.url)) {
|
||||
url = yield nfs.url(common.getCDNKey(name, filename));
|
||||
url = yield nfs.url(common.getCDNKey(name, filename), options);
|
||||
} else {
|
||||
url = nfs.url(common.getCDNKey(name, filename));
|
||||
url = nfs.url(common.getCDNKey(name, filename), options);
|
||||
}
|
||||
}
|
||||
|
||||
debug('download %s %s %s %s', name, filename, version, url);
|
||||
|
||||
if (!row || !row.package || !row.package.dist) {
|
||||
if (!url) {
|
||||
return yield* next;
|
||||
}
|
||||
// don't check database and just download tgz from nfs
|
||||
if (config.downloadTgzDontCheckModule && url) {
|
||||
this.status = 302;
|
||||
this.set('Location', url);
|
||||
_downloads[name] = (_downloads[name] || 0) + 1;
|
||||
const count = (globalDownloads.get(name) || 0) + 1;
|
||||
globalDownloads.set(name, count);
|
||||
return;
|
||||
}
|
||||
|
||||
_downloads[name] = (_downloads[name] || 0) + 1;
|
||||
var row = yield packageService.getModule(name, version);
|
||||
if (!row || !row.package || !row.package.dist) {
|
||||
if (!url) {
|
||||
return yield next;
|
||||
}
|
||||
this.status = 302;
|
||||
this.set('Location', url);
|
||||
const count = (globalDownloads.get(name) || 0) + 1;
|
||||
globalDownloads.set(name, count);
|
||||
return;
|
||||
}
|
||||
|
||||
const count = (globalDownloads.get(name) || 0) + 1;
|
||||
globalDownloads.set(name, count);
|
||||
|
||||
if (config.downloadRedirectToNFS && url) {
|
||||
this.status = 302;
|
||||
@@ -84,19 +86,29 @@ module.exports = function* download(next) {
|
||||
this.body = yield downloadAsReadStream(dist.key);
|
||||
};
|
||||
|
||||
var saving = false;
|
||||
defer.setInterval(function* () {
|
||||
// save download count
|
||||
var totals = [];
|
||||
for (var name in _downloads) {
|
||||
var count = _downloads[name];
|
||||
totals.push([name, count]);
|
||||
}
|
||||
_downloads = {};
|
||||
|
||||
if (totals.length === 0) {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
|
||||
// save download count
|
||||
var totals = [];
|
||||
var allCount = 0;
|
||||
for (const [ name, count ] of globalDownloads) {
|
||||
if (name !== '__all__') {
|
||||
totals.push([name, count]);
|
||||
}
|
||||
allCount += count;
|
||||
}
|
||||
globalDownloads = new Map();
|
||||
|
||||
if (allCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
saving = true;
|
||||
totals.push([ '__all__', allCount ]);
|
||||
debug('save download total: %j', totals);
|
||||
|
||||
var date = utility.YYYYMMDD();
|
||||
@@ -105,14 +117,16 @@ defer.setInterval(function* () {
|
||||
var name = item[0];
|
||||
var count = item[1];
|
||||
try {
|
||||
yield* downloadTotalService.plusModuleTotal({ name: name, date: date, count: count });
|
||||
yield downloadTotalService.plusModuleTotal({ name: name, date: date, count: count });
|
||||
} catch (err) {
|
||||
if (err.name !== 'SequelizeUniqueConstraintError') {
|
||||
err.message += '; name: ' + name + ', count: ' + count + ', date: ' + date;
|
||||
logger.error(err);
|
||||
}
|
||||
// save back to _downloads, try again next time
|
||||
_downloads[name] = (_downloads[name] || 0) + count;
|
||||
// save back to globalDownloads, try again next time
|
||||
count = (globalDownloads.get(name) || 0) + count;
|
||||
globalDownloads.set(name, count);
|
||||
}
|
||||
}
|
||||
saving = false;
|
||||
}, 5000 + Math.ceil(Math.random() * 1000));
|
||||
|
||||
@@ -12,9 +12,10 @@ module.exports = function* downloadTotal() {
|
||||
|| !range[0].match(DATE_REG)
|
||||
|| !range[1].match(DATE_REG)) {
|
||||
this.status = 400;
|
||||
const error = '[range_error] range must be YYYY-MM-DD:YYYY-MM-DD style';
|
||||
this.body = {
|
||||
error: 'range_error',
|
||||
reason: 'range must be YYYY-MM-DD:YYYY-MM-DD style'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,30 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:list');
|
||||
var utility = require('utility');
|
||||
var packageService = require('../../../services/package');
|
||||
var common = require('../../../lib/common');
|
||||
var SyncModuleWorker = require('../../sync_module_worker');
|
||||
var config = require('../../../config');
|
||||
const cache = require('../../../common/cache');
|
||||
const logger = require('../../../common/logger');
|
||||
|
||||
// https://forum.nginx.org/read.php?2,240120,240120#msg-240120
|
||||
// should set weak etag avoid nginx remove it
|
||||
function etag(objs) {
|
||||
return 'W/"' + utility.md5(JSON.stringify(objs)) + '"';
|
||||
}
|
||||
|
||||
/**
|
||||
* list all version of a module
|
||||
* GET /:name
|
||||
*/
|
||||
module.exports = function* list() {
|
||||
var orginalName = this.params.name || this.params[0];
|
||||
var name = orginalName;
|
||||
const name = this.params.name || this.params[0];
|
||||
// sync request will contain this query params
|
||||
let noCache = this.query.cache === '0';
|
||||
if (!noCache) {
|
||||
const ua = this.headers['user-agent'] || '';
|
||||
// old sync client will request with these user-agent
|
||||
if (ua.indexOf('npm_service.cnpmjs.org/') !== -1) {
|
||||
noCache = true;
|
||||
}
|
||||
}
|
||||
const isJSONPRequest = this.query.callback;
|
||||
let cacheKey;
|
||||
let needAbbreviatedMeta = false;
|
||||
let abbreviatedMetaType = 'application/vnd.npm.install-v1+json';
|
||||
if (config.enableAbbreviatedMetadata && this.accepts([ 'json', abbreviatedMetaType ]) === abbreviatedMetaType) {
|
||||
needAbbreviatedMeta = true;
|
||||
if (cache && !isJSONPRequest) {
|
||||
cacheKey = `list-${name}-v1`;
|
||||
}
|
||||
}
|
||||
|
||||
if (cacheKey && !noCache) {
|
||||
const values = yield cache.hmget(cacheKey, 'etag', 'body');
|
||||
if (values && values[0] && values[1]) {
|
||||
this.body = values[1];
|
||||
this.type = 'json';
|
||||
this.etag = values[0];
|
||||
this.set('x-hit-cache', cacheKey);
|
||||
debug('hmget %s success, etag:%j', cacheKey, values[0]);
|
||||
if (config.registryCacheControlHeader) {
|
||||
this.set('cache-control', config.registryCacheControlHeader);
|
||||
}
|
||||
if (config.registryVaryHeader) {
|
||||
this.set('vary', config.registryVaryHeader);
|
||||
}
|
||||
return;
|
||||
}
|
||||
debug('hmget %s missing, %j', cacheKey, values);
|
||||
}
|
||||
|
||||
var rs = yield [
|
||||
packageService.getModuleLastModified(name),
|
||||
packageService.listModuleTags(name)
|
||||
packageService.listModuleTags(name),
|
||||
];
|
||||
var modifiedTime = rs[0];
|
||||
var tags = rs[1];
|
||||
|
||||
debug('show %s(%s), last modified: %s, tags: %j', name, orginalName, modifiedTime, tags);
|
||||
debug('show %s, last modified: %s, tags: %j', name, modifiedTime, tags);
|
||||
if (modifiedTime) {
|
||||
// find out the latest modfied time
|
||||
// because update tags only modfied tag, wont change module gmt_modified
|
||||
@@ -44,6 +87,20 @@ module.exports = function* list() {
|
||||
}
|
||||
}
|
||||
|
||||
if (needAbbreviatedMeta) {
|
||||
var rows = yield packageService.listModuleAbbreviatedsByName(name);
|
||||
if (rows.length > 0) {
|
||||
yield handleAbbreviatedMetaRequest(this, name, modifiedTime, tags, rows, cacheKey);
|
||||
return;
|
||||
}
|
||||
var fullRows = yield packageService.listModulesByName(name);
|
||||
if (fullRows.length > 0) {
|
||||
// no abbreviated meta rows, use the full meta convert to abbreviated meta
|
||||
yield handleAbbreviatedMetaRequestWithFullMeta(this, name, modifiedTime, tags, fullRows);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var r = yield [
|
||||
packageService.listModulesByName(name),
|
||||
packageService.listStarUserNames(name),
|
||||
@@ -67,18 +124,18 @@ module.exports = function* list() {
|
||||
|
||||
if (rows.length === 0) {
|
||||
// check if unpublished
|
||||
var unpublishedInfo = yield* packageService.getUnpublishedModule(name);
|
||||
var unpublishedInfo = yield packageService.getUnpublishedModule(name);
|
||||
debug('show unpublished %j', unpublishedInfo);
|
||||
if (unpublishedInfo) {
|
||||
this.status = 404;
|
||||
this.body = {
|
||||
_id: orginalName,
|
||||
name: orginalName,
|
||||
this.jsonp = {
|
||||
_id: name,
|
||||
name: name,
|
||||
time: {
|
||||
modified: unpublishedInfo.package.time,
|
||||
unpublished: unpublishedInfo.package,
|
||||
},
|
||||
_attachments: {}
|
||||
_attachments: {},
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -89,15 +146,16 @@ module.exports = function* list() {
|
||||
if (rows.length === 0) {
|
||||
if (!this.allowSync) {
|
||||
this.status = 404;
|
||||
this.body = {
|
||||
error: 'not_found',
|
||||
reason: 'document not found',
|
||||
const error = '[not_found] document not found';
|
||||
this.jsonp = {
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// start sync
|
||||
var logId = yield* SyncModuleWorker.sync(name, 'sync-by-install');
|
||||
var logId = yield SyncModuleWorker.sync(name, 'sync-by-install');
|
||||
debug('start sync %s, get log id %s', name, logId);
|
||||
|
||||
return this.redirect(config.officialNpmRegistry + this.url);
|
||||
@@ -114,6 +172,7 @@ module.exports = function* list() {
|
||||
|
||||
// set versions and times
|
||||
var versions = {};
|
||||
var allVersionString = '';
|
||||
var times = {};
|
||||
var attachments = {};
|
||||
var createdTime = null;
|
||||
@@ -129,6 +188,7 @@ module.exports = function* list() {
|
||||
pkg.publish_time = pkg.publish_time || row.publish_time;
|
||||
|
||||
versions[pkg.version] = pkg;
|
||||
allVersionString += pkg.version + ',';
|
||||
|
||||
var t = times[pkg.version] = row.publish_time ? new Date(row.publish_time) : row.gmt_modified;
|
||||
if ((!distTags.latest && !latestMod) || distTags.latest === pkg.version) {
|
||||
@@ -170,12 +230,19 @@ module.exports = function* list() {
|
||||
distTags.latest = pkg.version;
|
||||
}
|
||||
|
||||
if (!readme && config.enableAbbreviatedMetadata) {
|
||||
var packageReadme = yield packageService.getPackageReadme(name);
|
||||
if (packageReadme) {
|
||||
readme = packageReadme.readme;
|
||||
}
|
||||
}
|
||||
|
||||
var info = {
|
||||
_id: orginalName,
|
||||
_id: name,
|
||||
_rev: rev,
|
||||
name: orginalName,
|
||||
name: name,
|
||||
description: pkg.description,
|
||||
"dist-tags": distTags,
|
||||
'dist-tags': distTags,
|
||||
maintainers: pkg.maintainers,
|
||||
time: times,
|
||||
users: starUsers,
|
||||
@@ -191,6 +258,182 @@ module.exports = function* list() {
|
||||
info.bugs = pkg.bugs;
|
||||
info.license = pkg.license;
|
||||
|
||||
debug('show module %s: %s, latest: %s', orginalName, rev, latestMod.version);
|
||||
debug('show module %s: %s, latest: %s', name, rev, latestMod.version);
|
||||
this.jsonp = info;
|
||||
// use faster etag
|
||||
this.etag = etag([
|
||||
modifiedTime,
|
||||
distTags,
|
||||
pkg.maintainers,
|
||||
allVersionString,
|
||||
]);
|
||||
|
||||
if (config.registryCacheControlHeader) {
|
||||
this.set('cache-control', config.registryCacheControlHeader);
|
||||
}
|
||||
if (config.registryVaryHeader) {
|
||||
this.set('vary', config.registryVaryHeader);
|
||||
}
|
||||
};
|
||||
|
||||
function* handleAbbreviatedMetaRequest(ctx, name, modifiedTime, tags, rows, cacheKey) {
|
||||
debug('show %s got %d rows, %d tags, modifiedTime: %s', name, rows.length, tags.length, modifiedTime);
|
||||
const isJSONPRequest = ctx.query.callback;
|
||||
var latestMod = null;
|
||||
// set tags
|
||||
var distTags = {};
|
||||
for (var i = 0; i < tags.length; i++) {
|
||||
var t = tags[i];
|
||||
distTags[t.tag] = t.version;
|
||||
}
|
||||
|
||||
// set versions and times
|
||||
var versions = {};
|
||||
var allVersionString = '';
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
var row = rows[i];
|
||||
var pkg = row.package;
|
||||
common.setDownloadURL(pkg, ctx);
|
||||
pkg._publish_on_cnpm = undefined;
|
||||
pkg.publish_time = pkg.publish_time || row.publish_time;
|
||||
|
||||
versions[pkg.version] = pkg;
|
||||
allVersionString += pkg.version + ',';
|
||||
|
||||
if ((!distTags.latest && !latestMod) || distTags.latest === pkg.version) {
|
||||
latestMod = row;
|
||||
}
|
||||
}
|
||||
|
||||
if (!latestMod) {
|
||||
latestMod = rows[0];
|
||||
}
|
||||
|
||||
if (tags.length === 0) {
|
||||
// some sync error reason, will cause tags missing
|
||||
// set latest tag at least
|
||||
distTags.latest = latestMod.package.version;
|
||||
}
|
||||
|
||||
var info = {
|
||||
name: name,
|
||||
modified: modifiedTime,
|
||||
'dist-tags': distTags,
|
||||
versions: versions,
|
||||
};
|
||||
|
||||
debug('show %j', info);
|
||||
// use faster etag
|
||||
const resultEtag = etag([
|
||||
modifiedTime,
|
||||
distTags,
|
||||
allVersionString,
|
||||
]);
|
||||
|
||||
if (isJSONPRequest) {
|
||||
ctx.jsonp = info;
|
||||
} else {
|
||||
ctx.body = JSON.stringify(info);
|
||||
ctx.type = 'json';
|
||||
// set cache
|
||||
if (cacheKey) {
|
||||
// set cache async, dont block the response
|
||||
cache.pipeline()
|
||||
.hmset(cacheKey, 'etag', resultEtag, 'body', ctx.body)
|
||||
// cache 120s
|
||||
.expire(cacheKey, 120)
|
||||
.exec()
|
||||
.catch(err => {
|
||||
logger.error(err);
|
||||
});
|
||||
}
|
||||
}
|
||||
ctx.etag = resultEtag;
|
||||
if (config.registryCacheControlHeader) {
|
||||
ctx.set('cache-control', config.registryCacheControlHeader);
|
||||
}
|
||||
if (config.registryVaryHeader) {
|
||||
ctx.set('vary', config.registryVaryHeader);
|
||||
}
|
||||
}
|
||||
|
||||
function* handleAbbreviatedMetaRequestWithFullMeta(ctx, name, modifiedTime, tags, rows) {
|
||||
debug('show %s got %d rows, %d tags',
|
||||
name, rows.length, tags.length);
|
||||
var latestMod = null;
|
||||
// set tags
|
||||
var distTags = {};
|
||||
for (var i = 0; i < tags.length; i++) {
|
||||
var t = tags[i];
|
||||
distTags[t.tag] = t.version;
|
||||
}
|
||||
|
||||
// set versions and times
|
||||
var versions = {};
|
||||
var allVersionString = '';
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
var row = rows[i];
|
||||
// pkg is string ... ignore it
|
||||
if (typeof row.package === 'string') {
|
||||
continue;
|
||||
}
|
||||
// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object
|
||||
var pkg = {
|
||||
name: row.package.name,
|
||||
version: row.package.version,
|
||||
deprecated: row.package.deprecated,
|
||||
dependencies: row.package.dependencies,
|
||||
optionalDependencies: row.package.optionalDependencies,
|
||||
devDependencies: row.package.devDependencies,
|
||||
bundleDependencies: row.package.bundleDependencies,
|
||||
peerDependencies: row.package.peerDependencies,
|
||||
bin: row.package.bin,
|
||||
directories: row.package.directories,
|
||||
dist: row.package.dist,
|
||||
engines: row.package.engines,
|
||||
_hasShrinkwrap: row.package._hasShrinkwrap,
|
||||
publish_time: row.package.publish_time || row.publish_time,
|
||||
};
|
||||
common.setDownloadURL(pkg, ctx);
|
||||
|
||||
versions[pkg.version] = pkg;
|
||||
allVersionString += pkg.version + ',';
|
||||
|
||||
if ((!distTags.latest && !latestMod) || distTags.latest === pkg.version) {
|
||||
latestMod = row;
|
||||
}
|
||||
}
|
||||
|
||||
if (!latestMod) {
|
||||
latestMod = rows[0];
|
||||
}
|
||||
|
||||
if (tags.length === 0) {
|
||||
// some sync error reason, will cause tags missing
|
||||
// set latest tag at least
|
||||
distTags.latest = latestMod.package.version;
|
||||
}
|
||||
|
||||
var info = {
|
||||
name: name,
|
||||
modified: modifiedTime,
|
||||
'dist-tags': distTags,
|
||||
versions: versions,
|
||||
};
|
||||
|
||||
debug('show %j', info);
|
||||
ctx.jsonp = info;
|
||||
// use faster etag
|
||||
ctx.etag = etag([
|
||||
modifiedTime,
|
||||
distTags,
|
||||
allVersionString,
|
||||
]);
|
||||
|
||||
if (config.registryCacheControlHeader) {
|
||||
ctx.set('cache-control', config.registryCacheControlHeader);
|
||||
}
|
||||
if (config.registryVaryHeader) {
|
||||
ctx.set('vary', config.registryVaryHeader);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/list_all.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../../../services/package');
|
||||
|
||||
// GET /-/all
|
||||
@@ -21,7 +7,7 @@ var packageService = require('../../../services/package');
|
||||
// https://github.com/npm/npm-registry-client/blob/master/lib/get.js#L86
|
||||
module.exports = function* () {
|
||||
var updated = Date.now();
|
||||
var names = yield* packageService.listAllPublicModuleNames();
|
||||
var names = yield packageService.listAllPublicModuleNames();
|
||||
var result = { _updated: updated };
|
||||
names.forEach(function (name) {
|
||||
result[name] = true;
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
/**!
|
||||
* Copyright(c) cnpm and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../../../services/package');
|
||||
const packageService = require('../../../services/package');
|
||||
const config = require('../../../config');
|
||||
|
||||
// GET /-/short
|
||||
// List all packages names only
|
||||
// List public all packages names only
|
||||
module.exports = function* () {
|
||||
if (this.query.private_only) {
|
||||
const tasks = [];
|
||||
for (let i = 0; i < config.scopes.length; i++) {
|
||||
const scope = config.scopes[i];
|
||||
tasks.push(packageService.listPrivateModulesByScope(scope));
|
||||
}
|
||||
|
||||
if (config.privatePackages && config.privatePackages.length > 0) {
|
||||
tasks.push(packageService.listModules(config.privatePackages));
|
||||
}
|
||||
|
||||
const results = yield tasks;
|
||||
const names = [];
|
||||
for (const rows of results) {
|
||||
for (const row of rows) {
|
||||
names.push(row.name);
|
||||
}
|
||||
}
|
||||
this.body = names;
|
||||
return;
|
||||
}
|
||||
|
||||
this.body = yield packageService.listAllPublicModuleNames();
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
var packageService = require('../../../services/package');
|
||||
|
||||
var A_WEEK_MS = 3600000 * 24 * 7;
|
||||
var TWA_DAYS_MS = 3600000 * 24 * 2;
|
||||
|
||||
// GET /-/all/since?stale=update_after&startkey={key}
|
||||
// List packages names since startkey
|
||||
@@ -11,9 +12,10 @@ module.exports = function* listSince() {
|
||||
var query = this.query;
|
||||
if (query.stale !== 'update_after') {
|
||||
this.status = 400;
|
||||
const error = '[query_parse_error] Invalid value for `stale`.';
|
||||
this.body = {
|
||||
error: 'query_parse_error',
|
||||
reason: 'Invalid value for `stale`.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -21,18 +23,19 @@ module.exports = function* listSince() {
|
||||
var startkey = Number(query.startkey);
|
||||
if (!startkey) {
|
||||
this.status = 400;
|
||||
const error = '[query_parse_error] Invalid value for `startkey`.';
|
||||
this.body = {
|
||||
error: 'query_parse_error',
|
||||
reason: 'Invalid value for `startkey`.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var updated = Date.now();
|
||||
if (updated - startkey > A_WEEK_MS) {
|
||||
startkey = updated - A_WEEK_MS;
|
||||
console.warn('[%s] list modules since time out of range: query: %j, ip: %s',
|
||||
Date(), query, this.ip);
|
||||
startkey = updated - TWA_DAYS_MS;
|
||||
console.warn('[%s] list modules since time out of range: query: %j, ip: %s, limit to %s',
|
||||
Date(), query, this.ip, startkey);
|
||||
}
|
||||
|
||||
var names = yield packageService.listPublicModuleNamesSince(startkey);
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/remove.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:remove');
|
||||
var urlparse = require('url').parse;
|
||||
var packageService = require('../../../services/package');
|
||||
@@ -28,11 +14,11 @@ module.exports = function* remove(next) {
|
||||
var rev = this.params.rev || this.params[1];
|
||||
debug('remove all the module with name: %s, id: %s', name, rev);
|
||||
|
||||
var mods = yield* packageService.listModulesByName(name);
|
||||
var mods = yield packageService.listModulesByName(name);
|
||||
debug('removeAll module %s: %d', name, mods.length);
|
||||
var mod = mods[0];
|
||||
if (!mod) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
yield [
|
||||
@@ -61,7 +47,7 @@ module.exports = function* remove(next) {
|
||||
}
|
||||
|
||||
// remove the maintainers
|
||||
yield* packageService.removeAllMaintainers(name);
|
||||
yield packageService.removeAllMaintainers(name);
|
||||
|
||||
this.body = { ok: true };
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/remove_version.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:remove_version');
|
||||
var packageService = require('../../../services/package');
|
||||
var nfs = require('../../../common/nfs');
|
||||
@@ -33,13 +19,13 @@ module.exports = function* removeOneVersion(next) {
|
||||
version = version.substring(0, version.lastIndexOf('.tgz'));
|
||||
}
|
||||
if (!version) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
debug('remove tarball with filename: %s, version: %s, revert to => rev id: %s', filename, version, id);
|
||||
|
||||
if (isNaN(id)) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var rs = yield [
|
||||
@@ -49,7 +35,7 @@ module.exports = function* removeOneVersion(next) {
|
||||
var revertTo = rs[0];
|
||||
var mod = rs[1]; // module need to delete
|
||||
if (!mod || mod.name !== name) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var key = mod.package && mod.package.dist && mod.package.dist.key;
|
||||
@@ -68,7 +54,7 @@ module.exports = function* removeOneVersion(next) {
|
||||
logger.error(err);
|
||||
}
|
||||
// remove version from table
|
||||
yield* packageService.removeModulesByNameAndVersions(name, [version]);
|
||||
yield packageService.removeModulesByNameAndVersions(name, [version]);
|
||||
debug('removed %s@%s', name, version);
|
||||
this.body = { ok: true };
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/save.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:save');
|
||||
var crypto = require('crypto');
|
||||
var deprecateVersions = require('./deprecate');
|
||||
@@ -21,6 +7,7 @@ var packageService = require('../../../services/package');
|
||||
var common = require('../../../lib/common');
|
||||
var nfs = require('../../../common/nfs');
|
||||
var config = require('../../../config');
|
||||
var hook = require('../../../services/hook');
|
||||
|
||||
// old flows:
|
||||
// 1. add()
|
||||
@@ -44,21 +31,23 @@ module.exports = function* save(next) {
|
||||
var version = Object.keys(pkg.versions || {})[0];
|
||||
if (!version) {
|
||||
this.status = 400;
|
||||
const error = '[version_error] package.versions is empty';
|
||||
this.body = {
|
||||
error: 'version_error',
|
||||
reason: 'package.versions is empty'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// check maintainers
|
||||
var result = yield* packageService.authMaintainer(name, username);
|
||||
var result = yield packageService.authMaintainer(name, username);
|
||||
if (!result.isMaintainer) {
|
||||
this.status = 403;
|
||||
const error = '[forbidden] ' + username + ' not authorized to modify ' + name +
|
||||
', please contact maintainers: ' + result.maintainers.join(', ');
|
||||
this.body = {
|
||||
error: 'forbidden user',
|
||||
reason: username + ' not authorized to modify ' + name +
|
||||
', please contact maintainers: ' + result.maintainers.join(', ')
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -73,13 +62,14 @@ module.exports = function* save(next) {
|
||||
}
|
||||
}
|
||||
if (hasDeprecated) {
|
||||
return yield* deprecateVersions.call(this, next);
|
||||
return yield deprecateVersions.call(this, next);
|
||||
}
|
||||
|
||||
this.status = 400;
|
||||
const error = '[attachment_error] package._attachments is empty';
|
||||
this.body = {
|
||||
error: 'attachment_error',
|
||||
reason: 'package._attachments is empty'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -91,9 +81,10 @@ module.exports = function* save(next) {
|
||||
// should never happened in normal request
|
||||
if (!maintainers) {
|
||||
this.status = 400;
|
||||
const error = '[maintainers_error] request body need maintainers';
|
||||
this.body = {
|
||||
error: 'maintainers error',
|
||||
reason: 'request body need maintainers'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -108,9 +99,10 @@ module.exports = function* save(next) {
|
||||
});
|
||||
if (m.length === 0) {
|
||||
this.status = 403;
|
||||
const error = '[maintainers_error] ' + username + ' does not in maintainer list';
|
||||
this.body = {
|
||||
error: 'maintainers error',
|
||||
reason: username + ' does not in maintainer list'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -125,9 +117,10 @@ module.exports = function* save(next) {
|
||||
|
||||
if (tags.length === 0) {
|
||||
this.status = 400;
|
||||
const error = '[invalid] dist-tags should not be empty';
|
||||
this.body = {
|
||||
error: 'invalid',
|
||||
reason: 'dist-tags should not be empty'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -135,34 +128,36 @@ module.exports = function* save(next) {
|
||||
debug('%s publish new %s:%s, attachment size: %s, maintainers: %j, distTags: %j',
|
||||
username, name, version, attachment.length, versionPackage.maintainers, distTags);
|
||||
|
||||
var exists = yield* packageService.getModule(name, version);
|
||||
var exists = yield packageService.getModule(name, version);
|
||||
var shasum;
|
||||
if (exists) {
|
||||
this.status = 403;
|
||||
const error = '[forbidden] cannot modify pre-existing version: ' + version;
|
||||
this.body = {
|
||||
error: 'forbidden',
|
||||
reason: 'cannot modify pre-existing version: ' + version
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// upload attachment
|
||||
var tarballBuffer;
|
||||
tarballBuffer = new Buffer(attachment.data, 'base64');
|
||||
tarballBuffer = Buffer.from(attachment.data, 'base64');
|
||||
|
||||
if (tarballBuffer.length !== attachment.length) {
|
||||
this.status = 403;
|
||||
const error = '[size_wrong] Attachment size ' + attachment.length
|
||||
+ ' not match download size ' + tarballBuffer.length;
|
||||
this.body = {
|
||||
error: 'size_wrong',
|
||||
reason: 'Attachment size ' + attachment.length
|
||||
+ ' not match download size ' + tarballBuffer.length,
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (!distTags.latest) {
|
||||
// need to check if latest tag exists or not
|
||||
var latest = yield* packageService.getModuleByTag(name, 'latest');
|
||||
var latest = yield packageService.getModuleByTag(name, 'latest');
|
||||
if (!latest) {
|
||||
// auto add latest
|
||||
tags.push(['latest', tags[0][1]]);
|
||||
@@ -202,9 +197,9 @@ module.exports = function* save(next) {
|
||||
};
|
||||
|
||||
mod.package.dist = dist;
|
||||
yield* addDepsRelations(mod.package);
|
||||
yield addDepsRelations(mod.package);
|
||||
|
||||
var addResult = yield* packageService.saveModule(mod);
|
||||
var addResult = yield packageService.saveModule(mod);
|
||||
debug('%s module: save file to %s, size: %d, sha1: %s, dist: %j, version: %s',
|
||||
addResult.id, dist.tarball, dist.size, shasum, dist, version);
|
||||
|
||||
@@ -219,13 +214,25 @@ module.exports = function* save(next) {
|
||||
var maintainerNames = maintainers.map(function (item) {
|
||||
return item.name;
|
||||
});
|
||||
yield* packageService.addPrivateModuleMaintainers(name, maintainerNames);
|
||||
yield packageService.addPrivateModuleMaintainers(name, maintainerNames);
|
||||
|
||||
this.status = 201;
|
||||
this.body = {
|
||||
ok: true,
|
||||
rev: String(addResult.id)
|
||||
};
|
||||
|
||||
// hooks
|
||||
const envelope = {
|
||||
event: 'package:publish',
|
||||
name: mod.name,
|
||||
type: 'package',
|
||||
version: mod.version,
|
||||
hookOwner: null,
|
||||
payload: null,
|
||||
change: null,
|
||||
};
|
||||
hook.trigger(envelope);
|
||||
};
|
||||
|
||||
function* addDepsRelations(pkg) {
|
||||
|
||||
@@ -53,15 +53,22 @@ module.exports = function* show() {
|
||||
// show tags for npminstall faster download
|
||||
mod.package['dist-tags'] = distTags;
|
||||
this.jsonp = mod.package;
|
||||
if (config.registryCacheControlHeader) {
|
||||
this.set('cache-control', config.registryCacheControlHeader);
|
||||
}
|
||||
if (config.registryVaryHeader) {
|
||||
this.set('vary', config.registryVaryHeader);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// if not fond, sync from source registry
|
||||
if (!this.allowSync) {
|
||||
this.status = 404;
|
||||
const error = '[not_exists] version not found: ' + version;
|
||||
this.jsonp = {
|
||||
error: 'not exist',
|
||||
reason: 'version not found: ' + version
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/tag.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:tag');
|
||||
var semver = require('semver');
|
||||
var util = require('util');
|
||||
@@ -30,40 +16,41 @@ module.exports = function* tag() {
|
||||
|
||||
if (!version) {
|
||||
this.status = 400;
|
||||
const error = '[version_missed] version not found';
|
||||
this.body = {
|
||||
error: 'version_missed',
|
||||
reason: 'version not found'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (!semver.valid(version)) {
|
||||
this.status = 403;
|
||||
var reason = util.format('setting tag %s to invalid version: %s: %s/%s',
|
||||
const error = util.format('[forbidden] setting tag %s to invalid version: %s: %s/%s',
|
||||
tag, version, name, tag);
|
||||
this.body = {
|
||||
error: 'forbidden',
|
||||
reason: reason
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var mod = yield* packageService.getModule(name, version);
|
||||
var mod = yield packageService.getModule(name, version);
|
||||
if (!mod) {
|
||||
this.status = 403;
|
||||
var reason = util.format('setting tag %s to unknown version: %s: %s/%s',
|
||||
const error = util.format('[forbidden] setting tag %s to unknown version: %s: %s/%s',
|
||||
tag, version, name, tag);
|
||||
this.body = {
|
||||
error: 'forbidden',
|
||||
reason: reason
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var row = yield* packageService.addModuleTag(name, tag, version);
|
||||
var row = yield packageService.addModuleTag(name, tag, version);
|
||||
this.status = 201;
|
||||
this.body = {
|
||||
ok: true,
|
||||
modified: row.gmt_modified
|
||||
modified: row.gmt_modified,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/package/update.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:package:update');
|
||||
var packageService = require('../../../services/package');
|
||||
var userService = require('../../../services/user');
|
||||
@@ -29,11 +15,11 @@ module.exports = function* update(next) {
|
||||
|
||||
var body = this.request.body;
|
||||
if (body.versions) {
|
||||
yield* updateVersions.call(this, next);
|
||||
yield updateVersions.call(this, next);
|
||||
} else if (body.maintainers) {
|
||||
yield* updateMaintainers.call(this, next);
|
||||
yield updateMaintainers.call(this, next);
|
||||
} else {
|
||||
yield* next;
|
||||
yield next;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -45,11 +31,11 @@ function* updateVersions(next) {
|
||||
var versions = this.request.body.versions;
|
||||
|
||||
// step1: list all the versions
|
||||
var mods = yield* packageService.listModulesByName(name);
|
||||
var mods = yield packageService.listModulesByName(name);
|
||||
debug('removeWithVersions module %s, left versions %j, %s mods',
|
||||
name, Object.keys(versions), mods && mods.length);
|
||||
if (!mods || !mods.length) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
// step3: calculate which versions need to remove and
|
||||
@@ -78,7 +64,7 @@ function* updateVersions(next) {
|
||||
|
||||
// step 4: remove all the versions which need to remove
|
||||
// let removeTar do remove versions from module table
|
||||
var tags = yield* packageService.listModuleTags(name);
|
||||
var tags = yield packageService.listModuleTags(name);
|
||||
|
||||
var removeTags = [];
|
||||
var latestRemoved = false;
|
||||
@@ -95,17 +81,17 @@ function* updateVersions(next) {
|
||||
debug('remove tags: %j', removeTags);
|
||||
if (removeTags.length) {
|
||||
// step 5: remove all the tags
|
||||
yield* packageService.removeModuleTagsByIds(removeTags);
|
||||
yield packageService.removeModuleTagsByIds(removeTags);
|
||||
if (latestRemoved && remainVersions[0]) {
|
||||
debug('latest tags removed, generate a new latest tag with new version: %s',
|
||||
remainVersions[0]);
|
||||
// step 6: insert new latest tag
|
||||
yield* packageService.addModuleTag(name, 'latest', remainVersions[0]);
|
||||
yield packageService.addModuleTag(name, 'latest', remainVersions[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// step 7: update last modified, make sure etag change
|
||||
yield* packageService.updateModuleLastModified(name);
|
||||
yield packageService.updateModuleLastModified(name);
|
||||
|
||||
this.status = 201;
|
||||
this.body = { ok: true };
|
||||
@@ -122,16 +108,17 @@ function* updateMaintainers() {
|
||||
|
||||
if (usernames.length === 0) {
|
||||
this.status = 403;
|
||||
const error = '[invalid_operation] Can not remove all maintainers';
|
||||
this.body = {
|
||||
error: 'invalid operation',
|
||||
reason: 'Can not remove all maintainers'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.customUserService) {
|
||||
// ensure new authors are vaild
|
||||
var maintainers = yield* packageService.listMaintainerNamesOnly(name);
|
||||
var maintainers = yield packageService.listMaintainerNamesOnly(name);
|
||||
var map = {};
|
||||
var newNames = [];
|
||||
for (var i = 0; i < maintainers.length; i++) {
|
||||
@@ -144,7 +131,7 @@ function* updateMaintainers() {
|
||||
}
|
||||
}
|
||||
if (newNames.length > 0) {
|
||||
var users = yield* userService.list(newNames);
|
||||
var users = yield userService.list(newNames);
|
||||
var map = {};
|
||||
for (var i = 0; i < users.length; i++) {
|
||||
var user = users[i];
|
||||
@@ -159,16 +146,17 @@ function* updateMaintainers() {
|
||||
}
|
||||
if (invailds.length > 0) {
|
||||
this.status = 403;
|
||||
const error = '[invalid] User: `' + invailds.join(', ') + '` not exists';
|
||||
this.body = {
|
||||
error: 'invalid user name',
|
||||
reason: 'User: `' + invailds.join(', ') + '` not exists'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var r = yield* packageService.updatePrivateModuleMaintainers(name, usernames);
|
||||
var r = yield packageService.updatePrivateModuleMaintainers(name, usernames);
|
||||
debug('result: %j', r);
|
||||
|
||||
this.status = 201;
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/user/add.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var ensurePasswordSalt = require('./common').ensurePasswordSalt;
|
||||
var userService = require('../../../services/user');
|
||||
var config = require('../../../config');
|
||||
@@ -55,34 +40,25 @@ var config = require('../../../config');
|
||||
module.exports = function* addUser() {
|
||||
var name = this.params.name;
|
||||
var body = this.request.body || {};
|
||||
var user = {
|
||||
name: body.name,
|
||||
// salt: body.salt,
|
||||
// password_sha: body.password_sha,
|
||||
email: body.email,
|
||||
ip: this.ip || '0.0.0.0',
|
||||
// roles: body.roles || [],
|
||||
};
|
||||
|
||||
ensurePasswordSalt(user, body);
|
||||
|
||||
if (!body.password || !user.name || !user.salt || !user.password_sha || !user.email) {
|
||||
if (!body.password || !body.name) {
|
||||
this.status = 422;
|
||||
const error = '[param_error] params missing, name, email or password missing';
|
||||
this.body = {
|
||||
error: 'paramError',
|
||||
reason: 'params missing, name, email or password missing.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var loginedUser;
|
||||
try {
|
||||
loginedUser = yield* userService.authAndSave(body.name, body.password);
|
||||
loginedUser = yield userService.authAndSave(body.name, body.password);
|
||||
} catch (err) {
|
||||
this.status = err.status || 500;
|
||||
this.body = {
|
||||
error: err.name,
|
||||
reason: err.message
|
||||
error: err.message,
|
||||
reason: err.message,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -99,25 +75,48 @@ module.exports = function* addUser() {
|
||||
if (config.customUserService) {
|
||||
// user login fail, not allow to add new user
|
||||
this.status = 401;
|
||||
const error = '[unauthorized] Login fail, please check your login name and password';
|
||||
this.body = {
|
||||
error: 'unauthorized',
|
||||
reason: 'Login fail, please check your login name and password'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var existUser = yield* userService.get(name);
|
||||
var user = {
|
||||
name: body.name,
|
||||
// salt: body.salt,
|
||||
// password_sha: body.password_sha,
|
||||
email: body.email,
|
||||
ip: this.ip || '0.0.0.0',
|
||||
// roles: body.roles || [],
|
||||
};
|
||||
|
||||
ensurePasswordSalt(user, body);
|
||||
|
||||
if (!user.salt || !user.password_sha || !user.email) {
|
||||
this.status = 422;
|
||||
const error = '[param_error] params missing, name, email or password missing';
|
||||
this.body = {
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var existUser = yield userService.get(name);
|
||||
if (existUser) {
|
||||
this.status = 409;
|
||||
const error = '[conflict] User ' + name + ' already exists';
|
||||
this.body = {
|
||||
error: 'conflict',
|
||||
reason: 'User ' + name + ' already exists.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// add new user
|
||||
var result = yield* userService.add(user);
|
||||
var result = yield userService.add(user);
|
||||
this.etag = '"' + result.rev + '"';
|
||||
this.status = 201;
|
||||
this.body = {
|
||||
|
||||
@@ -1,28 +1,13 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/user/show.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var userService = require('../../../services/user');
|
||||
|
||||
// GET /-/user/org.couchdb.user::name
|
||||
module.exports = function* show(next) {
|
||||
var name = this.params.name;
|
||||
var user = yield* userService.getAndSave(name);
|
||||
var user = yield userService.getAndSave(name);
|
||||
if (!user) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var data = user.json;
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/registry/user/update.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:registry:user:update');
|
||||
var ensurePasswordSalt = require('./common').ensurePasswordSalt;
|
||||
var userService = require('../../../services/user');
|
||||
@@ -40,16 +25,17 @@ module.exports = function* updateUser(next) {
|
||||
var name = this.params.name;
|
||||
var rev = this.params.rev;
|
||||
if (!name || !rev) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
debug('update: %s, rev: %s, user.name: %s', name, rev, this.user.name);
|
||||
|
||||
if (name !== this.user.name) {
|
||||
// must auth user first
|
||||
this.status = 401;
|
||||
const error = '[unauthorized] Name is incorrect';
|
||||
this.body = {
|
||||
error: 'unauthorized',
|
||||
reason: 'Name is incorrect.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -71,19 +57,21 @@ module.exports = function* updateUser(next) {
|
||||
|
||||
if (!body.password || !user.name || !user.salt || !user.password_sha || !user.email) {
|
||||
this.status = 422;
|
||||
const error = '[param_error] params missing, name, email or password missing';
|
||||
this.body = {
|
||||
error: 'paramError',
|
||||
reason: 'params missing, name, email or password missing.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
var result = yield* userService.update(user);
|
||||
var result = yield userService.update(user);
|
||||
if (!result) {
|
||||
this.status = 409;
|
||||
const error = '[conflict] Document update conflict';
|
||||
this.body = {
|
||||
error: 'conflict',
|
||||
reason: 'Document update conflict.'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -21,9 +21,10 @@ exports.list = function* () {
|
||||
var users = this.params.user.split('|');
|
||||
if (users.length > 20) {
|
||||
this.status = 400;
|
||||
const error = '[bad_request] reach max user names limit, must <= 20 user names';
|
||||
this.body = {
|
||||
error: 'bad_request',
|
||||
reason: 'reach max user names limit, must <= 20 user names'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/sync.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:sync');
|
||||
var Log = require('../services/module_log');
|
||||
var SyncModuleWorker = require('./sync_module_worker');
|
||||
@@ -32,12 +18,17 @@ exports.sync = function* () {
|
||||
}
|
||||
var publish = this.query.publish === 'true';
|
||||
var noDep = this.query.nodeps === 'true';
|
||||
debug('sync %s with query: %j', name, this.query);
|
||||
var syncUpstreamFirst = this.query.sync_upstream === 'true';
|
||||
if (!config.sourceNpmRegistryIsCNpm) {
|
||||
syncUpstreamFirst = false;
|
||||
}
|
||||
debug('sync %s with query: %j, syncUpstreamFirst: %s', name, this.query, syncUpstreamFirst);
|
||||
if (type === 'package' && publish && !this.user.isAdmin) {
|
||||
this.status = 403;
|
||||
const error = '[no_perms] Only admin can publish';
|
||||
this.body = {
|
||||
error: 'no_perms',
|
||||
reason: 'Only admin can publish'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -46,10 +37,10 @@ exports.sync = function* () {
|
||||
type: type,
|
||||
publish: publish,
|
||||
noDep: noDep,
|
||||
syncUpstreamFirst: config.sourceNpmRegistryIsCNpm,
|
||||
syncUpstreamFirst: syncUpstreamFirst,
|
||||
};
|
||||
|
||||
var logId = yield* SyncModuleWorker.sync(name, username, options);
|
||||
var logId = yield SyncModuleWorker.sync(name, username, options);
|
||||
debug('sync %s got log id %j', name, logId);
|
||||
|
||||
this.status = 201;
|
||||
@@ -67,14 +58,20 @@ exports.getSyncLog = function* (next) {
|
||||
this.status = 404;
|
||||
return;
|
||||
}
|
||||
var row = yield* Log.get(logId);
|
||||
var row = yield Log.get(logId);
|
||||
if (!row) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var log = row.log.trim();
|
||||
var syncDone = row.log.indexOf('[done] Sync') >= 0;
|
||||
if (offset > 0) {
|
||||
log = log.split('\n').slice(offset).join('\n');
|
||||
if (!log && syncDone) {
|
||||
// append the last 1k string
|
||||
// the cnpm client sync need the `[done] Sync {name}` string to detect when sync task finished
|
||||
log = '... ignore long logs ...\n' + row.log.substring(row.log.length - 1024);
|
||||
}
|
||||
}
|
||||
this.body = {ok: true, log: log};
|
||||
this.body = { ok: true, syncDone: syncDone, log: log };
|
||||
};
|
||||
|
||||
@@ -21,8 +21,11 @@ var common = require('../lib/common');
|
||||
var npmSerivce = require('../services/npm');
|
||||
var packageService = require('../services/package');
|
||||
var logService = require('../services/module_log');
|
||||
var downloadTotalService = require('../services/download_total');
|
||||
var hook = require('../services/hook');
|
||||
var User = require('../models').User;
|
||||
var os = require('os');
|
||||
const cache = require('../common/cache');
|
||||
|
||||
var USER_AGENT = 'sync.cnpmjs.org/' + config.version +
|
||||
' hostname/' + os.hostname() +
|
||||
@@ -36,6 +39,7 @@ function SyncModuleWorker(options) {
|
||||
this._logId = options.logId;
|
||||
this._log = '';
|
||||
this._loging = false;
|
||||
this._isEnd = false;
|
||||
if (!Array.isArray(options.name)) {
|
||||
options.name = [options.name];
|
||||
}
|
||||
@@ -77,11 +81,14 @@ SyncModuleWorker.prototype.finish = function () {
|
||||
this.type,
|
||||
this.successes.length, this.fails.length,
|
||||
this.successes.join(', '), this.fails.join(', '));
|
||||
this._saveLog();
|
||||
this._isEnd = true;
|
||||
this.emit('end');
|
||||
// make sure all event listeners release
|
||||
this.removeAllListeners();
|
||||
};
|
||||
|
||||
var MAX_LEN = 10 * 1024;
|
||||
// log(format, arg1, arg2, ...)
|
||||
SyncModuleWorker.prototype.log = function () {
|
||||
var str = '[' + utility.YYYYMMDDHHmmss() + '] ' + util.format.apply(util, arguments);
|
||||
@@ -92,7 +99,9 @@ SyncModuleWorker.prototype.log = function () {
|
||||
this._log += '\n';
|
||||
}
|
||||
this._log += str;
|
||||
this._saveLog();
|
||||
if (this._log.length >= MAX_LEN) {
|
||||
this._saveLog();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -104,31 +113,39 @@ SyncModuleWorker.prototype._saveLog = function () {
|
||||
that._loging = true;
|
||||
var logstr = that._log;
|
||||
that._log = '';
|
||||
|
||||
if (!logstr) {
|
||||
that._loging = false;
|
||||
return;
|
||||
}
|
||||
|
||||
co(function* () {
|
||||
yield* logService.append(that._logId, logstr);
|
||||
yield logService.append(that._logId, logstr);
|
||||
}).then(function () {
|
||||
that._loging = false;
|
||||
if (that._log) {
|
||||
that._saveLog();
|
||||
}
|
||||
}).catch(function (err) {
|
||||
logger.error(err);
|
||||
that._loging = false;
|
||||
if (that._log) {
|
||||
that._saveLog();
|
||||
logger.error(err);
|
||||
// ignore the unsave log
|
||||
if (this._isEnd) {
|
||||
logger.error('[SyncModuleWorker] skip to save %s logstr: %s', that._logId, logstr);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
SyncModuleWorker.prototype.start = function () {
|
||||
this.log('user: %s, sync %s worker start, %d concurrency, nodeps: %s, publish: %s',
|
||||
this.username, this.names[0], this.concurrency, this.noDep, this._publish);
|
||||
var that = this;
|
||||
that.log('user: %s, sync %s worker start, %d concurrency, nodeps: %s, publish: %s, syncUpstreamFirst: %s',
|
||||
that.username, that.names[0], that.concurrency, that.noDep, that._publish, that.syncUpstreamFirst);
|
||||
co(function* () {
|
||||
// sync upstream
|
||||
if (that.syncUpstreamFirst) {
|
||||
try {
|
||||
yield that.syncUpstream(that.startName);
|
||||
that._saveLog();
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
}
|
||||
@@ -136,6 +153,8 @@ SyncModuleWorker.prototype.start = function () {
|
||||
|
||||
if (that.type === 'user') {
|
||||
yield that.syncUser();
|
||||
that._saveLog();
|
||||
that._isEnd = true;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -144,8 +163,10 @@ SyncModuleWorker.prototype.start = function () {
|
||||
arr.push(that.next(i));
|
||||
}
|
||||
yield arr;
|
||||
that._saveLog();
|
||||
}).catch(function (err) {
|
||||
logger.error(err);
|
||||
that._saveLog();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -170,6 +191,14 @@ SyncModuleWorker.prototype.add = function (name) {
|
||||
};
|
||||
|
||||
SyncModuleWorker.prototype._doneOne = function* (concurrencyId, name, success) {
|
||||
// clean cache
|
||||
if (cache) {
|
||||
const cacheKey = `list-${name}-v1`;
|
||||
cache.del(cacheKey).catch(err => {
|
||||
logger.error(err);
|
||||
});
|
||||
}
|
||||
|
||||
this.log('----------------- Synced %s %s -------------------',
|
||||
name, success ? 'success' : 'fail');
|
||||
if (success) {
|
||||
@@ -197,9 +226,9 @@ SyncModuleWorker.prototype.syncUpstream = function* (name) {
|
||||
if (this.type === 'user') {
|
||||
syncname = this.type + ':' + syncname;
|
||||
}
|
||||
var url = config.sourceNpmRegistry + '/' + syncname + '/sync';
|
||||
var url = config.sourceNpmRegistry + '/' + syncname + '/sync?sync_upstream=true';
|
||||
if (this.noDep) {
|
||||
url += '?nodeps=true';
|
||||
url += '&nodeps=true';
|
||||
}
|
||||
var r = yield urllib.request(url, {
|
||||
method: 'put',
|
||||
@@ -237,17 +266,12 @@ SyncModuleWorker.prototype.syncUpstream = function* (name) {
|
||||
}
|
||||
|
||||
var data = rs.data;
|
||||
var syncDone = false;
|
||||
if (data.log && data.log.indexOf('[done] Sync') >= 0) {
|
||||
syncDone = true;
|
||||
data.log = data.log.replace('[done] Sync', '[Upstream done] Sync');
|
||||
}
|
||||
|
||||
if (data.log) {
|
||||
data.log = data.log.replace('[done] Sync', '[Upstream done] Sync');
|
||||
this.log(data.log);
|
||||
}
|
||||
|
||||
if (syncDone) {
|
||||
if (data.syncDone) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -281,17 +305,24 @@ SyncModuleWorker.prototype.syncUser = function* () {
|
||||
};
|
||||
|
||||
SyncModuleWorker.prototype.next = function* (concurrencyId) {
|
||||
var name = this.names.shift();
|
||||
if (!name) {
|
||||
return setImmediate(this.finish.bind(this));
|
||||
}
|
||||
|
||||
if (config.syncModel === 'none') {
|
||||
this.log('[c#%d] [%s] syncModel is none, ignore',
|
||||
concurrencyId, name);
|
||||
return this.finish();
|
||||
}
|
||||
|
||||
var name = this.names.shift();
|
||||
if (!name) {
|
||||
return setImmediate(this.finish.bind(this));
|
||||
}
|
||||
// try to sync from official replicate when source npm registry is not cnpmjs.org
|
||||
const registry = config.sourceNpmRegistryIsCNpm ? config.sourceNpmRegistry : config.officialNpmReplicate;
|
||||
|
||||
yield this.syncByName(concurrencyId, name, registry);
|
||||
};
|
||||
|
||||
SyncModuleWorker.prototype.syncByName = function* (concurrencyId, name, registry) {
|
||||
var that = this;
|
||||
that.syncingNames[name] = true;
|
||||
var pkg = null;
|
||||
@@ -307,22 +338,90 @@ SyncModuleWorker.prototype.next = function* (concurrencyId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// get from npm
|
||||
const packageUrl = '/' + name.replace('/', '%2f');
|
||||
// try to sync from official replicate when source npm registry is not cnpmjs.org
|
||||
const registry = config.sourceNpmRegistryIsCNpm ? config.sourceNpmRegistry : config.officialNpmReplicate;
|
||||
let realRegistry = registry;
|
||||
// get from npm, don't cache
|
||||
const packageUrl = '/' + name.replace('/', '%2f') + '?sync_timestamp=' + Date.now();
|
||||
try {
|
||||
var result = yield npmSerivce.request(packageUrl, { registry: registry });
|
||||
pkg = result.data;
|
||||
status = result.status;
|
||||
// read from officialNpmRegistry and use the latest modified package info
|
||||
if (registry === config.officialNpmReplicate) {
|
||||
try {
|
||||
const officialResult = yield npmSerivce.request(packageUrl, { registry: config.officialNpmRegistry });
|
||||
const officialPkg = officialResult.data;
|
||||
const officialStatus = officialResult.status;
|
||||
this.log('[c#%d] [%s] official registry(%j, %j), replicate(%j, %j), packageUrl: %s',
|
||||
concurrencyId, name,
|
||||
officialPkg['dist-tags'], officialPkg.time && officialPkg.time.modified,
|
||||
pkg['dist-tags'], pkg.time && pkg.time.modified, packageUrl);
|
||||
if (officialPkg.time) {
|
||||
if (!pkg.time || officialPkg.time.modified > pkg.time.modified) {
|
||||
this.log('[c#%d] [%s] use official registry\'s data instead of replicate, modified: %j < %j',
|
||||
concurrencyId, name, pkg.time && pkg.time.modified, officialPkg.time.modified);
|
||||
pkg = officialPkg;
|
||||
status = officialStatus;
|
||||
realRegistry = config.officialNpmRegistry;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
that.log('[c#%s] [error] [%s] get package(%s%s) error: %s',
|
||||
concurrencyId, name, config.officialNpmReplicate, packageUrl, err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// if 404
|
||||
if (!err.res || err.res.statusCode !== 404) {
|
||||
var errMessage = err.name + ': ' + err.message;
|
||||
that.log('[c#%s] [error] [%s] get package(%s%s) error: %s, status: %s',
|
||||
concurrencyId, name, registry, packageUrl, errMessage, status);
|
||||
yield that._doneOne(concurrencyId, name, false);
|
||||
return;
|
||||
// replicate request error, try to request from official registry
|
||||
if (registry !== config.officialNpmReplicate) {
|
||||
// sync fail
|
||||
yield that._doneOne(concurrencyId, name, false);
|
||||
return;
|
||||
}
|
||||
|
||||
// retry from officialNpmRegistry when officialNpmReplicate fail
|
||||
this.log('[c#%d] [%s] retry from %s', concurrencyId, name, config.officialNpmRegistry);
|
||||
try {
|
||||
var result = yield npmSerivce.request(packageUrl, { registry: config.officialNpmRegistry });
|
||||
pkg = result.data;
|
||||
status = result.status;
|
||||
realRegistry = config.officialNpmRegistry;
|
||||
} catch (err) {
|
||||
var errMessage = err.name + ': ' + err.message;
|
||||
that.log('[c#%s] [error] [%s] get package(%s%s) error: %s, status: %s',
|
||||
concurrencyId, name, config.officialNpmRegistry, packageUrl, errMessage, status);
|
||||
// sync fail
|
||||
yield that._doneOne(concurrencyId, name, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (status === 404 && pkg && pkg.reason && registry === config.officialNpmReplicate) {
|
||||
// unpublished package on replicate.npmjs.com
|
||||
// 404 { error: 'not_found', reason: 'deleted' }
|
||||
// try to read from registry.npmjs.com and get the whole unpublished info
|
||||
|
||||
// https://replicate.npmjs.com/registry-url
|
||||
// {"error":"not_found","reason":"no_db_file"}
|
||||
// try to read from registry.npmjs.com and get no_db_file
|
||||
try {
|
||||
var result = yield npmSerivce.request(packageUrl, { registry: config.sourceNpmRegistry });
|
||||
pkg = result.data;
|
||||
status = result.status;
|
||||
realRegistry = config.sourceNpmRegistry;
|
||||
} catch (err) {
|
||||
// if 404
|
||||
if (!err.res || err.res.statusCode !== 404) {
|
||||
var errMessage = err.name + ': ' + err.message;
|
||||
that.log('[c#%s] [error] [%s] get package(%s%s) error: %s, status: %s',
|
||||
concurrencyId, name, config.sourceNpmRegistry, packageUrl, errMessage, status);
|
||||
yield that._doneOne(concurrencyId, name, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,17 +434,25 @@ SyncModuleWorker.prototype.next = function* (concurrencyId) {
|
||||
} else {
|
||||
pkg = null;
|
||||
}
|
||||
} else {
|
||||
// unpublished package status become to 200
|
||||
if (name.length < 80 && pkg && pkg.time && pkg.time.unpublished && pkg.time.unpublished.time) {
|
||||
unpublishedInfo = pkg.time.unpublished;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pkg) {
|
||||
that.log('[c#%s] [error] [%s] get package(%s%s) error: package not exists, status: %s',
|
||||
concurrencyId, name, registry, packageUrl, status);
|
||||
concurrencyId, name, realRegistry, packageUrl, status);
|
||||
yield that._doneOne(concurrencyId, name, true);
|
||||
return;
|
||||
// return empty versions, try again on officialNpmRegistry
|
||||
return [];
|
||||
}
|
||||
|
||||
that.log('[c#%d] [%s] package(%s%s) status: %s, dist-tags: %j, time.modified: %s, start...',
|
||||
concurrencyId, name, registry, packageUrl, status, pkg['dist-tags'], pkg.time && pkg.time.modified);
|
||||
that.log('[c#%d] [%s] package(%s%s) status: %s, dist-tags: %j, time.modified: %s, unpublished: %j, start...',
|
||||
concurrencyId, name, realRegistry, packageUrl, status,
|
||||
pkg['dist-tags'], pkg.time && pkg.time.modified,
|
||||
unpublishedInfo);
|
||||
|
||||
if (unpublishedInfo) {
|
||||
try {
|
||||
@@ -375,6 +482,8 @@ SyncModuleWorker.prototype.next = function* (concurrencyId) {
|
||||
this.log('[c#%d] [%s] synced success, %d versions: %s',
|
||||
concurrencyId, name, versions.length, versions.join(', '));
|
||||
yield this._doneOne(concurrencyId, name, true);
|
||||
|
||||
return versions;
|
||||
};
|
||||
|
||||
function* _listStarUsers(modName) {
|
||||
@@ -407,14 +516,14 @@ function* _saveNpmUser(username) {
|
||||
|
||||
function* _saveMaintainer(modName, username, action) {
|
||||
if (action === 'add') {
|
||||
yield* packageService.addPublicModuleMaintainer(modName, username);
|
||||
yield packageService.addPublicModuleMaintainer(modName, username);
|
||||
} else if (action === 'remove') {
|
||||
yield* packageService.removePublicModuleMaintainer(modName, username);
|
||||
yield packageService.removePublicModuleMaintainer(modName, username);
|
||||
}
|
||||
}
|
||||
|
||||
SyncModuleWorker.prototype._unpublished = function* (name, unpublishedInfo) {
|
||||
var mods = yield* packageService.listModulesByName(name);
|
||||
var mods = yield packageService.listModulesByName(name);
|
||||
this.log(' [%s] start unpublished %d versions from local cnpm registry',
|
||||
name, mods.length);
|
||||
if (common.isLocalModule(mods)) {
|
||||
@@ -422,14 +531,25 @@ SyncModuleWorker.prototype._unpublished = function* (name, unpublishedInfo) {
|
||||
this.log(' [%s] publish on local cnpm registry, don\'t sync', name);
|
||||
return [];
|
||||
}
|
||||
if (!config.syncDeletedVersions) {
|
||||
const downloadCount = yield downloadTotalService.getTotalByName(name);
|
||||
if (downloadCount >= 10000) {
|
||||
this.log(' [%s] total downloads %s >= 10000 and `config.syncDeletedVersions=false`, don\'t sync unpublished info', name, downloadCount);
|
||||
return [];
|
||||
}
|
||||
this.log(' [%s] total downloads %s < 10000 and `config.syncDeletedVersions=false`, still need to sync unpublished info', name, downloadCount);
|
||||
}
|
||||
|
||||
var r = yield* packageService.saveUnpublishedModule(name, unpublishedInfo);
|
||||
var r = yield packageService.saveUnpublishedModule(name, unpublishedInfo);
|
||||
this.log(' [%s] save unpublished info: %j to row#%s',
|
||||
name, unpublishedInfo, r.id);
|
||||
if (mods.length === 0) {
|
||||
return;
|
||||
}
|
||||
yield [packageService.removeModulesByName(name), packageService.removeModuleTags(name)];
|
||||
yield [
|
||||
packageService.removeModulesByName(name),
|
||||
packageService.removeModuleTags(name),
|
||||
];
|
||||
var keys = [];
|
||||
for (var i = 0; i < mods.length; i++) {
|
||||
var row = mods[i];
|
||||
@@ -463,11 +583,13 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
packageService.listModuleTags(name),
|
||||
_listStarUsers(name),
|
||||
packageService.listPublicModuleMaintainers(name),
|
||||
packageService.listModuleAbbreviatedsByName(name),
|
||||
];
|
||||
var moduleRows = result[0];
|
||||
var tagRows = result[1];
|
||||
var existsStarUsers = result[2];
|
||||
var existsNpmMaintainers = result[3];
|
||||
var existsModuleAbbreviateds = result[4];
|
||||
|
||||
if (common.isLocalModule(moduleRows)) {
|
||||
// publish on cnpm, dont sync this version package
|
||||
@@ -475,7 +597,14 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var missingModuleAbbreviateds = [];
|
||||
var existsModuleAbbreviatedsMap = {};
|
||||
for (var item of existsModuleAbbreviateds) {
|
||||
existsModuleAbbreviatedsMap[item.version] = item;
|
||||
}
|
||||
|
||||
hasModules = moduleRows.length > 0;
|
||||
// localPackage
|
||||
var map = {};
|
||||
var localVersionNames = [];
|
||||
for (var i = 0; i < moduleRows.length; i++) {
|
||||
@@ -491,6 +620,11 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
localVersionNames.push(r.version);
|
||||
}
|
||||
|
||||
var latestVersionPackageReadme = {
|
||||
version: pkg['dist-tags'].latest,
|
||||
readme: pkg.readme,
|
||||
};
|
||||
|
||||
var tags = {};
|
||||
for (var i = 0; i < tagRows.length; i++) {
|
||||
var r = tagRows[i];
|
||||
@@ -501,6 +635,40 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
tags[r.tag] = r.version;
|
||||
}
|
||||
|
||||
// get package AbbreviatedMetadata
|
||||
var remoteAbbreviatedMetadatas = {};
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
// use ?cache=0 tell registry dont use cache result
|
||||
var packageUrl = '/' + name.replace('/', '%2f') + '?cache=0&sync_timestamp=' + Date.now();
|
||||
var result = yield npmSerivce.request(packageUrl, {
|
||||
dataType: 'text',
|
||||
registry: config.sourceNpmRegistry,
|
||||
headers: {
|
||||
Accept: 'application/vnd.npm.install-v1+json',
|
||||
},
|
||||
});
|
||||
if (result.status === 200) {
|
||||
var data;
|
||||
try {
|
||||
data = JSON.parse(result.data);
|
||||
} catch (err) {
|
||||
that.log(' [%s] get abbreviated meta error: %s, headers: %j, %j',
|
||||
name, err, result.headers, result.data);
|
||||
}
|
||||
if (data) {
|
||||
var versions = data && data.versions || {};
|
||||
for (var version in versions) {
|
||||
const item = versions[version];
|
||||
if (item && typeof item._hasShrinkwrap === 'boolean') {
|
||||
remoteAbbreviatedMetadatas[version] = { _hasShrinkwrap: item._hasShrinkwrap };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// any properties changed versions
|
||||
var changedVersions = {};
|
||||
var missingVersions = [];
|
||||
var missingTags = [];
|
||||
var missingDescriptions = [];
|
||||
@@ -511,6 +679,15 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
// [[user, 'add or remove'], ...]
|
||||
var diffNpmMaintainers = [];
|
||||
|
||||
// [
|
||||
// { name, version, _hasShrinkwrap }
|
||||
// ]
|
||||
var missingAbbreviatedMetadatas = [];
|
||||
// [
|
||||
// { name, version, deprecated },
|
||||
// ]
|
||||
var missingDeprecatedsOnExistsModuleAbbreviated = [];
|
||||
|
||||
// find out new maintainers
|
||||
var pkgMaintainers = pkg.maintainers || [];
|
||||
if (Array.isArray(pkgMaintainers)) {
|
||||
@@ -584,17 +761,47 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
if (!version || !version.dist || !version.dist.tarball) {
|
||||
continue;
|
||||
}
|
||||
//patch for readme
|
||||
if (!version.readme) {
|
||||
version.readme = pkg.readme;
|
||||
// remove readme
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
version.readme = undefined;
|
||||
} else {
|
||||
// patch for readme
|
||||
if (!version.readme) {
|
||||
version.readme = pkg.readme;
|
||||
}
|
||||
}
|
||||
|
||||
var publish_time = times[v];
|
||||
version.publish_time = publish_time ? Date.parse(publish_time) : null;
|
||||
if (!version.maintainers || !version.maintainers[0]) {
|
||||
version.maintainers = pkg.maintainers;
|
||||
}
|
||||
if (exists.package &&
|
||||
exists.package.dist.shasum === version.dist.shasum) {
|
||||
|
||||
var abbreviatedMetadata = remoteAbbreviatedMetadatas[version.version];
|
||||
|
||||
if (exists.package && exists.package.dist.shasum === version.dist.shasum) {
|
||||
var existsModuleAbbreviated = existsModuleAbbreviatedsMap[exists.package.version];
|
||||
if (!existsModuleAbbreviated) {
|
||||
missingModuleAbbreviateds.push(exists);
|
||||
} else {
|
||||
// sync missing deprecated on existsModuleAbbreviated
|
||||
if (exists.package.deprecated && exists.package.deprecated !== existsModuleAbbreviated.package.deprecated) {
|
||||
// add deprecated
|
||||
missingDeprecatedsOnExistsModuleAbbreviated.push({
|
||||
name,
|
||||
version: exists.package.version,
|
||||
deprecated: exists.package.deprecated,
|
||||
});
|
||||
} else if (existsModuleAbbreviated.package.deprecated && !exists.package.deprecated) {
|
||||
// remove deprecated
|
||||
missingDeprecatedsOnExistsModuleAbbreviated.push({
|
||||
name,
|
||||
version: exists.package.version,
|
||||
deprecated: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// * shasum make sure equal
|
||||
if ((version.publish_time === exists.publish_time) ||
|
||||
(!version.publish_time && exists.publish_time)) {
|
||||
@@ -607,22 +814,35 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
id: exists.id,
|
||||
description: version.description
|
||||
});
|
||||
changedVersions[v] = 1;
|
||||
}
|
||||
|
||||
if (!exists.package.readme && version.readme) {
|
||||
// * make sure readme exists
|
||||
missingReadmes.push({
|
||||
id: exists.id,
|
||||
readme: version.readme
|
||||
});
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
// remove readme
|
||||
if (exists.package.readme) {
|
||||
missingReadmes.push({
|
||||
id: exists.id,
|
||||
readme: undefined,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (!exists.package.readme && version.readme) {
|
||||
// * make sure readme exists
|
||||
missingReadmes.push({
|
||||
id: exists.id,
|
||||
readme: version.readme,
|
||||
});
|
||||
changedVersions[v] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (version.deprecated && version.deprecated !== exists.package.deprecated) {
|
||||
// need to sync deprecated field
|
||||
missingDeprecateds.push({
|
||||
id: exists.id,
|
||||
deprecated: version.deprecated
|
||||
deprecated: version.deprecated,
|
||||
});
|
||||
changedVersions[v] = 1;
|
||||
}
|
||||
if (exists.package.deprecated && !version.deprecated) {
|
||||
// remove deprecated info
|
||||
@@ -630,11 +850,32 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
id: exists.id,
|
||||
deprecated: undefined,
|
||||
});
|
||||
changedVersions[v] = 1;
|
||||
}
|
||||
// find missing abbreviatedMetadata
|
||||
if (abbreviatedMetadata) {
|
||||
for (var key in abbreviatedMetadata) {
|
||||
if (!(key in exists.package) || abbreviatedMetadata[key] !== exists.package[key]) {
|
||||
missingAbbreviatedMetadatas.push(Object.assign({
|
||||
id: exists.id,
|
||||
name: exists.package.name,
|
||||
version: exists.package.version,
|
||||
}, abbreviatedMetadata));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// set abbreviatedMetadata to version package
|
||||
if (abbreviatedMetadata) {
|
||||
Object.assign(version, abbreviatedMetadata);
|
||||
}
|
||||
missingVersions.push(version);
|
||||
changedVersions[v] = 1;
|
||||
}
|
||||
|
||||
// find out deleted versions
|
||||
@@ -645,6 +886,12 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
deletedVersionNames.push(v);
|
||||
}
|
||||
}
|
||||
// delete local abbreviatedMetadata data too
|
||||
for (var item of existsModuleAbbreviateds) {
|
||||
if (!remoteVersionNameMap[item.version] && deletedVersionNames.indexOf(item.version) === -1) {
|
||||
deletedVersionNames.push(item.version);
|
||||
}
|
||||
}
|
||||
|
||||
// find out missing tags
|
||||
var sourceTags = pkg['dist-tags'] || {};
|
||||
@@ -682,24 +929,76 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
if (!syncModule.dist.tarball) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
yield that._syncOneVersion(index, syncModule);
|
||||
syncedVersionNames.push(syncModule.version);
|
||||
} catch (err) {
|
||||
that.log(' [%s:%d] sync error, version: %s, %s: %s',
|
||||
syncModule.name, index, syncModule.version, err.name, err.stack);
|
||||
// retry 3 times
|
||||
var tries = 3;
|
||||
while (true) {
|
||||
try {
|
||||
yield that._syncOneVersion(index, syncModule);
|
||||
syncedVersionNames.push(syncModule.version);
|
||||
break;
|
||||
} catch (err) {
|
||||
var delay = Date.now() - syncModule.publish_time;
|
||||
that.log(' [%s:%d] tries: %d, delay: %s ms, sync error, version: %s, %s: %s',
|
||||
syncModule.name, index, tries, delay, syncModule.version, err.name, err.stack);
|
||||
var maxDelay = 3600000;
|
||||
if (tries-- > 0 && delay < maxDelay) {
|
||||
that.log(' [%s:%d] retry after 30s', syncModule.name, index);
|
||||
yield sleep(30000);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (deletedVersionNames.length === 0) {
|
||||
that.log(' [%s] no versions need to deleted', name);
|
||||
} else {
|
||||
that.log(' [%s] %d versions: %j need to deleted',
|
||||
name, deletedVersionNames.length, deletedVersionNames);
|
||||
try {
|
||||
yield packageService.removeModulesByNameAndVersions(name, deletedVersionNames);
|
||||
} catch (err) {
|
||||
that.log(' [%s] delete error, %s: %s', name, err.name, err.message);
|
||||
if (config.syncDeletedVersions) {
|
||||
that.log(' [%s] %d versions: %j need to deleted, because config.syncDeletedVersions=true',
|
||||
name, deletedVersionNames.length, deletedVersionNames);
|
||||
try {
|
||||
yield packageService.removeModulesByNameAndVersions(name, deletedVersionNames);
|
||||
} catch (err) {
|
||||
that.log(' [%s] delete error, %s: %s', name, err.name, err.message);
|
||||
}
|
||||
} else {
|
||||
const downloadCount = yield downloadTotalService.getTotalByName(name);
|
||||
if (downloadCount >= 10000) {
|
||||
// find deleted in 24 hours versions
|
||||
var oneDay = 3600000 * 24;
|
||||
var now = Date.now();
|
||||
var deletedIn24HoursVersions = [];
|
||||
var oldVersions = [];
|
||||
for (var i = 0; i < deletedVersionNames.length; i++) {
|
||||
var v = deletedVersionNames[i];
|
||||
var exists = map[v];
|
||||
if (exists && now - exists.publish_time < oneDay) {
|
||||
deletedIn24HoursVersions.push(v);
|
||||
} else {
|
||||
oldVersions.push(v);
|
||||
}
|
||||
}
|
||||
if (deletedIn24HoursVersions.length > 0) {
|
||||
that.log(' [%s] %d versions: %j need to deleted, because they are deleted in 24 hours',
|
||||
name, deletedIn24HoursVersions.length, deletedIn24HoursVersions);
|
||||
try {
|
||||
yield packageService.removeModulesByNameAndVersions(name, deletedIn24HoursVersions);
|
||||
} catch (err) {
|
||||
that.log(' [%s] delete error, %s: %s', name, err.name, err.message);
|
||||
}
|
||||
}
|
||||
that.log(' [%s] %d versions: %j no need to delete, because `config.syncDeletedVersions=false`',
|
||||
name, oldVersions.length, oldVersions);
|
||||
} else {
|
||||
that.log(' [%s] %d versions: %j need to deleted, because downloads %s < 10000',
|
||||
name, deletedVersionNames.length, deletedVersionNames, downloadCount);
|
||||
try {
|
||||
yield packageService.removeModulesByNameAndVersions(name, deletedVersionNames);
|
||||
} catch (err) {
|
||||
that.log(' [%s] delete error, %s: %s', name, err.name, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -729,7 +1028,7 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
// sync missing tags
|
||||
function* syncTag() {
|
||||
if (deletedTags.length > 0) {
|
||||
yield* packageService.removeModuleTagsByNames(name, deletedTags);
|
||||
yield packageService.removeModuleTagsByNames(name, deletedTags);
|
||||
that.log(' [%s] deleted %d tags: %j',
|
||||
name, deletedTags.length, deletedTags);
|
||||
}
|
||||
@@ -778,6 +1077,92 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
}
|
||||
}
|
||||
|
||||
function* syncModuleAbbreviateds() {
|
||||
if (missingModuleAbbreviateds.length === 0) {
|
||||
return;
|
||||
}
|
||||
that.log(' [%s] saving %d missing moduleAbbreviateds', name, missingModuleAbbreviateds.length);
|
||||
|
||||
var res = yield gather(missingModuleAbbreviateds.map(function (item) {
|
||||
return packageService.saveModuleAbbreviated(item);
|
||||
}));
|
||||
|
||||
for (var i = 0; i < res.length; i++) {
|
||||
var item = missingModuleAbbreviateds[i];
|
||||
var r = res[i];
|
||||
if (r.error) {
|
||||
that.log(' save moduleAbbreviateds error, module: %s@%s, error: %s', item.name, item.version, r.error.message);
|
||||
} else {
|
||||
that.log(' saved moduleAbbreviateds, module: %s@%s', item.name, item.version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function* syncAbbreviatedMetadatas() {
|
||||
if (missingAbbreviatedMetadatas.length === 0) {
|
||||
return;
|
||||
}
|
||||
that.log(' [%s] saving %d abbreviated meta datas', name, missingAbbreviatedMetadatas.length);
|
||||
|
||||
var res = yield gather(missingAbbreviatedMetadatas.map(function (item) {
|
||||
return packageService.updateModuleAbbreviatedPackage(item);
|
||||
}));
|
||||
|
||||
for (var i = 0; i < res.length; i++) {
|
||||
var item = missingAbbreviatedMetadatas[i];
|
||||
var r = res[i];
|
||||
if (r.error) {
|
||||
that.log(' save error, module_abbreviated: %s@%s, error: %s',
|
||||
item.name, item.version, r.error.stack);
|
||||
} else {
|
||||
that.log(' saved, module_abbreviated: %s@%s, %j', item.name, item.version, item);
|
||||
}
|
||||
}
|
||||
|
||||
var res = yield gather(missingAbbreviatedMetadatas.map(function (item) {
|
||||
var fields = {};
|
||||
for (var key in item) {
|
||||
if (key === 'id' || key === 'name' || key === 'version') {
|
||||
continue;
|
||||
}
|
||||
fields[key] = item[key];
|
||||
}
|
||||
return packageService.updateModulePackageFields(item.id, fields);
|
||||
}));
|
||||
|
||||
for (var i = 0; i < res.length; i++) {
|
||||
var item = missingAbbreviatedMetadatas[i];
|
||||
var r = res[i];
|
||||
if (r.error) {
|
||||
that.log(' save error, module id: %s, error: %s', item.id, r.error.stack);
|
||||
} else {
|
||||
that.log(' saved, module id: %s, %j', item.id, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function *syncDeprecatedsOnExistsModuleAbbreviated() {
|
||||
if (missingDeprecatedsOnExistsModuleAbbreviated.length === 0) {
|
||||
return;
|
||||
}
|
||||
that.log(' [%s] saving %d module abbreviated deprecated fields',
|
||||
name, missingDeprecatedsOnExistsModuleAbbreviated.length);
|
||||
|
||||
var res = yield gather(missingDeprecatedsOnExistsModuleAbbreviated.map(function (item) {
|
||||
return packageService.updateModuleAbbreviatedPackage(item);
|
||||
}));
|
||||
|
||||
for (var i = 0; i < res.length; i++) {
|
||||
var item = missingDeprecatedsOnExistsModuleAbbreviated[i];
|
||||
var r = res[i];
|
||||
if (r.error) {
|
||||
that.log(' save error, module abbreviated: %s@%s, error: %s', item.name, item.version, r.error.message);
|
||||
} else {
|
||||
that.log(' saved, module abbreviated: %s@%s, deprecated: %j', item.name, item.version, item.deprecated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function *syncDeprecateds() {
|
||||
if (missingDeprecateds.length === 0) {
|
||||
return;
|
||||
@@ -807,7 +1192,7 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
if (names.length === 0) {
|
||||
return;
|
||||
}
|
||||
var rows = yield* User.listByNames(names);
|
||||
var rows = yield User.listByNames(names);
|
||||
var map = {};
|
||||
rows.forEach(function (r) {
|
||||
map[r.name] = r;
|
||||
@@ -879,15 +1264,42 @@ SyncModuleWorker.prototype._sync = function* (name, pkg) {
|
||||
}
|
||||
}
|
||||
|
||||
yield [
|
||||
syncDes(),
|
||||
syncTag(),
|
||||
syncReadme(),
|
||||
syncDeprecateds(),
|
||||
syncMissingStarUsers(),
|
||||
syncMissingUsers(),
|
||||
syncNpmPackageMaintainers(),
|
||||
];
|
||||
if (latestVersionPackageReadme.version && latestVersionPackageReadme.readme) {
|
||||
var existsPackageReadme = yield packageService.getPackageReadme(name, true);
|
||||
if (!existsPackageReadme ||
|
||||
existsPackageReadme.version !== latestVersionPackageReadme.version ||
|
||||
existsPackageReadme.readme !== latestVersionPackageReadme.readme) {
|
||||
var r = yield packageService.savePackageReadme(name, latestVersionPackageReadme.readme, latestVersionPackageReadme.version);
|
||||
that.log(' save packageReadme: %s %s %s', r.id, r.name, r.version);
|
||||
}
|
||||
}
|
||||
|
||||
yield syncDes();
|
||||
yield syncTag();
|
||||
yield syncReadme();
|
||||
yield syncDeprecateds();
|
||||
yield syncMissingStarUsers();
|
||||
yield syncMissingUsers();
|
||||
yield syncNpmPackageMaintainers();
|
||||
yield syncModuleAbbreviateds();
|
||||
yield syncAbbreviatedMetadatas();
|
||||
yield syncDeprecatedsOnExistsModuleAbbreviated();
|
||||
|
||||
changedVersions = Object.keys(changedVersions);
|
||||
// hooks
|
||||
const envelope = {
|
||||
event: 'package:sync',
|
||||
name: name,
|
||||
type: 'package',
|
||||
version: null,
|
||||
hookOwner: null,
|
||||
payload: {
|
||||
changedVersions,
|
||||
},
|
||||
change: null,
|
||||
};
|
||||
hook.trigger(envelope);
|
||||
|
||||
return syncedVersionNames;
|
||||
};
|
||||
|
||||
@@ -899,19 +1311,23 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
var that = this;
|
||||
var username = this.username;
|
||||
var downurl = sourcePackage.dist.tarball;
|
||||
var filename = path.basename(downurl);
|
||||
var urlobj = urlparse(downurl);
|
||||
var filename = path.basename(urlobj.pathname);
|
||||
var filepath = common.getTarballFilepath(filename);
|
||||
var ws = fs.createWriteStream(filepath);
|
||||
|
||||
var options = {
|
||||
var downloadOptions = {
|
||||
writeStream: ws,
|
||||
followRedirect: true,
|
||||
timeout: 600000, // 10 minutes download
|
||||
headers: {
|
||||
'user-agent': USER_AGENT
|
||||
'user-agent': USER_AGENT,
|
||||
},
|
||||
gzip: true,
|
||||
};
|
||||
if (config.syncDownloadOptions) {
|
||||
Object.assign(downloadOptions, config.syncDownloadOptions);
|
||||
}
|
||||
|
||||
var dependencies = Object.keys(sourcePackage.dependencies || {});
|
||||
var devDependencies = [];
|
||||
@@ -957,7 +1373,7 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
logger.syncInfo('[sync_module_worker] downloading %j to %j', downurl, filepath);
|
||||
var r;
|
||||
try {
|
||||
r = yield urllib.request(downurl, options);
|
||||
r = yield urllib.request(downurl, downloadOptions);
|
||||
} catch (err) {
|
||||
logger.syncInfo('[sync_module_worker] download %j to %j error: %s', downurl, filepath, err);
|
||||
throw err;
|
||||
@@ -967,7 +1383,7 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
// https://github.com/cnpm/cnpmjs.org/issues/325
|
||||
// if (statusCode === 404) {
|
||||
// shasum = sourcePackage.dist.shasum;
|
||||
// return yield *afterUpload({
|
||||
// return yield afterUpload({
|
||||
// url: downurl
|
||||
// });
|
||||
// }
|
||||
@@ -976,6 +1392,7 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
var err = new Error('Download ' + downurl + ' fail, status: ' + statusCode);
|
||||
err.name = 'DownloadTarballError';
|
||||
err.data = sourcePackage;
|
||||
err.status = statusCode;
|
||||
logger.syncInfo('[sync_module_worker] %s', err.message);
|
||||
throw err;
|
||||
}
|
||||
@@ -1008,16 +1425,16 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
throw err;
|
||||
}
|
||||
|
||||
options = {
|
||||
var uploadOptions = {
|
||||
key: common.getCDNKey(sourcePackage.name, filename),
|
||||
size: dataSize,
|
||||
shasum: shasum
|
||||
};
|
||||
// upload to NFS
|
||||
logger.syncInfo('[sync_module_worker] uploading %j to nfs', options);
|
||||
logger.syncInfo('[sync_module_worker] uploading %j to nfs', uploadOptions);
|
||||
var result;
|
||||
try {
|
||||
result = yield nfs.upload(filepath, options);
|
||||
result = yield nfs.upload(filepath, uploadOptions);
|
||||
} catch (err) {
|
||||
logger.syncInfo('[sync_module_worker] upload %j to nfs error: %s', err);
|
||||
throw err;
|
||||
@@ -1036,8 +1453,12 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
//make sure sync module have the correct author info
|
||||
//only if can not get maintainers, use the username
|
||||
var author = username;
|
||||
if (Array.isArray(sourcePackage.maintainers)) {
|
||||
if (Array.isArray(sourcePackage.maintainers) && sourcePackage.maintainers.length > 0) {
|
||||
author = sourcePackage.maintainers[0].name || username;
|
||||
} else if (sourcePackage._npmUser && sourcePackage._npmUser.name) {
|
||||
// try to use _npmUser instead
|
||||
author = sourcePackage._npmUser.name;
|
||||
sourcePackage.maintainers = [ sourcePackage._npmUser ];
|
||||
}
|
||||
|
||||
var mod = {
|
||||
@@ -1070,14 +1491,21 @@ SyncModuleWorker.prototype._syncOneVersion = function *(versionIndex, sourcePack
|
||||
|
||||
mod.package.dist = dist;
|
||||
var r = yield packageService.saveModule(mod);
|
||||
var moduleAbbreviatedId = null;
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
var moduleAbbreviatedResult = yield packageService.saveModuleAbbreviated(mod);
|
||||
moduleAbbreviatedId = moduleAbbreviatedResult.id;
|
||||
}
|
||||
|
||||
that.log(' [%s:%s] done, insertId: %s, author: %s, version: %s, '
|
||||
+ 'size: %d, publish_time: %j, publish on cnpm: %s',
|
||||
+ 'size: %d, publish_time: %j, publish on cnpm: %s, '
|
||||
+ 'moduleAbbreviatedId: %s',
|
||||
sourcePackage.name, versionIndex,
|
||||
r.id,
|
||||
author, mod.version, dataSize,
|
||||
new Date(mod.publish_time),
|
||||
that._publish);
|
||||
that._publish,
|
||||
moduleAbbreviatedId);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -4,18 +4,34 @@ const Total = require('../services/total');
|
||||
const version = require('../package.json').version;
|
||||
const config = require('../config');
|
||||
const getDownloadTotal = require('./utils').getDownloadTotal;
|
||||
const cacheClient = require('../common/cache');
|
||||
const logger = require('../common/logger');
|
||||
|
||||
const startTime = '' + Date.now();
|
||||
let cache = null;
|
||||
|
||||
module.exports = function* showTotal() {
|
||||
if (cache && Date.now() - cache.cache_time < 10000) {
|
||||
// cache 10 seconds
|
||||
if (cache && Date.now() - cache.cache_time < 120000) {
|
||||
// cache 120 seconds
|
||||
this.body = cache;
|
||||
return;
|
||||
}
|
||||
|
||||
const r = yield [Total.get(), getDownloadTotal()];
|
||||
const cacheKey = 'registry_total';
|
||||
if (cacheClient) {
|
||||
const result = yield cacheClient.get(cacheKey);
|
||||
if (result) {
|
||||
this.body = JSON.parse(result);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (cache) {
|
||||
// set cache_time fisrt, avoid query in next time
|
||||
cache.cache_time = Date.now();
|
||||
}
|
||||
|
||||
const r = yield [ Total.get(), getDownloadTotal() ];
|
||||
const total = r[0];
|
||||
const download = r[1];
|
||||
|
||||
@@ -28,7 +44,17 @@ module.exports = function* showTotal() {
|
||||
total.sync_model = config.syncModel;
|
||||
|
||||
cache = total;
|
||||
total.cache_time = Date.now();
|
||||
cache.cache_time = Date.now();
|
||||
|
||||
this.body = total;
|
||||
if (cacheClient) {
|
||||
cacheClient.pipeline()
|
||||
.set(cacheKey, JSON.stringify(total))
|
||||
// cache 12h
|
||||
.expire(cacheKey, 3600 * 12)
|
||||
.exec()
|
||||
.catch(err => {
|
||||
logger.error(err);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,25 +1,12 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/utils.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:utils');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var utility = require('utility');
|
||||
var ms = require('humanize-ms');
|
||||
var moment = require('moment');
|
||||
var rimraf = require('rimraf');
|
||||
var downloadTotalService = require('../services/download_total');
|
||||
var nfs = require('../common/nfs');
|
||||
var config = require('../config');
|
||||
@@ -34,9 +21,13 @@ exports.downloadAsReadStream = function* (key) {
|
||||
|
||||
var tmpPath = path.join(config.uploadDir,
|
||||
utility.randomString() + key.replace(/\//g, '-'));
|
||||
var tarball;
|
||||
function cleanup() {
|
||||
debug('cleanup %s', tmpPath);
|
||||
fs.unlink(tmpPath, utility.noop);
|
||||
rimraf(tmpPath, utility.noop);
|
||||
if (tarball) {
|
||||
tarball.destroy();
|
||||
}
|
||||
}
|
||||
debug('downloadAsReadStream() %s to %s', key, tmpPath);
|
||||
try {
|
||||
@@ -46,7 +37,7 @@ exports.downloadAsReadStream = function* (key) {
|
||||
cleanup();
|
||||
throw err;
|
||||
}
|
||||
var tarball = fs.createReadStream(tmpPath);
|
||||
tarball = fs.createReadStream(tmpPath);
|
||||
tarball.once('error', cleanup);
|
||||
tarball.once('end', cleanup);
|
||||
return tarball;
|
||||
@@ -70,7 +61,7 @@ exports.getDownloadTotal = function* (name) {
|
||||
args.unshift(name);
|
||||
}
|
||||
|
||||
var rows = yield* downloadTotalService[method].apply(downloadTotalService, args);
|
||||
var rows = yield downloadTotalService[method].apply(downloadTotalService, args);
|
||||
var download = {
|
||||
today: 0,
|
||||
thisweek: 0,
|
||||
|
||||
@@ -1,31 +1,20 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/web/badge.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utility = require('utility');
|
||||
var util = require('util');
|
||||
var config = require('../../config');
|
||||
var packageService = require('../../services/package');
|
||||
var DownloadTotal = require('../../services/download_total');
|
||||
|
||||
exports.version = function* () {
|
||||
var color = 'lightgrey';
|
||||
var version = 'invalid';
|
||||
var color = 'grey';
|
||||
var name = this.params[0];
|
||||
var tag = this.query.tag || 'latest';
|
||||
var info = yield* packageService.getModuleByTag(name, tag);
|
||||
var version = this.query.version;
|
||||
let info;
|
||||
if (version) {
|
||||
info = yield packageService.getModule(name, version);
|
||||
} else {
|
||||
info = yield packageService.getModuleByTag(name, tag);
|
||||
}
|
||||
if (info) {
|
||||
version = info.version;
|
||||
if (/^0\.0\./.test(version)) {
|
||||
@@ -40,14 +29,15 @@ exports.version = function* () {
|
||||
}
|
||||
}
|
||||
|
||||
var subject = config.badgeSubject.replace(/\-/g, '--');
|
||||
var subject = config.badgeSubject;
|
||||
if (this.query.subject) {
|
||||
subject = this.query.subject.replace(/\-/g, '--');
|
||||
subject = this.query.subject;
|
||||
}
|
||||
if (!version) {
|
||||
version = 'invalid';
|
||||
}
|
||||
version = version.replace(/\-/g, '--');
|
||||
var style = this.query.style || 'flat-square';
|
||||
var url = util.format(config.badgePrefixURL + '/%s-%s-%s.svg?style=%s',
|
||||
utility.encodeURIComponent(subject), version, color, utility.encodeURIComponent(style));
|
||||
var url = config.badgeService.url(subject, version, { color, style });
|
||||
this.redirect(url);
|
||||
};
|
||||
|
||||
@@ -55,8 +45,7 @@ exports.downloads = function* () {
|
||||
// https://dn-img-shields-io.qbox.me/badge/downloads-100k/month-brightgreen.svg?style=flat-square
|
||||
var name = this.params[0];
|
||||
var count = yield DownloadTotal.getTotalByName(name);
|
||||
var style = this.query.style || 'flat-square';
|
||||
var url = util.format(config.badgePrefixURL + '/downloads-%s-brightgreen.svg?style=%s',
|
||||
count, utility.encodeURIComponent(style));
|
||||
var style = this.query.style;
|
||||
var url = config.badgeService.url('downloads', count, { style });
|
||||
this.redirect(url);
|
||||
};
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/web/package/list_privates.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../../../services/package');
|
||||
var config = require('../../../config');
|
||||
|
||||
|
||||
@@ -1,22 +1,8 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/web/package/search.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:controllers:web:package:search');
|
||||
var packageService = require('../../../services/package');
|
||||
var config = require('../../../config');
|
||||
|
||||
module.exports = function* search() {
|
||||
var params = this.params;
|
||||
@@ -27,8 +13,12 @@ module.exports = function* search() {
|
||||
limit = 10000;
|
||||
}
|
||||
|
||||
if (config.disableSearch) {
|
||||
return this.redirect(`/package/${encodeURIComponent(word)}`);
|
||||
}
|
||||
|
||||
debug('search %j', word);
|
||||
var result = yield* packageService.search(word, {
|
||||
var result = yield packageService.search(word, {
|
||||
limit: limit
|
||||
});
|
||||
|
||||
|
||||
@@ -1,20 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/web/package/search_range.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../../../services/package');
|
||||
|
||||
module.exports = function* searchRange() {
|
||||
@@ -26,7 +11,7 @@ module.exports = function* searchRange() {
|
||||
startKey = startKey.substring(0, startKey.length - 1);
|
||||
}
|
||||
var limit = Number(this.query.limit) || 20;
|
||||
var result = yield* packageService.search(startKey, {limit: limit});
|
||||
var result = yield packageService.search(startKey, {limit: limit});
|
||||
|
||||
var packages = result.searchMatchs.concat(result.keywordMatchs);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ var utils = require('../../utils');
|
||||
var setDownloadURL = require('../../../lib/common').setDownloadURL;
|
||||
var renderMarkdown = require('../../../common/markdown').render;
|
||||
var packageService = require('../../../services/package');
|
||||
var downloadTotalService = require('../../../services/download_total');
|
||||
|
||||
module.exports = function* show(next) {
|
||||
var params = this.params;
|
||||
@@ -34,9 +35,17 @@ module.exports = function* show(next) {
|
||||
}
|
||||
|
||||
var pkg = yield packageService[getPackageMethod].apply(packageService, getPackageArgs);
|
||||
if ((!pkg || !pkg.package) && tag) {
|
||||
// + if we can't find it by tag, it may be a non-semver version, check it then
|
||||
// + if we can't find it by version, it may be a tag, check it then
|
||||
getPackageMethod = version ? 'getModuleByTag' : 'getModule';
|
||||
pkg = yield packageService[getPackageMethod](name, tag);
|
||||
}
|
||||
|
||||
// if it's still not found
|
||||
if (!pkg || !pkg.package) {
|
||||
// check if unpublished
|
||||
var unpublishedInfo = yield* packageService.getUnpublishedModule(name);
|
||||
var unpublishedInfo = yield packageService.getUnpublishedModule(name);
|
||||
debug('show unpublished %j', unpublishedInfo);
|
||||
if (unpublishedInfo) {
|
||||
var data = {
|
||||
@@ -59,23 +68,55 @@ module.exports = function* show(next) {
|
||||
return;
|
||||
}
|
||||
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var r = yield [
|
||||
utils.getDownloadTotal(name),
|
||||
packageService.listDependents(name),
|
||||
packageService.listStarUserNames(name),
|
||||
packageService.listMaintainers(name)
|
||||
packageService.listMaintainers(name),
|
||||
packageService.listModulesByName(name),
|
||||
packageService.listModuleTags(name),
|
||||
downloadTotalService.getTotalByName(name),
|
||||
];
|
||||
var download = r[0];
|
||||
var dependents = r[1];
|
||||
var users = r[2];
|
||||
var maintainers = r[3];
|
||||
var rows = r[4];
|
||||
var tags = r[5];
|
||||
var downloadTotal = r[6];
|
||||
|
||||
const versionsMap = {};
|
||||
const versions = [];
|
||||
for (const row of rows) {
|
||||
var versionPkg = row.package;
|
||||
// pkg is string ... ignore it
|
||||
if (typeof versionPkg === 'string') {
|
||||
continue;
|
||||
}
|
||||
versionPkg.fromNow = moment(versionPkg.publish_time || row.publish_time).fromNow();
|
||||
versions.push(versionPkg);
|
||||
versionsMap[versionPkg.version] = versionPkg;
|
||||
}
|
||||
|
||||
for (const row of tags) {
|
||||
row.fromNow = versionsMap[row.version] && versionsMap[row.version].fromNow;
|
||||
}
|
||||
|
||||
pkg.package.fromNow = moment(pkg.publish_time).fromNow();
|
||||
pkg = pkg.package;
|
||||
pkg.users = users;
|
||||
pkg.versions = versions;
|
||||
pkg.tags = tags;
|
||||
|
||||
if (!pkg.readme && config.enableAbbreviatedMetadata) {
|
||||
var packageReadme = yield packageService.getPackageReadme(name);
|
||||
if (packageReadme) {
|
||||
pkg.readme = packageReadme.readme;
|
||||
}
|
||||
}
|
||||
if (pkg.readme && typeof pkg.readme !== 'string') {
|
||||
pkg.readme = 'readme is not string: ' + JSON.stringify(pkg.readme);
|
||||
} else {
|
||||
@@ -110,7 +151,9 @@ module.exports = function* show(next) {
|
||||
pkg.repository = null;
|
||||
}
|
||||
if (pkg.repository && pkg.repository.url) {
|
||||
pkg.repository.weburl = /^https?:\/\//.test(pkg.repository.url) ? pkg.repository.url : (giturl.parse(pkg.repository.url) || pkg.repository.url);
|
||||
if (!pkg.repository.weburl) {
|
||||
pkg.repository.weburl = /^https?:\/\//.test(pkg.repository.url) ? pkg.repository.url : (giturl.parse(pkg.repository.url) || pkg.repository.url);
|
||||
}
|
||||
}
|
||||
if (!pkg.bugs) {
|
||||
pkg.bugs = {};
|
||||
@@ -134,6 +177,7 @@ module.exports = function* show(next) {
|
||||
}
|
||||
|
||||
pkg.registryUrl = '//' + config.registryHost + '/' + pkg.name;
|
||||
pkg.registryPackageUrl = '//' + config.registryHost + '/' + pkg.name + '/' + pkg.version;
|
||||
|
||||
// pkg.engines = {
|
||||
// "python": ">= 0.11.9",
|
||||
@@ -142,48 +186,58 @@ module.exports = function* show(next) {
|
||||
// "node2": ">= 0.10.9",
|
||||
// "node3": ">= 0.6.9",
|
||||
// };
|
||||
if (pkg.engines) {
|
||||
for (var k in pkg.engines) {
|
||||
var engine = String(pkg.engines[k] || '').trim();
|
||||
var color = 'blue';
|
||||
if (k.indexOf('node') === 0) {
|
||||
color = 'yellowgreen';
|
||||
var version = /(\d+\.\d+\.\d+)/.exec(engine);
|
||||
if (version) {
|
||||
version = version[0];
|
||||
if (/^0\.11\.\d+/.test(version)) {
|
||||
color = 'red';
|
||||
} else if (/^0\.10\./.test(version) ||
|
||||
/^0\.12\./.test(version) ||
|
||||
/^0\.14\./.test(version) ||
|
||||
/^[^0]+\./.test(version)) {
|
||||
color = 'brightgreen';
|
||||
}
|
||||
}
|
||||
}
|
||||
pkg.engines[k] = {
|
||||
version: engine,
|
||||
title: k + ': ' + engine,
|
||||
badgeURL: config.badgePrefixURL + '/' + encodeURIComponent(k) +
|
||||
'-' + encodeURIComponent(engine) + '-' + color + '.svg?style=flat-square',
|
||||
};
|
||||
}
|
||||
// "engines": "0.10.24",
|
||||
// invalid engines
|
||||
if (pkg.engines && typeof pkg.engines !== 'object') {
|
||||
pkg.engines = {};
|
||||
}
|
||||
|
||||
for (var k in pkg.engines) {
|
||||
var engine = String(pkg.engines[k] || '').trim();
|
||||
var color = 'blue';
|
||||
if (k.indexOf('node') === 0 || k.indexOf('install-') === 0) {
|
||||
color = 'green';
|
||||
var version = /(\d+\.)/.exec(engine);
|
||||
if (version) {
|
||||
version = version[0];
|
||||
if (/^[0123]\./.test(version)) {
|
||||
color = 'red';
|
||||
}
|
||||
}
|
||||
if (engine === '*') {
|
||||
color = 'red';
|
||||
}
|
||||
}
|
||||
pkg.engines[k] = {
|
||||
version: engine,
|
||||
title: k + ': ' + engine,
|
||||
badgeURL: config.badgeService.url(k, engine, { color }),
|
||||
};
|
||||
}
|
||||
|
||||
let packagephobiaSupport = downloadTotal >= config.packagephobiaMinDownloadCount;
|
||||
if (pkg._publish_on_cnpm) {
|
||||
pkg.isPrivate = true;
|
||||
// need download total >= 1000
|
||||
packagephobiaSupport = downloadTotal >= config.packagephobiaMinDownloadCount && config.packagephobiaSupportPrivatePackage;
|
||||
} else {
|
||||
pkg.isPrivate = false;
|
||||
// add security check badge
|
||||
pkg.snyk = {
|
||||
badge: `${config.snykUrl}/test/npm/${pkg.name}/badge.svg?style=flat-square`,
|
||||
badge: `${config.snykUrl}/test/npm/${pkg.name}/badge.svg`,
|
||||
url: `${config.snykUrl}/test/npm/${pkg.name}`,
|
||||
};
|
||||
}
|
||||
if (packagephobiaSupport) {
|
||||
pkg.packagephobia = {
|
||||
badge: `${config.packagephobiaURL}/badge?p=${pkg.name}@${pkg.version}`,
|
||||
url: `${config.packagephobiaURL}/result?p=${pkg.name}@${pkg.version}`,
|
||||
};
|
||||
}
|
||||
|
||||
yield this.render('package', {
|
||||
title: 'Package - ' + pkg.name,
|
||||
package: pkg,
|
||||
download: download
|
||||
download: download,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
/**!
|
||||
* cnpmjs.org - controllers/web/user/show.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../../../config');
|
||||
var packageService = require('../../../services/package');
|
||||
var userService = require('../../../services/user');
|
||||
var common = require('../../../lib/common');
|
||||
var he = require('he');
|
||||
|
||||
module.exports = function* showUser(next) {
|
||||
var name = this.params.name;
|
||||
@@ -29,14 +15,14 @@ module.exports = function* showUser(next) {
|
||||
var packages = r[0];
|
||||
var user = r[1];
|
||||
if (!user && !packages.length) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
|
||||
user = user || {};
|
||||
|
||||
var data = {
|
||||
name: name,
|
||||
email: user.email,
|
||||
email: user.email ? he.encode(user.email, { encodeEverything: true }) : user.email,
|
||||
json: user.json || {},
|
||||
isNpmUser: user.isNpmUser,
|
||||
};
|
||||
|
||||
30
docker-compose.yml
Normal file
30
docker-compose.yml
Normal file
@@ -0,0 +1,30 @@
|
||||
version: '3'
|
||||
services:
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: cnpmjs.org
|
||||
depends_on:
|
||||
- mysql-db
|
||||
volumes:
|
||||
- cnpm-files-volume:/var/data/cnpm_data
|
||||
ports:
|
||||
- "7001:7001"
|
||||
- "7002:7002"
|
||||
|
||||
mysql-db:
|
||||
image: mysql:5.6
|
||||
restart: always
|
||||
environment :
|
||||
MYSQL_USER: root
|
||||
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
|
||||
MYSQL_DATABASE: cnpmjs_test
|
||||
MYSQL_ROOT_HOST: "%"
|
||||
volumes:
|
||||
- ./docs/db.sql:/docker-entrypoint-initdb.d/cnpm-init.sql
|
||||
- cnpm-db-volume:/var/lib/mysql
|
||||
|
||||
volumes:
|
||||
cnpm-files-volume:
|
||||
cnpm-db-volume:
|
||||
190
docs/db.sql
190
docs/db.sql
@@ -3,81 +3,96 @@ CREATE TABLE IF NOT EXISTS `user` (
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) NOT NULL COMMENT 'user name',
|
||||
`salt` varchar(100) NOT NULL,
|
||||
`salt` varchar(100) NOT NULL COMMENT 'user salt',
|
||||
`password_sha` varchar(100) NOT NULL COMMENT 'user password hash',
|
||||
`ip` varchar(64) NOT NULL COMMENT 'user last request ip',
|
||||
`roles` varchar(200) NOT NULL DEFAULT '[]',
|
||||
`rev` varchar(40) NOT NULL,
|
||||
`email` varchar(400) NOT NULL,
|
||||
`json` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'json details',
|
||||
`roles` varchar(200) NOT NULL DEFAULT '[]' COMMENT 'user roles',
|
||||
`rev` varchar(40) NOT NULL COMMENT 'user rev',
|
||||
`email` varchar(400) NOT NULL COMMENT 'user email',
|
||||
`json` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'json details',
|
||||
`npm_user` tinyint(1) DEFAULT '0' COMMENT 'user sync from npm or not, 1: true, other: false',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name` (`name`),
|
||||
KEY `gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='user base info';
|
||||
-- ALTER TABLE `user`
|
||||
-- ADD `json` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'json details',
|
||||
-- ADD `npm_user` tinyint(1) DEFAULT '0' COMMENT 'user sync from npm or not, 1: true, other: false';
|
||||
-- ALTER TABLE `user` CHANGE `json` `json` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'json details';
|
||||
-- ALTER TABLE `user`
|
||||
-- CHANGE `salt` `salt` varchar(100) NOT NULL COMMENT 'user salt',
|
||||
-- CHANGE `roles` `roles` varchar(200) NOT NULL DEFAULT '[]' COMMENT 'user roles',
|
||||
-- CHANGE `rev` `rev` varchar(40) NOT NULL COMMENT 'user rev',
|
||||
-- CHANGE `email` `email` varchar(400) NOT NULL COMMENT 'user email';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_keyword` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`keyword` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'keyword',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`description` longtext,
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`description` longtext COMMENT 'module description',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `keyword_module_name` (`keyword`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_keyword_module_name` (`keyword`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module keyword';
|
||||
-- ALTER TABLE `module_keyword`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
-- CHANGE `description` `description` longtext COMMENT 'module description';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_star` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `user_module_name` (`user`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module star';
|
||||
-- ALTER TABLE `module_star`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_maintainer` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `user_module_name` (`user`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='private module maintainers';
|
||||
-- ALTER TABLE `module_maintainer`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `npm_module_maintainer` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `user_module_name` (`user`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='npm original module maintainers';
|
||||
-- ALTER TABLE `npm_module_maintainer`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`author` varchar(100) NOT NULL,
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`author` varchar(100) NOT NULL COMMENT 'module author',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`description` longtext,
|
||||
`description` longtext COMMENT 'module description',
|
||||
`package` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'package.json',
|
||||
`dist_shasum` varchar(100) DEFAULT NULL,
|
||||
`dist_tarball` varchar(2048) DEFAULT NULL,
|
||||
`dist_size` int(10) unsigned NOT NULL DEFAULT '0',
|
||||
`publish_time` bigint(20) unsigned,
|
||||
`dist_shasum` varchar(100) DEFAULT NULL COMMENT 'module dist SHASUM',
|
||||
`dist_tarball` varchar(2048) DEFAULT NULL COMMENT 'module dist tarball',
|
||||
`dist_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'module dist size',
|
||||
`publish_time` bigint(20) unsigned COMMENT 'module publish time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name` (`name`,`version`),
|
||||
KEY `gmt_modified` (`gmt_modified`),
|
||||
KEY `publish_time` (`publish_time`),
|
||||
KEY `author` (`author`)
|
||||
UNIQUE KEY `uk_name` (`name`,`version`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`),
|
||||
KEY `idx_publish_time` (`publish_time`),
|
||||
KEY `idx_author` (`author`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module info';
|
||||
-- ALTER TABLE `module` ADD `description` longtext;
|
||||
-- ALTER TABLE `module` ADD `publish_time` bigint(20) unsigned, ADD KEY `publish_time` (`publish_time`);
|
||||
@@ -85,48 +100,97 @@ CREATE TABLE IF NOT EXISTS `module` (
|
||||
-- ALTER TABLE `module` CHANGE `description` `description` LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci;
|
||||
-- show create table module\G
|
||||
-- ALTER TABLE `module` CHANGE `name` `name` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
-- ALTER TABLE `module`
|
||||
-- CHANGE `author` `author` varchar(100) NOT NULL COMMENT 'module author',
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
-- CHANGE `version` `version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
-- CHANGE `description` `description` longtext COMMENT 'module description',
|
||||
-- CHANGE `package` `package` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'package.json',
|
||||
-- CHANGE `dist_shasum` `dist_shasum` varchar(100) DEFAULT NULL COMMENT 'module dist SHASUM',
|
||||
-- CHANGE `dist_tarball` `dist_tarball` varchar(2048) DEFAULT NULL COMMENT 'module dist tarball',
|
||||
-- CHANGE `dist_size` `dist_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'module dist size',
|
||||
-- CHANGE `publish_time` `publish_time` bigint(20) unsigned COMMENT 'module publish time';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_abbreviated` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`package` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'the abbreviated metadata',
|
||||
`publish_time` bigint(20) unsigned COMMENT 'the publish time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_name` (`name`,`version`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`),
|
||||
KEY `idx_publish_time` (`publish_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module abbreviated info';
|
||||
-- ALTER TABLE `module_abbreviated`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
-- CHANGE `publish_time` `publish_time` bigint(20) unsigned COMMENT 'the publish time';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `package_readme` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`readme` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'the latest version readme',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='package latest readme';
|
||||
-- ALTER TABLE `package_readme`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_log` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`username` varchar(100) NOT NULL,
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`log` longtext,
|
||||
`username` varchar(100) NOT NULL COMMENT 'which username',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`log` longtext COMMENT 'the raw log',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `name` (`name`)
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module sync log';
|
||||
-- ALTER TABLE `module_log` CHANGE `name` `name` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
-- ALTER TABLE `module_log`
|
||||
-- CHANGE `username` `username` varchar(100) NOT NULL COMMENT 'which username',
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
-- CHANGE `log` `log` longtext COMMENT 'the raw log';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `tag` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`tag` varchar(30) NOT NULL COMMENT 'tag name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`module_id` bigint(20) unsigned NOT NULL COMMENT 'module id',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name` (`name`, `tag`),
|
||||
KEY `gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`, `tag`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module tag';
|
||||
-- ALTER TABLE `tag` ADD `module_id` BIGINT( 20 ) UNSIGNED NOT NULL;
|
||||
-- ALTER TABLE `tag` CHANGE `name` `name` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
-- ALTER TABLE `tag` ADD KEY `gmt_modified` (`gmt_modified`);
|
||||
-- ALTER TABLE `tag`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_unpublished` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`package` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'base info: tags, time, maintainers, description, versions',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name` (`name`),
|
||||
KEY `gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module unpublished info';
|
||||
-- ALTER TABLE `module_unpublished`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `total` (
|
||||
`name` varchar(100) NOT NULL COMMENT 'total name',
|
||||
`name` varchar(214) NOT NULL COMMENT 'total name',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`module_delete` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'module delete count',
|
||||
`last_sync_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'last timestamp sync from official registry',
|
||||
@@ -150,6 +214,7 @@ INSERT INTO total(name, gmt_modified) VALUES('total', now())
|
||||
-- ALTER TABLE `total` ADD `fail_sync_num` int unsigned NOT NULL DEFAULT '0' COMMENT 'how many packages sync fail at this time'
|
||||
-- ALTER TABLE `total` ADD `left_sync_num` int unsigned NOT NULL DEFAULT '0' COMMENT 'how many packages left to be sync'
|
||||
-- ALTER TABLE `total` ADD `last_sync_module` varchar(100) NOT NULL COMMENT 'last sync success module name';
|
||||
-- ALTER TABLE `total` CHANGE `name` `name` varchar(214) NOT NULL COMMENT 'total name';
|
||||
|
||||
-- CREATE TABLE IF NOT EXISTS `download_total` (
|
||||
-- `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
@@ -168,7 +233,7 @@ CREATE TABLE IF NOT EXISTS `downloads` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`date` int unsigned NOT NULL COMMENT 'YYYYMM format',
|
||||
`d01` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '01 download count',
|
||||
`d02` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '02 download count',
|
||||
@@ -202,43 +267,54 @@ CREATE TABLE IF NOT EXISTS `downloads` (
|
||||
`d30` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '30 download count',
|
||||
`d31` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '31 download count',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name_date` (`name`, `date`),
|
||||
KEY `date` (`date`)
|
||||
UNIQUE KEY `uk_name_date` (`name`, `date`),
|
||||
KEY `idx_date` (`date`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module download total info';
|
||||
-- ALTER TABLE `downloads`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `module_deps` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`deps` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'which module depend on this module',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`deps` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'which module depend on this module',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name_deps` (`name`,`deps`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_name_deps` (`name`,`deps`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module deps';
|
||||
-- ALTER TABLE `module_deps`
|
||||
-- CHANGE `name` `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
-- CHANGE `deps` `deps` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'which module depend on this module';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `dist_dir` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(200) NOT NULL COMMENT 'dir name',
|
||||
`parent` varchar(200) NOT NULL COMMENT 'parent dir' DEFAULT '/',
|
||||
`name` varchar(214) NOT NULL COMMENT 'dir name',
|
||||
`parent` varchar(214) NOT NULL COMMENT 'parent dir' DEFAULT '/',
|
||||
`date` varchar(20) COMMENT '02-May-2014 01:06',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `name` (`parent`, `name`),
|
||||
KEY `gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`parent`, `name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='dist dir info';
|
||||
-- ALTER TABLE `dist_dir`
|
||||
-- CHANGE `name` `name` varchar(214) NOT NULL COMMENT 'dir name',
|
||||
-- CHANGE `parent` `parent` varchar(214) NOT NULL COMMENT 'parent dir' DEFAULT '/';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `dist_file` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) NOT NULL COMMENT 'file name',
|
||||
`parent` varchar(200) NOT NULL COMMENT 'parent dir' DEFAULT '/',
|
||||
`name` varchar(214) NOT NULL COMMENT 'file name',
|
||||
`parent` varchar(214) NOT NULL COMMENT 'parent dir' DEFAULT '/',
|
||||
`date` varchar(20) COMMENT '02-May-2014 01:06',
|
||||
`size` int(10) unsigned NOT NULL COMMENT 'file size' DEFAULT '0',
|
||||
`sha1` varchar(40) COMMENT 'sha1 hex value',
|
||||
`url` varchar(2048),
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `fullname` (`parent`, `name`),
|
||||
KEY `gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_fullname` (`parent`, `name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='dist file info';
|
||||
-- ALTER TABLE `dist_file`
|
||||
-- CHANGE `name` `name` varchar(214) NOT NULL COMMENT 'file name',
|
||||
-- CHANGE `parent` `parent` varchar(214) NOT NULL COMMENT 'parent dir' DEFAULT '/';
|
||||
|
||||
261
docs/dockerize/config.js
Normal file
261
docs/dockerize/config.js
Normal file
@@ -0,0 +1,261 @@
|
||||
'use strict';
|
||||
|
||||
var mkdirp = require('mkdirp');
|
||||
var copy = require('copy-to');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var os = require('os');
|
||||
|
||||
var version = require('../package.json').version;
|
||||
|
||||
var root = path.dirname(__dirname);
|
||||
var dataDir = process.env.CNPM_DATA_DIR ;
|
||||
|
||||
var config = {
|
||||
version: version,
|
||||
dataDir: dataDir,
|
||||
|
||||
/**
|
||||
* Cluster mode
|
||||
*/
|
||||
enableCluster: false,
|
||||
numCPUs: os.cpus().length,
|
||||
|
||||
/*
|
||||
* server configure
|
||||
*/
|
||||
|
||||
registryPort: 7001,
|
||||
webPort: 7002,
|
||||
bindingHost: '0.0.0.0', // binding on 0.0.0.0 for outside of container access
|
||||
|
||||
// debug mode
|
||||
// if in debug mode, some middleware like limit wont load
|
||||
// logger module will print to stdout
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
// page mode, enable on development env
|
||||
pagemock: process.env.NODE_ENV === 'development',
|
||||
// session secret
|
||||
sessionSecret: 'cnpmjs.org test session secret',
|
||||
// max request json body size
|
||||
jsonLimit: '10mb',
|
||||
// log dir name
|
||||
logdir: path.join(dataDir, 'logs'),
|
||||
// update file template dir
|
||||
uploadDir: path.join(dataDir, 'downloads'),
|
||||
// web page viewCache
|
||||
viewCache: false,
|
||||
|
||||
// config for koa-limit middleware
|
||||
// for limit download rates
|
||||
limit: {
|
||||
enable: false,
|
||||
token: 'koa-limit:download',
|
||||
limit: 1000,
|
||||
interval: 1000 * 60 * 60 * 24,
|
||||
whiteList: [],
|
||||
blackList: [],
|
||||
message: 'request frequency limited, any question, please contact fengmk2@gmail.com',
|
||||
},
|
||||
|
||||
enableCompress: false, // enable gzip response or not
|
||||
|
||||
// default system admins
|
||||
admins: {
|
||||
// name: email
|
||||
fengmk2: 'fengmk2@gmail.com',
|
||||
admin: 'admin@cnpmjs.org',
|
||||
dead_horse: 'dead_horse@qq.com',
|
||||
},
|
||||
|
||||
// email notification for errors
|
||||
// check https://github.com/andris9/Nodemailer for more informations
|
||||
mail: {
|
||||
enable: false,
|
||||
appname: 'cnpmjs.org',
|
||||
from: 'cnpmjs.org mail sender <adderss@gmail.com>',
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
user: 'address@gmail.com',
|
||||
pass: 'your password'
|
||||
}
|
||||
},
|
||||
|
||||
logoURL: 'https://os.alipayobjects.com/rmsportal/oygxuIUkkrRccUz.jpg', // cnpm logo image url
|
||||
adBanner: '',
|
||||
customReadmeFile: '', // you can use your custom readme file instead the cnpm one
|
||||
customFooter: '', // you can add copyright and site total script html here
|
||||
npmClientName: 'cnpm', // use `${name} install package`
|
||||
packagePageContributorSearch: true, // package page contributor link to search, default is true
|
||||
|
||||
// max handle number of package.json `dependencies` property
|
||||
maxDependencies: 200,
|
||||
// backup filepath prefix
|
||||
backupFilePrefix: '/cnpm/backup/',
|
||||
|
||||
/**
|
||||
* database config
|
||||
*/
|
||||
|
||||
database: {
|
||||
db: 'cnpmjs_test',
|
||||
username: 'root',
|
||||
password: '',
|
||||
|
||||
// the sql dialect of the database
|
||||
// - currently supported: 'mysql', 'sqlite', 'postgres', 'mariadb'
|
||||
dialect: 'mysql',
|
||||
|
||||
// the Docker container network hostname defined at docker-compose.yml
|
||||
host: 'mysql-db',
|
||||
|
||||
// custom port; default: 3306
|
||||
port: 3306,
|
||||
|
||||
// use pooling in order to reduce db connection overload and to increase speed
|
||||
// currently only for mysql and postgresql (since v1.5.0)
|
||||
pool: {
|
||||
maxConnections: 10,
|
||||
minConnections: 0,
|
||||
maxIdleTime: 30000
|
||||
},
|
||||
|
||||
// the storage engine for 'sqlite'
|
||||
// default store into ~/.cnpmjs.org/data.sqlite
|
||||
//storage: path.join(dataDir, 'data.sqlite'),
|
||||
|
||||
logging: !!process.env.SQL_DEBUG,
|
||||
},
|
||||
|
||||
// package tarball store in local filesystem by default
|
||||
nfs: require('fs-cnpm')({
|
||||
dir: path.join(dataDir, 'nfs')
|
||||
}),
|
||||
// if set true, will 302 redirect to `nfs.url(dist.key)`
|
||||
downloadRedirectToNFS: false,
|
||||
|
||||
// registry url name
|
||||
registryHost: '127.0.0.1:7001',
|
||||
|
||||
/**
|
||||
* registry mode config
|
||||
*/
|
||||
|
||||
// enable private mode or not
|
||||
// private mode: only admins can publish, other users just can sync package from source npm
|
||||
// public mode: all users can publish
|
||||
enablePrivate: false,
|
||||
|
||||
// registry scopes, if don't set, means do not support scopes
|
||||
scopes: [ '@cnpm', '@cnpmtest', '@cnpm-test' ],
|
||||
|
||||
// some registry already have some private packages in global scope
|
||||
// but we want to treat them as scoped private packages,
|
||||
// so you can use this white list.
|
||||
privatePackages: [],
|
||||
|
||||
/**
|
||||
* sync configs
|
||||
*/
|
||||
|
||||
// the official npm registry
|
||||
// cnpm wont directly sync from this one
|
||||
// but sometimes will request it for some package infomations
|
||||
// please don't change it if not necessary
|
||||
officialNpmRegistry: 'https://registry.npmjs.com',
|
||||
officialNpmReplicate: 'https://replicate.npmjs.com',
|
||||
|
||||
// sync source, upstream registry
|
||||
// If you want to directly sync from official npm's registry
|
||||
// please drop them an email first
|
||||
sourceNpmRegistry: 'https://registry.npm.taobao.org',
|
||||
|
||||
// upstream registry is base on cnpm/cnpmjs.org or not
|
||||
// if your upstream is official npm registry, please turn it off
|
||||
sourceNpmRegistryIsCNpm: true,
|
||||
|
||||
// if install return 404, try to sync from source registry
|
||||
syncByInstall: true,
|
||||
|
||||
// sync mode select
|
||||
// none: do not sync any module, proxy all public modules from sourceNpmRegistry
|
||||
// exist: only sync exist modules
|
||||
// all: sync all modules
|
||||
syncModel: 'none', // 'none', 'all', 'exist'
|
||||
|
||||
syncConcurrency: 1,
|
||||
// sync interval, default is 10 minutes
|
||||
syncInterval: '10m',
|
||||
|
||||
// sync polular modules, default to false
|
||||
// because cnpm can't auto sync tag change for now
|
||||
// so we want to sync popular modules to ensure their tags
|
||||
syncPopular: false,
|
||||
syncPopularInterval: '1h',
|
||||
// top 100
|
||||
topPopular: 100,
|
||||
|
||||
// sync devDependencies or not, default is false
|
||||
syncDevDependencies: false,
|
||||
|
||||
// changes streaming sync
|
||||
syncChangesStream: false,
|
||||
handleSyncRegistry: 'http://127.0.0.1:7001',
|
||||
|
||||
// badge subject on http://shields.io/
|
||||
badgePrefixURL: 'https://img.shields.io/badge',
|
||||
badgeSubject: 'cnpm',
|
||||
|
||||
// custom user service, @see https://github.com/cnpm/cnpmjs.org/wiki/Use-Your-Own-User-Authorization
|
||||
// when you not intend to ingegrate with your company's user system, then use null, it would
|
||||
// use the default cnpm user system
|
||||
userService: null,
|
||||
|
||||
// always-auth https://docs.npmjs.com/misc/config#always-auth
|
||||
// Force npm to always require authentication when accessing the registry, even for GET requests.
|
||||
alwaysAuth: false,
|
||||
|
||||
// if you're behind firewall, need to request through http proxy, please set this
|
||||
// e.g.: `httpProxy: 'http://proxy.mycompany.com:8080'`
|
||||
httpProxy: null,
|
||||
|
||||
// snyk.io root url
|
||||
snykUrl: 'https://snyk.io',
|
||||
|
||||
// https://github.com/cnpm/cnpmjs.org/issues/1149
|
||||
// if enable this option, must create module_abbreviated and package_readme table in database
|
||||
enableAbbreviatedMetadata: true,
|
||||
|
||||
// global hook function: function* (envelope) {}
|
||||
// envelope format please see https://github.com/npm/registry/blob/master/docs/hooks/hooks-payload.md#payload
|
||||
globalHook: null,
|
||||
};
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
var customConfig;
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
customConfig = path.join(root, 'config', 'config.js');
|
||||
} else {
|
||||
// 1. try to load `$dataDir/config.json` first, not exists then goto 2.
|
||||
// 2. load config/config.js, everything in config.js will cover the same key in index.js
|
||||
customConfig = path.join(dataDir, 'config.json');
|
||||
if (!fs.existsSync(customConfig)) {
|
||||
customConfig = path.join(root, 'config', 'config.js');
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(customConfig)) {
|
||||
copy(require(customConfig)).override(config);
|
||||
}
|
||||
}
|
||||
|
||||
mkdirp.sync(config.logdir);
|
||||
mkdirp.sync(config.uploadDir);
|
||||
|
||||
module.exports = config;
|
||||
|
||||
config.loadConfig = function (customConfig) {
|
||||
if (!customConfig) {
|
||||
return;
|
||||
}
|
||||
copy(customConfig).override(config);
|
||||
};
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - lib/common.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var crypto = require('crypto');
|
||||
var path = require('path');
|
||||
var config = require('../config');
|
||||
@@ -38,9 +24,14 @@ exports.getCDNKey = function (name, filename) {
|
||||
exports.setDownloadURL = function (pkg, ctx, host) {
|
||||
if (pkg.dist) {
|
||||
host = host || config.registryHost || ctx.host;
|
||||
var protocol = config.protocol || ctx.protocol;
|
||||
pkg.dist.tarball = util.format('%s://%s/%s/download/%s-%s.tgz',
|
||||
ctx.protocol,
|
||||
protocol,
|
||||
host, pkg.name, pkg.name, pkg.version);
|
||||
if (ctx.querystring) {
|
||||
var backupUrl = pkg.dist.tarball;
|
||||
pkg.dist.tarball += '?' + ctx.querystring + '&other_urls=' + encodeURIComponent(backupUrl);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/auth.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:middleware:auth');
|
||||
var UserService = require('../services/user');
|
||||
var config = require('../config');
|
||||
@@ -31,13 +17,13 @@ module.exports = function () {
|
||||
authorization = authorization.trim();
|
||||
debug('%s %s with %j', this.method, this.url, authorization);
|
||||
if (!authorization) {
|
||||
return yield* unauthorized.call(this, next);
|
||||
return yield unauthorized.call(this, next);
|
||||
}
|
||||
|
||||
authorization = new Buffer(authorization, 'base64').toString();
|
||||
authorization = Buffer.from(authorization, 'base64').toString();
|
||||
var pos = authorization.indexOf(':');
|
||||
if (pos === -1) {
|
||||
return yield* unauthorized.call(this, next);
|
||||
return yield unauthorized.call(this, next);
|
||||
}
|
||||
|
||||
var username = authorization.slice(0, pos);
|
||||
@@ -45,7 +31,7 @@ module.exports = function () {
|
||||
|
||||
var row;
|
||||
try {
|
||||
row = yield* UserService.auth(username, password);
|
||||
row = yield UserService.auth(username, password);
|
||||
} catch (err) {
|
||||
// do not response error here
|
||||
// many request do not need login
|
||||
@@ -54,27 +40,28 @@ module.exports = function () {
|
||||
|
||||
if (!row) {
|
||||
debug('auth fail user: %j, headers: %j', row, this.header);
|
||||
return yield* unauthorized.call(this, next);
|
||||
return yield unauthorized.call(this, next);
|
||||
}
|
||||
|
||||
this.user.name = row.login;
|
||||
this.user.isAdmin = row.site_admin;
|
||||
this.user.scopes = row.scopes;
|
||||
debug('auth pass user: %j, headers: %j', this.user, this.header);
|
||||
yield* next;
|
||||
yield next;
|
||||
};
|
||||
};
|
||||
|
||||
function* unauthorized(next) {
|
||||
if (!config.alwaysAuth || this.method !== 'GET') {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
this.status = 401;
|
||||
this.set('WWW-Authenticate', 'Basic realm="sample"');
|
||||
if (this.accepts(['html', 'json']) === 'json') {
|
||||
const error = '[unauthorized] login first';
|
||||
this.body = {
|
||||
error: 'unauthorized',
|
||||
reason: 'login first'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
} else {
|
||||
this.body = 'login first';
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/block.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
module.exports = function () {
|
||||
return function* block(next) {
|
||||
var ua = String(this.get('user-agent')).toLowerCase();
|
||||
@@ -23,6 +9,6 @@ module.exports = function () {
|
||||
message: 'forbidden Ruby user-agent, ip: ' + this.ip
|
||||
};
|
||||
}
|
||||
yield* next;
|
||||
yield next;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/editable.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../services/package');
|
||||
|
||||
// admin or module's maintainer can modified the module
|
||||
@@ -22,11 +8,11 @@ module.exports = function* editable(next) {
|
||||
var moduleName = this.params.name || this.params[0];
|
||||
if (username && moduleName) {
|
||||
if (this.user.isAdmin) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
var isMaintainer = yield* packageService.isMaintainer(moduleName, username);
|
||||
var isMaintainer = yield packageService.isMaintainer(moduleName, username);
|
||||
if (isMaintainer) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,8 +21,9 @@ module.exports = function* editable(next) {
|
||||
if (username) {
|
||||
message = username + ' ' + message;
|
||||
}
|
||||
message = '[forbidden] ' + message;
|
||||
this.body = {
|
||||
error: 'forbidden user',
|
||||
reason: message
|
||||
error: message,
|
||||
reason: message,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,28 +1,17 @@
|
||||
/**!
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../services/package');
|
||||
|
||||
module.exports = function* (next) {
|
||||
var name = this.params.name || this.params[0];
|
||||
var pkg = yield packageService.getLatestModule(name);
|
||||
if (pkg) {
|
||||
return yield* next;
|
||||
return yield next;
|
||||
}
|
||||
this.status = 404;
|
||||
const error = '[not_found] document not found';
|
||||
this.body = {
|
||||
error: 'not_found',
|
||||
reason: 'document not found'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,27 +1,13 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/limit.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../config');
|
||||
var limit = require('koa-limit');
|
||||
|
||||
var limitConfig = config.limit;
|
||||
|
||||
if (!limitConfig.enable) {
|
||||
module.exports = function *ignoreLimit(next) {
|
||||
yield *next;
|
||||
module.exports = function* ignoreLimit(next) {
|
||||
yield next;
|
||||
};
|
||||
} else {
|
||||
module.exports = limit(limitConfig);
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/*!
|
||||
* cnpmjs.org - middleware/login.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var http = require('http');
|
||||
|
||||
module.exports = function *login(next) {
|
||||
@@ -23,20 +9,22 @@ module.exports = function *login(next) {
|
||||
? status
|
||||
: 500;
|
||||
|
||||
const error = `[${this.user.error.name}] ${this.user.error.message}`;
|
||||
this.body = {
|
||||
error: this.user.error.name,
|
||||
reason: this.user.error.message
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.user.name) {
|
||||
this.status = 401;
|
||||
const error = '[unauthorized] Login first';
|
||||
this.body = {
|
||||
error: 'unauthorized',
|
||||
reason: 'Login first'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
yield *next;
|
||||
yield next;
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/opensearch.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var template = '<?xml version="1.0" encoding="UTF-8"?>\
|
||||
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">\
|
||||
<ShortName>CNPM</ShortName>\
|
||||
@@ -22,11 +8,13 @@ var template = '<?xml version="1.0" encoding="UTF-8"?>\
|
||||
<Url method="get" type="text/html" template="http://${host}/browse/keyword/{searchTerms}"/>\
|
||||
</OpenSearchDescription>';
|
||||
|
||||
module.exports = function *opensearch(next) {
|
||||
var config = require('../config');
|
||||
|
||||
module.exports = function* opensearch(next) {
|
||||
if (this.path === '/opensearch.xml') {
|
||||
this.type = 'text/xml';
|
||||
this.charset = 'utf-8';
|
||||
this.body = template.replace('${host}', this.host);
|
||||
this.body = template.replace('${host}', config.opensearch.host || this.host);
|
||||
}
|
||||
yield *next;
|
||||
yield next;
|
||||
};
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:middleware:proxy_to_npm');
|
||||
var config = require('../config');
|
||||
|
||||
@@ -11,40 +7,78 @@ module.exports = function (options) {
|
||||
var redirectUrl = config.sourceNpmRegistry;
|
||||
var proxyUrls = [
|
||||
// /:pkg, dont contains scoped package
|
||||
/^\/[\w\-\.]+$/,
|
||||
// /:pkg/:versionOrTag
|
||||
/^\/[\w\-\.]+(?:\/[\w\-\.]+)?$/,
|
||||
// /-/package/:pkg/dist-tags
|
||||
/^\/\-\/package\/[\w\-\.]+\/dist-tags/,
|
||||
];
|
||||
var scopedUrls = [
|
||||
// scoped package
|
||||
/^\/(@[\w\-\.]+)\/[\w\-\.]+(?:\/[\w\-\.]+)?$/,
|
||||
/^\/\-\/package\/(@[\w\-\.]+)\/[\w\-\.]+\/dist\-tags/,
|
||||
];
|
||||
if (options && options.isWeb) {
|
||||
redirectUrl = redirectUrl.replace('//registry.', '//');
|
||||
redirectUrl = config.sourceNpmWeb || redirectUrl.replace('//registry.', '//');
|
||||
proxyUrls = [
|
||||
// /package/:pkg
|
||||
/^\/package\/[\w\-\.]+$/,
|
||||
/^\/package\/[\w\-\.]+/,
|
||||
];
|
||||
scopedUrls = [
|
||||
// scoped package
|
||||
/^\/package\/(@[\w\-\.]+)\/[\w\-\.]+/,
|
||||
];
|
||||
}
|
||||
|
||||
return function* proxyToNpm(next) {
|
||||
if (config.syncModel !== 'none') {
|
||||
return yield next;
|
||||
}
|
||||
|
||||
// syncModel === none
|
||||
// only proxy read requests
|
||||
if (this.method !== 'GET' && this.method !== 'HEAD') {
|
||||
return yield next;
|
||||
}
|
||||
|
||||
var pathname = this.path;
|
||||
var match;
|
||||
for (var i = 0; i < proxyUrls.length; i++) {
|
||||
match = proxyUrls[i].test(pathname);
|
||||
if (match) {
|
||||
break;
|
||||
var pathname = decodeURIComponent(this.path);
|
||||
|
||||
var isScoped = false;
|
||||
var isPublichScoped = false;
|
||||
// check scoped name
|
||||
if (config.scopes && config.scopes.length > 0) {
|
||||
for (var i = 0; i < scopedUrls.length; i++) {
|
||||
const m = scopedUrls[i].exec(pathname);
|
||||
if (m) {
|
||||
isScoped = true;
|
||||
if (config.scopes.indexOf(m[1]) !== -1) {
|
||||
// internal scoped
|
||||
isPublichScoped = false;
|
||||
} else {
|
||||
isPublichScoped = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!match) {
|
||||
return yield next;
|
||||
|
||||
var isPublich = false;
|
||||
if (!isScoped) {
|
||||
for (var i = 0; i < proxyUrls.length; i++) {
|
||||
isPublich = proxyUrls[i].test(pathname);
|
||||
if (isPublich) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var url = redirectUrl + this.url;
|
||||
debug('proxy to %s', url);
|
||||
this.redirect(url);
|
||||
if (isPublich || isPublichScoped) {
|
||||
var url = redirectUrl + this.url;
|
||||
debug('proxy isPublich: %s, isPublichScoped: %s, package to %s',
|
||||
isPublich, isPublichScoped, url);
|
||||
this.redirect(url);
|
||||
return;
|
||||
}
|
||||
|
||||
yield next;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/publishable.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var packageService = require('../services/package');
|
||||
|
||||
var util = require('util');
|
||||
var config = require('../config');
|
||||
var debug = require('debug')('cnpmjs.org:middlewares/publishable');
|
||||
@@ -27,9 +19,10 @@ module.exports = function *publishable(next) {
|
||||
// private mode, normal user can't publish and unpublish
|
||||
if (config.enablePrivate) {
|
||||
this.status = 403;
|
||||
const error = '[no_perms] Private mode enable, only admin can publish this module';
|
||||
this.body = {
|
||||
error: 'no_perms',
|
||||
reason: 'Private mode enable, only admin can publish this module'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -44,6 +37,22 @@ module.exports = function *publishable(next) {
|
||||
return yield next;
|
||||
}
|
||||
|
||||
// check the package is already exists and is maintainer
|
||||
var result = yield packageService.authMaintainer(name, this.user.name);
|
||||
if (result.maintainers && result.maintainers.length) {
|
||||
if (result.isMaintainer) {
|
||||
return yield next;
|
||||
}
|
||||
this.status = 403;
|
||||
const error = '[forbidden] ' + this.user.name + ' not authorized to modify ' + name +
|
||||
', please contact maintainers: ' + result.maintainers.join(', ');
|
||||
this.body = {
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// scoped module
|
||||
if (name[0] === '@') {
|
||||
if (checkScope(name, this)) {
|
||||
@@ -70,9 +79,10 @@ function checkScope(name, ctx) {
|
||||
if (ctx.user.scopes.indexOf(scope) === -1) {
|
||||
debug('assert scope %s error', name);
|
||||
ctx.status = 400;
|
||||
const error = util.format('[invalid] scope %s not match legal scopes: %s', scope, ctx.user.scopes.join(', '));
|
||||
ctx.body = {
|
||||
error: 'invalid scope',
|
||||
reason: util.format('scope %s not match legal scopes: %s', scope, ctx.user.scopes.join(', '))
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return false;
|
||||
}
|
||||
@@ -87,15 +97,17 @@ function checkScope(name, ctx) {
|
||||
function assertNoneScope(name, ctx) {
|
||||
ctx.status = 403;
|
||||
if (ctx.user.scopes.length === 0) {
|
||||
const error = '[no_perms] can\'t publish non-scoped package, please set `config.scopes`';
|
||||
ctx.body = {
|
||||
error: 'no_perms',
|
||||
reason: 'can\'t publish non-scoped package, please set `config.scopes`'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const error = '[no_perms] only allow publish with ' + ctx.user.scopes.join(', ') + ' scope(s)';
|
||||
ctx.body = {
|
||||
error: 'no_perms',
|
||||
reason: 'only allow publish with ' + ctx.user.scopes.join(', ') + ' scope(s)'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/registry_not_found.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
module.exports = function* notFound(next) {
|
||||
yield* next;
|
||||
yield next;
|
||||
|
||||
if (this.status && this.status !== 404) {
|
||||
return;
|
||||
@@ -25,8 +11,9 @@ module.exports = function* notFound(next) {
|
||||
}
|
||||
|
||||
this.status = 404;
|
||||
const error = '[not_found] document not found';
|
||||
this.body = {
|
||||
error: 'not_found',
|
||||
reason: 'document not found'
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,22 +1,13 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/unpublishable.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com>
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
module.exports = function *unpublishable(next) {
|
||||
// only admin user can unpublish
|
||||
if (!this.user.isAdmin) {
|
||||
this.status = 403;
|
||||
const error = '[no_perms] Only administrators can unpublish module';
|
||||
this.body = {
|
||||
error: 'no_perms',
|
||||
reason: 'Only administrators can unpublish module',
|
||||
error,
|
||||
reason: error,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,9 @@
|
||||
/**!
|
||||
* cnpmjs.org - middleware/web_not_found.js
|
||||
*
|
||||
* Copyright(c) cnpmjs.org and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var debug = require('debug')('cnpmjs.org:middleware:web_not_found');
|
||||
|
||||
module.exports = function* notFound(next) {
|
||||
yield* next;
|
||||
yield next;
|
||||
|
||||
if (this.status && this.status !== 404) {
|
||||
return;
|
||||
@@ -46,7 +32,7 @@ module.exports = function* notFound(next) {
|
||||
}
|
||||
|
||||
this.status = 404;
|
||||
yield* this.render('404', {
|
||||
yield this.render('404', {
|
||||
title: title,
|
||||
name: name
|
||||
});
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - models/_module_maintainer_class_methods.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
/**
|
||||
* list all module names by user
|
||||
* @param {String} user
|
||||
@@ -134,7 +120,7 @@ exports.updateMaintainers = function* (name, users) {
|
||||
remove: []
|
||||
};
|
||||
}
|
||||
var exists = yield* this.listMaintainers(name);
|
||||
var exists = yield this.listMaintainers(name);
|
||||
|
||||
var addUsers = users.filter(function (username) {
|
||||
// add user which in `users` but do not in `exists`
|
||||
@@ -156,4 +142,3 @@ exports.updateMaintainers = function* (name, users) {
|
||||
remove: removeUsers
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
// `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
// `gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
// `gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
// `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
// `name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
// `date` int unsigned NOT NULL COMMENT 'YYYYMM format',
|
||||
// `d01` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '01 download count',
|
||||
// `d02` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '02 download count',
|
||||
@@ -52,14 +52,14 @@
|
||||
// `d30` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '30 download count',
|
||||
// `d31` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '31 download count',
|
||||
// PRIMARY KEY (`id`),
|
||||
// UNIQUE KEY `name_date` (`name`, `date`)
|
||||
// KEY `date` (`date`)
|
||||
// UNIQUE KEY `uk_name_date` (`name`, `date`),
|
||||
// KEY `idx_date` (`date`)
|
||||
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module download total info';
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('DownloadTotal', {
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
@@ -260,10 +260,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name', 'date']
|
||||
fields: ['name', 'date'],
|
||||
},
|
||||
{
|
||||
fields: ['date']
|
||||
fields: ['date'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -1,24 +1,16 @@
|
||||
/**!
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var path = require('path');
|
||||
var config = require('../config');
|
||||
var sequelize = require('../common/sequelize');
|
||||
|
||||
function load(name) {
|
||||
return sequelize.import(path.join(__dirname, name));
|
||||
}
|
||||
|
||||
var _ModuleAbbreviated = config.enableAbbreviatedMetadata ? load('module_abbreviated') : null;
|
||||
var _PackageReadme = config.enableAbbreviatedMetadata ? load('package_readme') : null;
|
||||
|
||||
module.exports = {
|
||||
sequelize: sequelize,
|
||||
Module: load('module'),
|
||||
@@ -44,7 +36,27 @@ module.exports = {
|
||||
return data[1];
|
||||
},
|
||||
queryOne: function* (sql, args) {
|
||||
var rows = yield* this.query(sql, args);
|
||||
var rows = yield this.query(sql, args);
|
||||
return rows && rows[0];
|
||||
}
|
||||
},
|
||||
|
||||
get ModuleAbbreviated() {
|
||||
if (!config.enableAbbreviatedMetadata) {
|
||||
return null;
|
||||
}
|
||||
if (!_ModuleAbbreviated) {
|
||||
_ModuleAbbreviated = load('module_abbreviated');
|
||||
}
|
||||
return _ModuleAbbreviated;
|
||||
},
|
||||
|
||||
get PackageReadme() {
|
||||
if (!config.enableAbbreviatedMetadata) {
|
||||
return null;
|
||||
}
|
||||
if (!_PackageReadme) {
|
||||
_PackageReadme = load('package_readme');
|
||||
}
|
||||
return _PackageReadme;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - models/init_script.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../config');
|
||||
|
||||
config.database.logging = console.log;
|
||||
|
||||
@@ -16,26 +16,24 @@
|
||||
|
||||
/*
|
||||
CREATE TABLE IF NOT EXISTS `module` (
|
||||
`id` INTEGER NOT NULL auto_increment ,
|
||||
`author` VARCHAR(100) NOT NULL,
|
||||
`name` VARCHAR(100) NOT NULL,
|
||||
`version` VARCHAR(30) NOT NULL,
|
||||
`description` LONGTEXT,
|
||||
`package` LONGTEXT,
|
||||
`dist_shasum` VARCHAR(100),
|
||||
`dist_tarball` VARCHAR(2048),
|
||||
`dist_size` INTEGER UNSIGNED NOT NULL DEFAULT 0,
|
||||
`publish_time` BIGINT(20) UNSIGNED,
|
||||
`gmt_create` DATETIME NOT NULL,
|
||||
`gmt_modified` DATETIME NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
)
|
||||
COMMENT 'module info' ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
|
||||
|
||||
CREATE UNIQUE INDEX `module_name_version` ON `module` (`name`, `version`);
|
||||
CREATE INDEX `module_gmt_modified` ON `module` (`gmt_modified`);
|
||||
CREATE INDEX `module_publish_time` ON `module` (`publish_time`);
|
||||
CREATE INDEX `module_author` ON `module` (`author`);
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`author` varchar(100) NOT NULL COMMENT 'module author',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`description` longtext COMMENT 'module description',
|
||||
`package` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'package.json',
|
||||
`dist_shasum` varchar(100) DEFAULT NULL COMMENT 'module dist SHASUM',
|
||||
`dist_tarball` varchar(2048) DEFAULT NULL COMMENT 'module dist tarball',
|
||||
`dist_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'module dist size',
|
||||
`publish_time` bigint(20) unsigned COMMENT 'module publish time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_name` (`name`,`version`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`),
|
||||
KEY `idx_publish_time` (`publish_time`),
|
||||
KEY `idx_author` (`author`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module info';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
@@ -46,7 +44,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
comment: 'first maintainer name'
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name'
|
||||
},
|
||||
@@ -57,6 +55,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
comment: 'module description',
|
||||
},
|
||||
package: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
@@ -65,19 +64,23 @@ module.exports = function (sequelize, DataTypes) {
|
||||
dist_shasum: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: true,
|
||||
comment: 'module dist SHASUM',
|
||||
},
|
||||
dist_tarball: {
|
||||
type: DataTypes.STRING(2048),
|
||||
allowNull: true,
|
||||
comment: 'module dist tarball',
|
||||
},
|
||||
dist_size: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: 'module dist size',
|
||||
},
|
||||
publish_time: {
|
||||
type: DataTypes.BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: 'module publish time',
|
||||
}
|
||||
}, {
|
||||
tableName: 'module',
|
||||
@@ -85,16 +88,16 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name', 'version']
|
||||
fields: ['name', 'version'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified']
|
||||
fields: ['gmt_modified'],
|
||||
},
|
||||
{
|
||||
fields: ['publish_time']
|
||||
fields: ['publish_time'],
|
||||
},
|
||||
{
|
||||
fields: ['author']
|
||||
fields: ['author'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
63
models/module_abbreviated.js
Normal file
63
models/module_abbreviated.js
Normal file
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
/*
|
||||
CREATE TABLE IF NOT EXISTS `module_abbreviated` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`package` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'the abbreviated metadata',
|
||||
`publish_time` bigint(20) unsigned COMMENT 'the publish time',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_name` (`name`,`version`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`),
|
||||
KEY `idx_publish_time` (`publish_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module abbreviated info';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('ModuleAbbreviated', {
|
||||
name: {
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name'
|
||||
},
|
||||
version: {
|
||||
type: DataTypes.STRING(30),
|
||||
allowNull: false,
|
||||
comment: 'module version'
|
||||
},
|
||||
package: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
comment: 'package.json',
|
||||
},
|
||||
publish_time: {
|
||||
type: DataTypes.BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: 'the publish time',
|
||||
}
|
||||
}, {
|
||||
tableName: 'module_abbreviated',
|
||||
comment: 'module abbreviated info',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name', 'version'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified'],
|
||||
},
|
||||
{
|
||||
fields: ['publish_time'],
|
||||
},
|
||||
],
|
||||
classMethods: {
|
||||
findByNameAndVersion: function* (name, version) {
|
||||
return yield this.find({
|
||||
where: { name: name, version: version }
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -18,18 +18,18 @@
|
||||
CREATE TABLE IF NOT EXISTS `module_deps` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`deps` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '`name` is deped by `deps`',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`deps` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'which module depend on this module',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `module_deps_name_deps` (`name`,`deps`),
|
||||
KEY `deps` (`module_deps_deps`)
|
||||
UNIQUE KEY `uk_name_deps` (`name`,`deps`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module deps';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('ModuleDependency', {
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
@@ -46,10 +46,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name', 'deps']
|
||||
fields: ['name', 'deps'],
|
||||
},
|
||||
{
|
||||
fields: ['deps']
|
||||
fields: ['deps'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -19,11 +19,11 @@ CREATE TABLE IF NOT EXISTS `module_keyword` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`keyword` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'keyword',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`description` longtext,
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`description` longtext COMMENT 'module description',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `keyword_module_name` (`keyword`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_keyword_module_name` (`keyword`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module keyword';
|
||||
*/
|
||||
|
||||
@@ -32,15 +32,17 @@ module.exports = function (sequelize, DataTypes) {
|
||||
keyword: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: false,
|
||||
comment: 'keyword',
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
allowNull: true,
|
||||
comment: 'module description',
|
||||
}
|
||||
}, {
|
||||
tableName: 'module_keyword',
|
||||
@@ -49,10 +51,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['keyword', 'name']
|
||||
fields: ['keyword', 'name'],
|
||||
},
|
||||
{
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -15,15 +15,15 @@
|
||||
*/
|
||||
|
||||
/*
|
||||
CREATE TABLE IF NOT EXISTS `module_log` (
|
||||
CREATE TABLE IF NOT EXISTS `module_log` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`username` varchar(100) NOT NULL,
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`log` longtext,
|
||||
`username` varchar(100) NOT NULL COMMENT 'which username',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`log` longtext COMMENT 'the raw log',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `module_log_name` (`name`)
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module sync log';
|
||||
*/
|
||||
|
||||
@@ -35,19 +35,20 @@ module.exports = function (sequelize, DataTypes) {
|
||||
comment: 'user name'
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
log: {
|
||||
type: DataTypes.LONGTEXT
|
||||
type: DataTypes.LONGTEXT,
|
||||
comment: 'the raw log',
|
||||
}
|
||||
}, {
|
||||
tableName: 'module_log',
|
||||
comment: 'module sync log',
|
||||
indexes: [
|
||||
{
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -19,10 +19,10 @@ CREATE TABLE IF NOT EXISTS `module_maintainer` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `module_maintainer_user_name` (`user`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='private module maintainers';
|
||||
*/
|
||||
|
||||
@@ -34,7 +34,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
comment: 'user name'
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
}
|
||||
@@ -45,10 +45,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['user', 'name']
|
||||
fields: ['user', 'name'],
|
||||
},
|
||||
{
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
}
|
||||
],
|
||||
classMethods: require('./_module_maintainer_class_methods'),
|
||||
|
||||
@@ -19,10 +19,10 @@ CREATE TABLE IF NOT EXISTS `module_star` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `module_star_user_name` (`user`,`name`),
|
||||
KEY `module_star_name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module star';
|
||||
*/
|
||||
|
||||
@@ -34,7 +34,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
comment: 'user name'
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
}
|
||||
@@ -45,10 +45,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['user', 'name']
|
||||
fields: ['user', 'name'],
|
||||
},
|
||||
{
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -21,18 +21,18 @@ CREATE TABLE IF NOT EXISTS `module_unpublished` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`package` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'base info: tags, time, maintainers, description, versions',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `module_unpublished_name` (`name`),
|
||||
KEY `module_unpublished_gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module unpublished info';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('ModuleUnpublished', {
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
@@ -48,10 +48,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified']
|
||||
fields: ['gmt_modified'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -19,10 +19,10 @@ CREATE TABLE IF NOT EXISTS `npm_module_maintainer` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`user` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `npm_module_maintainer_user_name` (`user`,`name`),
|
||||
KEY `name` (`name`)
|
||||
UNIQUE KEY `uk_user_module_name` (`user`,`name`),
|
||||
KEY `idx_name` (`name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='npm original module maintainers';
|
||||
*/
|
||||
|
||||
@@ -34,7 +34,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
comment: 'user name'
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
}
|
||||
@@ -45,10 +45,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['user', 'name']
|
||||
fields: ['user', 'name'],
|
||||
},
|
||||
{
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
}
|
||||
],
|
||||
classMethods: require('./_module_maintainer_class_methods'),
|
||||
|
||||
53
models/package_readme.js
Normal file
53
models/package_readme.js
Normal file
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/*
|
||||
CREATE TABLE IF NOT EXISTS `package_readme` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`readme` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'the latest version readme',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='package latest readme';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('PackageReadme', {
|
||||
name: {
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name'
|
||||
},
|
||||
version: {
|
||||
type: DataTypes.STRING(30),
|
||||
allowNull: false,
|
||||
comment: 'module latest version'
|
||||
},
|
||||
readme: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
comment: 'latest version readme',
|
||||
},
|
||||
}, {
|
||||
tableName: 'package_readme',
|
||||
comment: 'package latest readme',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified'],
|
||||
},
|
||||
],
|
||||
classMethods: {
|
||||
findByName: function* (name) {
|
||||
return yield this.find({
|
||||
where: { name: name },
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -19,20 +19,20 @@ CREATE TABLE IF NOT EXISTS `tag` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key',
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`name` varchar(214) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'module name',
|
||||
`tag` varchar(30) NOT NULL COMMENT 'tag name',
|
||||
`version` varchar(30) NOT NULL COMMENT 'module version',
|
||||
`module_id` bigint(20) unsigned NOT NULL COMMENT 'module id',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `tag_name_tag` (`name`, `tag`),
|
||||
KEY `tag_gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`, `tag`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='module tag';
|
||||
*/
|
||||
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('Tag', {
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
allowNull: false,
|
||||
comment: 'module name',
|
||||
},
|
||||
@@ -57,10 +57,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name', 'tag']
|
||||
fields: ['name', 'tag'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified']
|
||||
fields: ['gmt_modified'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
|
||||
// CREATE TABLE IF NOT EXISTS `total` (
|
||||
// `name` varchar(100) NOT NULL COMMENT 'total name',
|
||||
// `name` varchar(214) NOT NULL COMMENT 'total name',
|
||||
// `gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
// `module_delete` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'module delete count',
|
||||
// `last_sync_time` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'last timestamp sync from official registry',
|
||||
@@ -35,7 +35,7 @@
|
||||
module.exports = function (sequelize, DataTypes) {
|
||||
return sequelize.define('Total', {
|
||||
name: {
|
||||
type: DataTypes.STRING(100),
|
||||
type: DataTypes.STRING(214),
|
||||
primaryKey: true,
|
||||
comment: 'total name'
|
||||
},
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - models/user.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utility = require('utility');
|
||||
var utils = require('./utils');
|
||||
|
||||
@@ -23,17 +9,17 @@ CREATE TABLE IF NOT EXISTS `user` (
|
||||
`gmt_create` datetime NOT NULL COMMENT 'create time',
|
||||
`gmt_modified` datetime NOT NULL COMMENT 'modified time',
|
||||
`name` varchar(100) NOT NULL COMMENT 'user name',
|
||||
`salt` varchar(100) NOT NULL,
|
||||
`salt` varchar(100) NOT NULL COMMENT 'user salt',
|
||||
`password_sha` varchar(100) NOT NULL COMMENT 'user password hash',
|
||||
`ip` varchar(64) NOT NULL COMMENT 'user last request ip',
|
||||
`roles` varchar(200) NOT NULL DEFAULT '[]',
|
||||
`rev` varchar(40) NOT NULL,
|
||||
`email` varchar(400) NOT NULL,
|
||||
`json` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT 'json details',
|
||||
`roles` varchar(200) NOT NULL DEFAULT '[]' COMMENT 'user roles',
|
||||
`rev` varchar(40) NOT NULL COMMENT 'user rev',
|
||||
`email` varchar(400) NOT NULL COMMENT 'user email',
|
||||
`json` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT 'json details',
|
||||
`npm_user` tinyint(1) DEFAULT '0' COMMENT 'user sync from npm or not, 1: true, other: false',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `user_name` (`name`),
|
||||
KEY `user_gmt_modified` (`gmt_modified`)
|
||||
UNIQUE KEY `uk_name` (`name`),
|
||||
KEY `idx_gmt_modified` (`gmt_modified`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='user base info';
|
||||
*/
|
||||
|
||||
@@ -47,6 +33,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
salt: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: false,
|
||||
comment: 'user salt',
|
||||
},
|
||||
password_sha: {
|
||||
type: DataTypes.STRING(100),
|
||||
@@ -62,14 +49,17 @@ module.exports = function (sequelize, DataTypes) {
|
||||
type: DataTypes.STRING(200),
|
||||
allowNull: false,
|
||||
defaultValue: '[]',
|
||||
comment: 'user roles',
|
||||
},
|
||||
rev: {
|
||||
type: DataTypes.STRING(40),
|
||||
allowNull: false,
|
||||
comment: 'user rev',
|
||||
},
|
||||
email: {
|
||||
type: DataTypes.STRING(400),
|
||||
allowNull: false,
|
||||
comment: 'user email',
|
||||
},
|
||||
json: {
|
||||
type: DataTypes.LONGTEXT,
|
||||
@@ -90,10 +80,10 @@ module.exports = function (sequelize, DataTypes) {
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: ['name']
|
||||
fields: ['name'],
|
||||
},
|
||||
{
|
||||
fields: ['gmt_modified']
|
||||
fields: ['gmt_modified'],
|
||||
}
|
||||
],
|
||||
classMethods: {
|
||||
@@ -104,7 +94,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
|
||||
// read
|
||||
auth: function* (name, password) {
|
||||
var user = yield* this.findByName(name);
|
||||
var user = yield this.findByName(name);
|
||||
if (user) {
|
||||
var sha = this.createPasswordSha(password, user.salt);
|
||||
if (user.password_sha !== sha) {
|
||||
@@ -141,7 +131,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
|
||||
// write
|
||||
saveNpmUser: function* (data) {
|
||||
var user = yield* this.findByName(data.name);
|
||||
var user = yield this.findByName(data.name);
|
||||
if (!user) {
|
||||
user = this.build({
|
||||
isNpmUser: true,
|
||||
@@ -162,7 +152,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
},
|
||||
saveCustomUser: function* (data) {
|
||||
var name = data.user.login;
|
||||
var user = yield* this.findByName(name);
|
||||
var user = yield this.findByName(name);
|
||||
if (!user) {
|
||||
user = this.build({
|
||||
isNpmUser: false,
|
||||
@@ -230,7 +220,7 @@ module.exports = function (sequelize, DataTypes) {
|
||||
roles = '[]';
|
||||
}
|
||||
|
||||
var row = yield* this.findByName(user.name);
|
||||
var row = yield this.findByName(user.name);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
87
package.json
87
package.json
@@ -1,79 +1,93 @@
|
||||
{
|
||||
"name": "cnpmjs.org",
|
||||
"version": "2.19.2",
|
||||
"version": "3.0.0-rc.29",
|
||||
"description": "Private npm registry and web for Enterprise, base on MySQL and Simple Store Service",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "DEBUG=cnpm* node dispatch.js",
|
||||
"test": "make jshint && make test",
|
||||
"test-local": "make test",
|
||||
"start": "./bin/nodejsctl start && cp History.md docs/web/history.md",
|
||||
"status": "./bin/nodejsctl status",
|
||||
"stop": "./bin/nodejsctl stop"
|
||||
"stop": "./bin/nodejsctl stop",
|
||||
"snyk-protect": "snyk protect",
|
||||
"prepublish": "npm run snyk-protect"
|
||||
},
|
||||
"bin": {
|
||||
"cnpmjs.org": "bin/cli.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"agentkeepalive": "^2.2.0",
|
||||
"await-event": "^1.0.0",
|
||||
"bytes": "^2.4.0",
|
||||
"cfork": "^1.5.1",
|
||||
"agentkeepalive": "^4.0.0",
|
||||
"await-event": "^2.1.0",
|
||||
"bytes": "^2.5.0",
|
||||
"cfork": "^1.6.1",
|
||||
"changes-stream": "^1.1.0",
|
||||
"co": "^4.6.0",
|
||||
"co-defer": "^1.0.0",
|
||||
"co-gather": "^0.0.1",
|
||||
"co-sleep": "^0.0.1",
|
||||
"commander": "^2.9.0",
|
||||
"co-gather": "~0.0.1",
|
||||
"co-sleep": "~0.0.1",
|
||||
"commander": "^2.11.0",
|
||||
"copy-to": "^2.0.1",
|
||||
"debug": "^2.2.0",
|
||||
"debug": "^3.0.0",
|
||||
"error-formater": "^1.0.3",
|
||||
"fs-cnpm": "^1.2.0",
|
||||
"giturl": "^1.0.0",
|
||||
"graceful": "^1.0.0",
|
||||
"gravatar": "^1.5.0",
|
||||
"humanize-ms": "^1.2.0",
|
||||
"humanize-number": "^0.0.2",
|
||||
"is-type-of": "^1.0.0",
|
||||
"graceful": "^1.0.1",
|
||||
"gravatar": "^1.6.0",
|
||||
"he": "^1.2.0",
|
||||
"humanize-ms": "^1.2.1",
|
||||
"humanize-number": "~0.0.2",
|
||||
"ioredis": "^4.6.2",
|
||||
"is-type-of": "^1.2.0",
|
||||
"kcors": "^1.2.1",
|
||||
"koa": "^1.2.0",
|
||||
"koa-bodyparser": "^2.5.0",
|
||||
"koa-conditional-get": "^1.0.4",
|
||||
"koa-etag": "^2.1.2",
|
||||
"koa-limit": "^1.0.2",
|
||||
"koa-markdown": "^2.0.1",
|
||||
"koa-markdown": "^2.0.2",
|
||||
"koa-maxrequests": "^1.0.0",
|
||||
"koa-middlewares": "^2.1.0",
|
||||
"koa-mock": "^1.6.1",
|
||||
"koa-mock": "^1.6.2",
|
||||
"koa-proxy": "^0.9.0",
|
||||
"koa-rewrite": "^1.1.2",
|
||||
"koa-rt": "^1.0.0",
|
||||
"koa-safe-jsonp": "^0.3.1",
|
||||
"markdown-it": "^3.0.6",
|
||||
"mime": "^1.3.4",
|
||||
"mini-logger": "^1.1.1",
|
||||
"mkdirp": "^0.5.0",
|
||||
"moment": "^2.12.0",
|
||||
"mysql": "^2.10.2",
|
||||
"mz": "^2.4.0",
|
||||
"markdown-it": "^8.3.2",
|
||||
"mime": "^1.3.6",
|
||||
"mini-logger": "^1.1.3",
|
||||
"mkdirp": "^0.5.1",
|
||||
"moment": "^2.18.1",
|
||||
"mysql": "^2.14.1",
|
||||
"mz": "^2.6.0",
|
||||
"nodemailer": "^1.3.0",
|
||||
"normalize-registry-metadata": "^1.1.2",
|
||||
"semver": "^5.2.0",
|
||||
"rimraf": "^2.6.2",
|
||||
"semver": "^5.4.1",
|
||||
"sequelize": "^3.23.4",
|
||||
"thunkify-wrap": "^1.0.4",
|
||||
"treekill": "^1.0.0",
|
||||
"tunnel-agent": "^0.4.0",
|
||||
"urllib": "^2.11.0",
|
||||
"utility": "^1.8.0",
|
||||
"xss": "^0.2.13"
|
||||
"tunnel-agent": "^0.6.0",
|
||||
"urllib": "^2.24.0",
|
||||
"utility": "^1.12.0",
|
||||
"xss": "^0.3.3",
|
||||
"snyk": "^1.231.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autod": "*",
|
||||
"chunkstream": "*",
|
||||
"contributors": "*",
|
||||
"intelli-espower-loader": "^1.0.1",
|
||||
"istanbul": "*",
|
||||
"jshint": "*",
|
||||
"mm": "*",
|
||||
"mocha": "*",
|
||||
"mocha": "3",
|
||||
"node-dev": "*",
|
||||
"pedding": "*",
|
||||
"pg": "5",
|
||||
"pg-hstore": "2",
|
||||
"power-assert": "^1.4.2",
|
||||
"should": "8",
|
||||
"should-http": "*",
|
||||
"sqlite3": "*",
|
||||
"supertest": "2",
|
||||
"thunk-mocha": "1"
|
||||
@@ -85,8 +99,10 @@
|
||||
"web": "https://github.com/cnpm/cnpmjs.org"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cnpm/cnpmjs.org/issues",
|
||||
"email": "fengmk2@gmail.com"
|
||||
"url": "https://github.com/cnpm/cnpmjs.org/issues"
|
||||
},
|
||||
"publishConfig": {
|
||||
"tag": "latest-3"
|
||||
},
|
||||
"keywords": [
|
||||
"cnpmjs.org",
|
||||
@@ -96,11 +112,12 @@
|
||||
"registry"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 4.3.1"
|
||||
"node": ">= 8.0.0"
|
||||
},
|
||||
"author": [
|
||||
"fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)",
|
||||
"dead_horse <dead_horse@qq.com> (http://deadhorse.me)"
|
||||
],
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"snyk": true
|
||||
}
|
||||
|
||||
@@ -24,26 +24,28 @@ $(function () {
|
||||
$('#node-version').html(data.node_version || 'v0.10.22');
|
||||
$('#app-version').html(data.app_version || '0.0.0');
|
||||
|
||||
if (data.sync_model === 'all') {
|
||||
$('#sync-model').html('This registry will sync all packages from official registry.');
|
||||
$('#last-sync-time').html(new Date(data.last_sync_time));
|
||||
} else if (data.sync_model === 'exist') {
|
||||
$('#sync-model').html('This registry will only update exist packages from official registry.');
|
||||
$('#last-sync-time').html(new Date(data.last_exist_sync_time));
|
||||
if (data.sync_model !== 'none') {
|
||||
if (data.sync_model === 'all') {
|
||||
$('#sync-model').html('This registry will sync all packages from official registry.');
|
||||
$('#last-sync-time').html(new Date(data.last_sync_time));
|
||||
} else if (data.sync_model === 'exist') {
|
||||
$('#sync-model').html('This registry will only update exist packages from official registry.');
|
||||
$('#last-sync-time').html(new Date(data.last_exist_sync_time));
|
||||
}
|
||||
|
||||
$('#need-sync').html(data.need_sync_num);
|
||||
$('#success-sync').html(data.success_sync_num);
|
||||
$('#fail-sync').html(data.fail_sync_num);
|
||||
$('#left-sync').html(data.left_sync_num);
|
||||
$('#percent-sync').html(Math.floor(data.success_sync_num / data.need_sync_num * 100));
|
||||
$('#last-success-name').html('<a target="_blank" href="/package/' + data.last_sync_module + '">' +
|
||||
data.last_sync_module + '</a>');
|
||||
|
||||
if (!data.sync_status) {
|
||||
$('.syncing').remove();
|
||||
}
|
||||
|
||||
$('.sync').show();
|
||||
}
|
||||
|
||||
$('#need-sync').html(data.need_sync_num);
|
||||
$('#success-sync').html(data.success_sync_num);
|
||||
$('#fail-sync').html(data.fail_sync_num);
|
||||
$('#left-sync').html(data.left_sync_num);
|
||||
$('#percent-sync').html(Math.floor(data.success_sync_num / data.need_sync_num * 100));
|
||||
$('#last-success-name').html('<a target="_blank" href="/package/' + data.last_sync_module + '">' +
|
||||
data.last_sync_module + '</a>');
|
||||
|
||||
if (!data.sync_status) {
|
||||
$('.syncing').remove();
|
||||
}
|
||||
|
||||
$('.sync').show();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ var tags = require('../controllers/registry/package/dist_tag');
|
||||
function routes(app) {
|
||||
|
||||
function* jsonp(next) {
|
||||
yield* next;
|
||||
yield next;
|
||||
if (this.body) {
|
||||
this.jsonp = this.body;
|
||||
}
|
||||
|
||||
@@ -16,9 +16,11 @@ function routes(app) {
|
||||
// scope package without version
|
||||
app.get(/\/package\/(@[\w\-\.]+\/[\w\-\.]+)$/, showPackage);
|
||||
// scope package with version
|
||||
app.get(/\/package\/(@[\w\-\.]+\/[\w\-\.]+)\/([\w\d\.]+)$/, showPackage);
|
||||
app.get(/\/package\/(@[\w\-\.]+\/[\w\-\.]+)\/([\w\-\d\.]+)$/, showPackage);
|
||||
app.get(/\/package\/(@[\w\-\.]+\/[\w\-\.]+)\/v\/([\w\-\d\.]+)$/, showPackage);
|
||||
app.get('/package/:name', showPackage);
|
||||
app.get('/package/:name/:version', showPackage);
|
||||
app.get('/package/:name/v/:version', showPackage);
|
||||
|
||||
app.get('/privates', listPrivates);
|
||||
|
||||
|
||||
@@ -4,6 +4,11 @@ var koa = require('koa');
|
||||
var app = module.exports = koa();
|
||||
var http = require('http');
|
||||
var middlewares = require('koa-middlewares');
|
||||
var bodyParser = require('koa-bodyparser');
|
||||
var rt = require('koa-rt');
|
||||
var rewrite = require('koa-rewrite');
|
||||
var conditional = require('koa-conditional-get');
|
||||
var etag = require('koa-etag');
|
||||
var routes = require('../routes/registry');
|
||||
var logger = require('../common/logger');
|
||||
var config = require('../config');
|
||||
@@ -15,28 +20,41 @@ var cors = require('kcors');
|
||||
var proxyToNpm = require('../middleware/proxy_to_npm');
|
||||
var maxrequests = require('koa-maxrequests');
|
||||
|
||||
if (config.enableNpmAuditsProxy) {
|
||||
var proxy = require('koa-proxy');
|
||||
app.use(proxy({
|
||||
host: 'https://registry.npmjs.org',
|
||||
match: /^\/\-\/npm\/v1\/security\/audits/
|
||||
}));
|
||||
}
|
||||
|
||||
app.use(maxrequests());
|
||||
app.use(block());
|
||||
middlewares.jsonp(app);
|
||||
app.use(middlewares.rt({ headerName: 'X-ReadTime' }));
|
||||
app.use(middlewares.rewrite('/favicon.ico', '/favicon.png'));
|
||||
app.use(rt({ headerName: 'X-ReadTime' }));
|
||||
app.use(rewrite('/favicon.ico', '/favicon.png'));
|
||||
app.use(staticCache);
|
||||
|
||||
app.keys = ['todokey', config.sessionSecret];
|
||||
app.proxy = true;
|
||||
app.use(middlewares.bodyParser({ jsonLimit: config.jsonLimit }));
|
||||
app.use(bodyParser({ jsonLimit: config.jsonLimit, strict: false }));
|
||||
app.use(cors({
|
||||
allowMethods: 'GET,HEAD',
|
||||
}));
|
||||
app.use(auth());
|
||||
app.use(proxyToNpm());
|
||||
app.use(notFound);
|
||||
|
||||
if (config.enableCompress) {
|
||||
app.use(middlewares.compress({ threshold: 150 }));
|
||||
}
|
||||
app.use(middlewares.conditional());
|
||||
app.use(middlewares.etag());
|
||||
app.use(notFound);
|
||||
|
||||
app.use(conditional());
|
||||
app.use(etag());
|
||||
|
||||
for (const middleware of config.customRegistryMiddlewares) {
|
||||
app.use(middleware(app));
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes
|
||||
@@ -56,10 +74,10 @@ app.on('error', function (err, ctx) {
|
||||
logger.error(err);
|
||||
});
|
||||
|
||||
app = http.createServer(app.callback());
|
||||
const server = http.createServer(app.callback());
|
||||
|
||||
if (!module.parent) {
|
||||
app.listen(config.registryPort);
|
||||
server.listen(config.registryPort);
|
||||
}
|
||||
|
||||
module.exports = app;
|
||||
module.exports = server;
|
||||
|
||||
@@ -4,6 +4,11 @@ var opensearch = require('../middleware/opensearch');
|
||||
var notFound = require('../middleware/web_not_found');
|
||||
var staticCache = require('../middleware/static');
|
||||
var middlewares = require('koa-middlewares');
|
||||
var bodyParser = require('koa-bodyparser');
|
||||
var rt = require('koa-rt');
|
||||
var rewrite = require('koa-rewrite');
|
||||
var conditional = require('koa-conditional-get');
|
||||
var etag = require('koa-etag');
|
||||
var markdownMiddleware = require('koa-markdown');
|
||||
var block = require('../middleware/block');
|
||||
var logger = require('../common/logger');
|
||||
@@ -27,8 +32,8 @@ var rootdir = path.dirname(__dirname);
|
||||
|
||||
app.use(maxrequests());
|
||||
app.use(block());
|
||||
app.use(middlewares.rt({headerName: 'X-ReadTime'}));
|
||||
app.use(middlewares.rewrite('/favicon.ico', '/favicon.png'));
|
||||
app.use(rt({ headerName: 'X-ReadTime' }));
|
||||
app.use(rewrite('/favicon.ico', '/favicon.png'));
|
||||
app.use(staticCache);
|
||||
|
||||
if (config.pagemock) {
|
||||
@@ -43,7 +48,7 @@ app.proxy = true;
|
||||
app.use(proxyToNpm({
|
||||
isWeb: true
|
||||
}));
|
||||
app.use(middlewares.bodyParser());
|
||||
app.use(bodyParser({ jsonLimit: config.jsonLimit, strict: false }));
|
||||
app.use(auth());
|
||||
app.use(notFound);
|
||||
|
||||
@@ -51,10 +56,10 @@ if (config.enableCompress) {
|
||||
app.use(middlewares.compress({threshold: 150}));
|
||||
}
|
||||
|
||||
app.use(middlewares.conditional());
|
||||
app.use(middlewares.etag());
|
||||
app.use(conditional());
|
||||
app.use(etag());
|
||||
|
||||
var viewDir = path.join(rootdir, 'view', 'web');
|
||||
var viewDir = config.viewDir || path.join(rootdir, 'view', 'web');
|
||||
var docDir = path.join(rootdir, 'docs', 'web');
|
||||
|
||||
var layoutFile = path.join(viewDir, '_layout.html');
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - services/common.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../config');
|
||||
var isPrivateScopedPackage = require('../lib/common').isPrivateScopedPackage;
|
||||
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - services/default_user_service.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var gravatar = require('gravatar');
|
||||
// var User = require('../proxy/user');
|
||||
var User = require('../models').User;
|
||||
@@ -83,7 +69,7 @@ var proto = DefaultUserService.prototype;
|
||||
* @return {User}
|
||||
*/
|
||||
proto.auth = function* (login, password) {
|
||||
var row = yield* User.auth(login, password);
|
||||
var row = yield User.auth(login, password);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
@@ -109,7 +95,7 @@ proto.get = function* (login) {
|
||||
* @return {Array<User>}
|
||||
*/
|
||||
proto.list = function* (logins) {
|
||||
var rows = yield* User.listByNames(logins);
|
||||
var rows = yield User.listByNames(logins);
|
||||
var users = [];
|
||||
rows.forEach(function (row) {
|
||||
users.push(convertToUser(row));
|
||||
@@ -131,7 +117,7 @@ proto.search = function* (query, options) {
|
||||
options.limit = 20;
|
||||
}
|
||||
|
||||
var rows = yield* User.search(query, options);
|
||||
var rows = yield User.search(query, options);
|
||||
var users = [];
|
||||
rows.forEach(function (row) {
|
||||
users.push(convertToUser(row));
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
/**!
|
||||
* Copyright(c) cnpm and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utility = require('utility');
|
||||
var config = require('../config');
|
||||
var models = require('../models');
|
||||
var DownloadTotal = require('../models').DownloadTotal;
|
||||
|
||||
exports.getModuleTotal = function* (name, start, end) {
|
||||
@@ -53,50 +43,36 @@ exports.getTotalByName = function* (name) {
|
||||
|
||||
exports.plusModuleTotal = function* (data) {
|
||||
var yearMonth = parseYearMonth(data.date);
|
||||
// all module download total
|
||||
var row = yield DownloadTotal.find({
|
||||
where: {
|
||||
name: '__all__',
|
||||
date: yearMonth
|
||||
name: data.name,
|
||||
date: yearMonth,
|
||||
}
|
||||
});
|
||||
if (!row) {
|
||||
row = DownloadTotal.build({
|
||||
name: '__all__',
|
||||
name: data.name,
|
||||
date: yearMonth,
|
||||
});
|
||||
}
|
||||
var field = 'd' + data.date.substring(8, 10);
|
||||
if (typeof row[field] === 'string') {
|
||||
// pg bigint is string...
|
||||
row[field] = utility.toSafeNumber(row[field]);
|
||||
}
|
||||
row[field] += data.count;
|
||||
if (row.changed()) {
|
||||
yield row.save();
|
||||
}
|
||||
|
||||
row = yield DownloadTotal.find({
|
||||
where: {
|
||||
name: data.name,
|
||||
date: yearMonth,
|
||||
}
|
||||
});
|
||||
if (!row) {
|
||||
row = DownloadTotal.build({
|
||||
name: data.name,
|
||||
date: yearMonth,
|
||||
});
|
||||
}
|
||||
var field = 'd' + data.date.substring(8, 10);
|
||||
if (typeof row[field] === 'string') {
|
||||
// pg bigint is string...
|
||||
row[field] = utility.toSafeNumber(row[field]);
|
||||
}
|
||||
row[field] += data.count;
|
||||
if (row.changed()) {
|
||||
return yield row.save();
|
||||
if (config.database.dialect === 'mysql') {
|
||||
// mysql update set field = field + count
|
||||
yield models.query(`UPDATE downloads SET ${field} = ${field} + ${data.count}, gmt_modified=? WHERE id = ?`,
|
||||
[ new Date(), row.id ]);
|
||||
} else {
|
||||
// pg
|
||||
if (typeof row[field] === 'string') {
|
||||
// pg bigint is string...
|
||||
row[field] = utility.toSafeNumber(row[field]);
|
||||
}
|
||||
row[field] += data.count;
|
||||
if (row.changed()) {
|
||||
return yield row.save();
|
||||
}
|
||||
}
|
||||
|
||||
return row;
|
||||
};
|
||||
|
||||
|
||||
19
services/hook.js
Normal file
19
services/hook.js
Normal file
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
const co = require('co');
|
||||
const config = require('../config');
|
||||
const logger = require('../common/logger');
|
||||
|
||||
exports.trigger = envelope => {
|
||||
if (!config.globalHook) {
|
||||
return;
|
||||
}
|
||||
|
||||
envelope.time = Date.now();
|
||||
|
||||
co(function* () {
|
||||
yield config.globalHook(envelope);
|
||||
}).catch(err => {
|
||||
logger.error(err);
|
||||
});
|
||||
};
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - services/module_log.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var models = require('../models');
|
||||
var ModuleLog = models.ModuleLog;
|
||||
|
||||
@@ -26,14 +12,14 @@ exports.create = function* (data) {
|
||||
return yield row.save();
|
||||
};
|
||||
|
||||
var ONE_MB = 1024 * 1024;
|
||||
|
||||
// 50kb
|
||||
var MAX_LEN = 50 * 1024;
|
||||
exports.append = function* (id, log) {
|
||||
if (!log) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var row = yield* exports.get(id);
|
||||
var row = yield exports.get(id);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
@@ -43,8 +29,9 @@ exports.append = function* (id, log) {
|
||||
} else {
|
||||
row.log = log;
|
||||
}
|
||||
if (row.log.length >= ONE_MB) {
|
||||
row.log = '...\n' + row.log.substring(ONE_MB / 2);
|
||||
if (row.log.length > MAX_LEN) {
|
||||
// only keep the fisrt 1kb and the last 50kb log string
|
||||
row.log = row.log.substring(0, 1024) + '\n... ignore long logs ...\n' + row.log.substring(row.log.length - MAX_LEN);
|
||||
}
|
||||
return yield row.save(['log']);
|
||||
};
|
||||
|
||||
@@ -11,9 +11,9 @@ function* request(url, options) {
|
||||
options = options || {};
|
||||
options.dataType = options.dataType || 'json';
|
||||
options.timeout = options.timeout || 120000;
|
||||
options.headers = {
|
||||
options.headers = Object.assign({
|
||||
'user-agent': USER_AGENT
|
||||
};
|
||||
}, options.headers);
|
||||
options.gzip = true;
|
||||
options.followRedirect = true;
|
||||
var registry = options.registry || config.sourceNpmRegistry;
|
||||
@@ -42,7 +42,7 @@ exports.request = request;
|
||||
|
||||
exports.getUser = function* (name) {
|
||||
var url = '/-/user/org.couchdb.user:' + name;
|
||||
var r = yield* request(url);
|
||||
var r = yield request(url);
|
||||
var data = r.data;
|
||||
if (data && !data.name) {
|
||||
// 404
|
||||
@@ -52,7 +52,7 @@ exports.getUser = function* (name) {
|
||||
};
|
||||
|
||||
exports.get = function* (name) {
|
||||
var r = yield* request('/' + name);
|
||||
var r = yield request('/' + name);
|
||||
var data = r.data;
|
||||
if (r.status === 404) {
|
||||
data = null;
|
||||
@@ -138,14 +138,14 @@ exports.fetchAllPackagesSince = function* (timestamp) {
|
||||
};
|
||||
|
||||
exports.getAllSince = function* (startkey, timeout) {
|
||||
var r = yield* request('/-/all/since?stale=update_after&startkey=' + startkey, {
|
||||
var r = yield request('/-/all/since?stale=update_after&startkey=' + startkey, {
|
||||
timeout: timeout || 300000
|
||||
});
|
||||
return r.data;
|
||||
};
|
||||
|
||||
exports.getAllToday = function* (timeout) {
|
||||
var r = yield* request('/-/all/static/today.json', {
|
||||
var r = yield request('/-/all/static/today.json', {
|
||||
timeout: timeout || 300000
|
||||
});
|
||||
// data is array: see https://registry.npmjs.org/-/all/static/today.json
|
||||
@@ -153,16 +153,28 @@ exports.getAllToday = function* (timeout) {
|
||||
};
|
||||
|
||||
exports.getShort = function* (timeout) {
|
||||
var r = yield* request('/-/short', {
|
||||
const registry = config.sourceNpmRegistryIsCNpm ? config.sourceNpmRegistry : 'https://r.cnpmjs.org';
|
||||
var r = yield request('/-/short', {
|
||||
timeout: timeout || 300000,
|
||||
// registry.npmjs.org/-/short is 404 now therefore have a fallback
|
||||
registry: config.sourceNpmRegistryIsCNpm ? config.sourceNpmRegistry : 'http://r.cnpmjs.org',
|
||||
registry: registry,
|
||||
});
|
||||
if (r.status !== 200) {
|
||||
const data = r.data;
|
||||
if (data && data.code && data.message) {
|
||||
// { code: 'MethodNotAllowedError', message: 'GET is not allowed' }
|
||||
const url = registry + '/-/short';
|
||||
const err = new Error(data.message + ', url: ' + url);
|
||||
err.name = data.code;
|
||||
err.url = url;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return r.data;
|
||||
};
|
||||
|
||||
exports.getPopular = function* (top, timeout) {
|
||||
var r = yield* request('/-/_view/dependedUpon?group_level=1', {
|
||||
var r = yield request('/-/_view/dependedUpon?group_level=1', {
|
||||
registry: config.officialNpmRegistry,
|
||||
timeout: timeout || 120000
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
var semver = require('semver');
|
||||
var models = require('../models');
|
||||
var common = require('./common');
|
||||
var config = require('../config');
|
||||
var Tag = models.Tag;
|
||||
var User = models.User;
|
||||
var Module = models.Module;
|
||||
@@ -49,17 +50,17 @@ exports.getModuleById = function* (id) {
|
||||
};
|
||||
|
||||
exports.getModule = function* (name, version) {
|
||||
var row = yield* Module.findByNameAndVersion(name, version);
|
||||
var row = yield Module.findByNameAndVersion(name, version);
|
||||
parseRow(row);
|
||||
return row;
|
||||
};
|
||||
|
||||
exports.getModuleByTag = function* (name, tag) {
|
||||
var tag = yield* Tag.findByNameAndTag(name, tag);
|
||||
var tag = yield Tag.findByNameAndTag(name, tag);
|
||||
if (!tag) {
|
||||
return null;
|
||||
}
|
||||
return yield* exports.getModule(tag.name, tag.version);
|
||||
return yield exports.getModule(tag.name, tag.version);
|
||||
};
|
||||
|
||||
exports.getModuleByRange = function* (name, range) {
|
||||
@@ -82,7 +83,7 @@ exports.getModuleByRange = function* (name, range) {
|
||||
};
|
||||
|
||||
exports.getLatestModule = function* (name) {
|
||||
return yield* exports.getModuleByTag(name, 'latest');
|
||||
return yield exports.getModuleByTag(name, 'latest');
|
||||
};
|
||||
|
||||
// module:list
|
||||
@@ -144,20 +145,20 @@ exports.listModules = function* (names) {
|
||||
};
|
||||
|
||||
exports.listModulesByUser = function* (username) {
|
||||
var names = yield* exports.listModuleNamesByUser(username);
|
||||
return yield* exports.listModules(names);
|
||||
var names = yield exports.listModuleNamesByUser(username);
|
||||
return yield exports.listModules(names);
|
||||
};
|
||||
|
||||
exports.listModuleNamesByUser = function* (username) {
|
||||
var sql = 'SELECT distinct(name) AS name FROM module WHERE author=?;';
|
||||
var rows = yield* models.query(sql, [username]);
|
||||
var rows = yield models.query(sql, [username]);
|
||||
var map = {};
|
||||
var names = rows.map(function (r) {
|
||||
return r.name;
|
||||
});
|
||||
|
||||
// find from npm module maintainer table
|
||||
var moduleNames = yield* NpmModuleMaintainer.listModuleNamesByUser(username);
|
||||
var moduleNames = yield NpmModuleMaintainer.listModuleNamesByUser(username);
|
||||
moduleNames.forEach(function (name) {
|
||||
if (!map[name]) {
|
||||
names.push(name);
|
||||
@@ -165,7 +166,7 @@ exports.listModuleNamesByUser = function* (username) {
|
||||
});
|
||||
|
||||
// find from private module maintainer table
|
||||
moduleNames = yield* PrivateModuleMaintainer.listModuleNamesByUser(username);
|
||||
moduleNames = yield PrivateModuleMaintainer.listModuleNamesByUser(username);
|
||||
moduleNames.forEach(function (name) {
|
||||
if (!map[name]) {
|
||||
names.push(name);
|
||||
@@ -175,14 +176,14 @@ exports.listModuleNamesByUser = function* (username) {
|
||||
};
|
||||
|
||||
exports.listPublicModulesByUser = function* (username) {
|
||||
var names = yield* exports.listPublicModuleNamesByUser(username);
|
||||
return yield* exports.listModules(names);
|
||||
var names = yield exports.listPublicModuleNamesByUser(username);
|
||||
return yield exports.listModules(names);
|
||||
};
|
||||
|
||||
// return user all public package names
|
||||
exports.listPublicModuleNamesByUser = function* (username) {
|
||||
var sql = 'SELECT distinct(name) AS name FROM module WHERE author=?;';
|
||||
var rows = yield* models.query(sql, [username]);
|
||||
var rows = yield models.query(sql, [username]);
|
||||
var map = {};
|
||||
var names = rows.map(function (r) {
|
||||
return r.name;
|
||||
@@ -195,7 +196,7 @@ exports.listPublicModuleNamesByUser = function* (username) {
|
||||
});
|
||||
|
||||
// find from npm module maintainer table
|
||||
var moduleNames = yield* NpmModuleMaintainer.listModuleNamesByUser(username);
|
||||
var moduleNames = yield NpmModuleMaintainer.listModuleNamesByUser(username);
|
||||
moduleNames.forEach(function (name) {
|
||||
if (!map[name]) {
|
||||
names.push(name);
|
||||
@@ -275,7 +276,7 @@ exports.saveModule = function* (mod) {
|
||||
// dist.shasum = '';
|
||||
// dist.size = 0;
|
||||
var publish_time = mod.publish_time || Date.now();
|
||||
var item = yield* Module.findByNameAndVersion(mod.name, mod.version);
|
||||
var item = yield Module.findByNameAndVersion(mod.name, mod.version);
|
||||
if (!item) {
|
||||
item = Module.build({
|
||||
name: mod.name,
|
||||
@@ -316,12 +317,74 @@ exports.saveModule = function* (mod) {
|
||||
|
||||
if (words.length > 0) {
|
||||
// add keywords
|
||||
yield* exports.addKeywords(mod.name, description, words);
|
||||
yield exports.addKeywords(mod.name, description, words);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.listModuleAbbreviatedsByName = function* (name) {
|
||||
if (!config.enableAbbreviatedMetadata) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var rows = yield models.ModuleAbbreviated.findAll({
|
||||
where: {
|
||||
name: name,
|
||||
},
|
||||
order: [ ['id', 'DESC'] ],
|
||||
});
|
||||
|
||||
for (var row of rows) {
|
||||
row.package = JSON.parse(row.package);
|
||||
if (row.publish_time && typeof row.publish_time === 'string') {
|
||||
// pg bigint is string
|
||||
row.publish_time = Number(row.publish_time);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object
|
||||
exports.saveModuleAbbreviated = function* (mod) {
|
||||
var pkg = JSON.stringify({
|
||||
name: mod.package.name,
|
||||
version: mod.package.version,
|
||||
deprecated: mod.package.deprecated,
|
||||
dependencies: mod.package.dependencies,
|
||||
optionalDependencies: mod.package.optionalDependencies,
|
||||
devDependencies: mod.package.devDependencies,
|
||||
bundleDependencies: mod.package.bundleDependencies,
|
||||
peerDependencies: mod.package.peerDependencies,
|
||||
bin: mod.package.bin,
|
||||
directories: mod.package.directories,
|
||||
dist: mod.package.dist,
|
||||
engines: mod.package.engines,
|
||||
_hasShrinkwrap: mod.package._hasShrinkwrap,
|
||||
_publish_on_cnpm: mod.package._publish_on_cnpm,
|
||||
});
|
||||
var publish_time = mod.publish_time || Date.now();
|
||||
var item = yield models.ModuleAbbreviated.findByNameAndVersion(mod.name, mod.version);
|
||||
if (!item) {
|
||||
item = models.ModuleAbbreviated.build({
|
||||
name: mod.name,
|
||||
version: mod.version,
|
||||
});
|
||||
}
|
||||
item.publish_time = publish_time;
|
||||
item.package = pkg;
|
||||
|
||||
if (item.changed()) {
|
||||
item = yield item.save();
|
||||
}
|
||||
var result = {
|
||||
id: item.id,
|
||||
gmt_modified: item.gmt_modified,
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.updateModulePackage = function* (id, pkg) {
|
||||
var mod = yield Module.findById(Number(id));
|
||||
if (!mod) {
|
||||
@@ -344,18 +407,36 @@ exports.updateModulePackageFields = function* (id, fields) {
|
||||
return yield exports.updateModulePackage(id, pkg);
|
||||
};
|
||||
|
||||
exports.updateModuleAbbreviatedPackage = function* (item) {
|
||||
// item => { id, name, version, _hasShrinkwrap }
|
||||
var mod = yield models.ModuleAbbreviated.findByNameAndVersion(item.name, item.version);
|
||||
if (!mod) {
|
||||
return null;
|
||||
}
|
||||
var pkg = JSON.parse(mod.package);
|
||||
for (var key in item) {
|
||||
if (key === 'name' || key === 'version' || key === 'id') {
|
||||
continue;
|
||||
}
|
||||
pkg[key] = item[key];
|
||||
}
|
||||
mod.package = JSON.stringify(pkg);
|
||||
|
||||
return yield mod.save([ 'package' ]);
|
||||
};
|
||||
|
||||
exports.updateModuleReadme = function* (id, readme) {
|
||||
var mod = yield* exports.getModuleById(id);
|
||||
var mod = yield exports.getModuleById(id);
|
||||
if (!mod) {
|
||||
return null;
|
||||
}
|
||||
var pkg = mod.package || {};
|
||||
pkg.readme = readme;
|
||||
return yield* exports.updateModulePackage(id, pkg);
|
||||
return yield exports.updateModulePackage(id, pkg);
|
||||
};
|
||||
|
||||
exports.updateModuleDescription = function* (id, description) {
|
||||
var mod = yield* exports.getModuleById(id);
|
||||
var mod = yield exports.getModuleById(id);
|
||||
if (!mod) {
|
||||
return null;
|
||||
}
|
||||
@@ -381,32 +462,83 @@ exports.updateModuleLastModified = function* (name) {
|
||||
return yield row.save();
|
||||
};
|
||||
|
||||
// try to return latest version readme
|
||||
exports.getPackageReadme = function* (name, onlyPackageReadme) {
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
var row = yield models.PackageReadme.findByName(name);
|
||||
if (row) {
|
||||
return {
|
||||
version: row.version,
|
||||
readme: row.readme,
|
||||
};
|
||||
}
|
||||
if (onlyPackageReadme) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var mod = yield exports.getLatestModule(name);
|
||||
if (mod) {
|
||||
return {
|
||||
version: mod.package.version,
|
||||
readme: mod.package.readme,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
exports.savePackageReadme = function* (name, readme, latestVersion) {
|
||||
var item = yield models.PackageReadme.find({ where: { name: name } });
|
||||
if (!item) {
|
||||
item = models.PackageReadme.build({
|
||||
name: name,
|
||||
});
|
||||
}
|
||||
item.readme = readme;
|
||||
item.version = latestVersion;
|
||||
return yield item.save();
|
||||
};
|
||||
|
||||
exports.removeModulesByName = function* (name) {
|
||||
yield Module.destroy({
|
||||
where: {
|
||||
name: name
|
||||
}
|
||||
name: name,
|
||||
},
|
||||
});
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
yield models.ModuleAbbreviated.destroy({
|
||||
where: {
|
||||
name: name,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.removeModulesByNameAndVersions = function* (name, versions) {
|
||||
yield Module.destroy({
|
||||
where: {
|
||||
name: name,
|
||||
version: versions
|
||||
version: versions,
|
||||
}
|
||||
});
|
||||
if (config.enableAbbreviatedMetadata) {
|
||||
yield models.ModuleAbbreviated.destroy({
|
||||
where: {
|
||||
name: name,
|
||||
version: versions,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// tags
|
||||
|
||||
exports.addModuleTag = function* (name, tag, version) {
|
||||
var mod = yield* exports.getModule(name, version);
|
||||
var mod = yield exports.getModule(name, version);
|
||||
if (!mod) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var row = yield* Tag.findByNameAndTag(name, tag);
|
||||
var row = yield Tag.findByNameAndTag(name, tag);
|
||||
if (!row) {
|
||||
row = Tag.build({
|
||||
name: name,
|
||||
@@ -487,26 +619,26 @@ exports.listDependents = function* (dependency) {
|
||||
// maintainers
|
||||
|
||||
exports.listPublicModuleMaintainers = function* (name) {
|
||||
return yield* NpmModuleMaintainer.listMaintainers(name);
|
||||
return yield NpmModuleMaintainer.listMaintainers(name);
|
||||
};
|
||||
|
||||
exports.addPublicModuleMaintainer = function* (name, user) {
|
||||
return yield* NpmModuleMaintainer.addMaintainer(name, user);
|
||||
return yield NpmModuleMaintainer.addMaintainer(name, user);
|
||||
};
|
||||
|
||||
exports.removePublicModuleMaintainer = function* (name, user) {
|
||||
return yield* NpmModuleMaintainer.removeMaintainers(name, user);
|
||||
return yield NpmModuleMaintainer.removeMaintainers(name, user);
|
||||
};
|
||||
|
||||
// only can add to cnpm maintainer table
|
||||
exports.addPrivateModuleMaintainers = function* (name, usernames) {
|
||||
return yield* PrivateModuleMaintainer.addMaintainers(name, usernames);
|
||||
return yield PrivateModuleMaintainer.addMaintainers(name, usernames);
|
||||
};
|
||||
|
||||
exports.updatePrivateModuleMaintainers = function* (name, usernames) {
|
||||
var result = yield* PrivateModuleMaintainer.updateMaintainers(name, usernames);
|
||||
var result = yield PrivateModuleMaintainer.updateMaintainers(name, usernames);
|
||||
if (result.add.length > 0 || result.remove.length > 0) {
|
||||
yield* exports.updateModuleLastModified(name);
|
||||
yield exports.updateModuleLastModified(name);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -516,12 +648,12 @@ function* getMaintainerModel(name) {
|
||||
}
|
||||
|
||||
exports.listMaintainers = function* (name) {
|
||||
var mod = yield* getMaintainerModel(name);
|
||||
var usernames = yield* mod.listMaintainers(name);
|
||||
var mod = yield getMaintainerModel(name);
|
||||
var usernames = yield mod.listMaintainers(name);
|
||||
if (usernames.length === 0) {
|
||||
return usernames;
|
||||
}
|
||||
var users = yield* User.listByNames(usernames);
|
||||
var users = yield User.listByNames(usernames);
|
||||
return users.map(function (user) {
|
||||
return {
|
||||
name: user.name,
|
||||
@@ -531,8 +663,8 @@ exports.listMaintainers = function* (name) {
|
||||
};
|
||||
|
||||
exports.listMaintainerNamesOnly = function* (name) {
|
||||
var mod = yield* getMaintainerModel(name);
|
||||
return yield* mod.listMaintainers(name);
|
||||
var mod = yield getMaintainerModel(name);
|
||||
return yield mod.listMaintainers(name);
|
||||
};
|
||||
|
||||
exports.removeAllMaintainers = function* (name) {
|
||||
@@ -543,7 +675,7 @@ exports.removeAllMaintainers = function* (name) {
|
||||
};
|
||||
|
||||
exports.authMaintainer = function* (packageName, username) {
|
||||
var mod = yield* getMaintainerModel(packageName);
|
||||
var mod = yield getMaintainerModel(packageName);
|
||||
var rs = yield [
|
||||
mod.listMaintainers(packageName),
|
||||
exports.getLatestModule(packageName)
|
||||
@@ -579,7 +711,7 @@ exports.authMaintainer = function* (packageName, username) {
|
||||
};
|
||||
|
||||
exports.isMaintainer = function* (name, username) {
|
||||
var result = yield* exports.authMaintainer(name, username);
|
||||
var result = yield exports.authMaintainer(name, username);
|
||||
return result.isMaintainer;
|
||||
};
|
||||
|
||||
@@ -626,13 +758,13 @@ exports.search = function* (word, options) {
|
||||
|
||||
var sql = 'SELECT module_id FROM tag WHERE LOWER(name) LIKE LOWER(?) AND tag=\'latest\' \
|
||||
ORDER BY name LIMIT ?;';
|
||||
var rows = yield* models.query(sql, [word + '%', limit ]);
|
||||
var rows = yield models.query(sql, [word + '%', limit ]);
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
ids[rows[i].module_id] = 1;
|
||||
}
|
||||
|
||||
if (rows.length < 20) {
|
||||
rows = yield* models.query(sql, [ '%' + word + '%', limit ]);
|
||||
rows = yield models.query(sql, [ '%' + word + '%', limit ]);
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
ids[rows[i].module_id] = 1;
|
||||
}
|
||||
@@ -719,9 +851,9 @@ exports.listUserStarModuleNames = function* (user) {
|
||||
|
||||
// unpublish info
|
||||
exports.saveUnpublishedModule = function* (name, pkg) {
|
||||
return yield* ModuleUnpublished.save(name, pkg);
|
||||
return yield ModuleUnpublished.save(name, pkg);
|
||||
};
|
||||
|
||||
exports.getUnpublishedModule = function* (name) {
|
||||
return yield* ModuleUnpublished.findByName(name);
|
||||
return yield ModuleUnpublished.findByName(name);
|
||||
};
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
/**
|
||||
* Copyright(c) cnpm and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../config');
|
||||
var models = require('../models');
|
||||
var Total = models.Total;
|
||||
@@ -102,22 +90,22 @@ exports.getTotalInfo = function* () {
|
||||
|
||||
exports.plusDeleteModule = function* () {
|
||||
var sql = 'UPDATE total SET module_delete=module_delete+1 WHERE name=\'total\'';
|
||||
return yield* models.query(sql);
|
||||
return yield models.query(sql);
|
||||
};
|
||||
|
||||
exports.setLastSyncTime = function* (time) {
|
||||
var sql = 'UPDATE total SET last_sync_time=? WHERE name=\'total\'';
|
||||
return yield* models.query(sql, [Number(time)]);
|
||||
return yield models.query(sql, [Number(time)]);
|
||||
};
|
||||
|
||||
exports.setLastExistSyncTime = function* (time) {
|
||||
var sql = 'UPDATE total SET last_exist_sync_time=? WHERE name=\'total\'';
|
||||
return yield* models.query(sql, [Number(time)]);
|
||||
return yield models.query(sql, [Number(time)]);
|
||||
};
|
||||
|
||||
exports.updateSyncStatus = function* (status) {
|
||||
var sql = 'UPDATE total SET sync_status=? WHERE name=\'total\'';
|
||||
return yield* models.query(sql, [status]);
|
||||
return yield models.query(sql, [status]);
|
||||
};
|
||||
|
||||
exports.updateSyncNum = function* (params) {
|
||||
@@ -133,5 +121,5 @@ exports.updateSyncNum = function* (params) {
|
||||
sync_status=?, need_sync_num=?, success_sync_num=?, \
|
||||
fail_sync_num=?, left_sync_num=?, last_sync_module=? \
|
||||
WHERE name=\'total\'';
|
||||
return yield* models.query(sql, args);
|
||||
return yield models.query(sql, args);
|
||||
};
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
/**!
|
||||
* cnpmjs.org - services/user.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var config = require('../config');
|
||||
var User = require('../models').User;
|
||||
|
||||
@@ -38,40 +24,40 @@ function convertUser(user) {
|
||||
}
|
||||
|
||||
exports.auth = function* (login, password) {
|
||||
var user = yield* config.userService.auth(login, password);
|
||||
var user = yield config.userService.auth(login, password);
|
||||
return convertUser(user);
|
||||
};
|
||||
|
||||
exports.get = function* (login) {
|
||||
var user = yield* config.userService.get(login);
|
||||
var user = yield config.userService.get(login);
|
||||
return convertUser(user);
|
||||
};
|
||||
|
||||
exports.list = function* (logins) {
|
||||
var users = yield* config.userService.list(logins);
|
||||
var users = yield config.userService.list(logins);
|
||||
return users.map(convertUser);
|
||||
};
|
||||
|
||||
exports.search = function* (query, options) {
|
||||
var users = yield* config.userService.search(query, options);
|
||||
var users = yield config.userService.search(query, options);
|
||||
return users.map(convertUser);
|
||||
};
|
||||
|
||||
exports.getAndSave = function* (login) {
|
||||
if (config.customUserService) {
|
||||
var user = yield* exports.get(login);
|
||||
var user = yield exports.get(login);
|
||||
if (user) {
|
||||
var data = {
|
||||
user: user
|
||||
};
|
||||
yield* User.saveCustomUser(data);
|
||||
yield User.saveCustomUser(data);
|
||||
}
|
||||
}
|
||||
return yield* User.findByName(login);
|
||||
return yield User.findByName(login);
|
||||
};
|
||||
|
||||
exports.authAndSave = function* (login, password) {
|
||||
var user = yield* exports.auth(login, password);
|
||||
var user = yield exports.auth(login, password);
|
||||
if (user) {
|
||||
if (config.customUserService) {
|
||||
// make sure sync user meta to cnpm database
|
||||
@@ -79,16 +65,16 @@ exports.authAndSave = function* (login, password) {
|
||||
rev: Date.now() + '-' + user.login,
|
||||
user: user
|
||||
};
|
||||
yield* User.saveCustomUser(data);
|
||||
yield User.saveCustomUser(data);
|
||||
}
|
||||
}
|
||||
return user;
|
||||
};
|
||||
|
||||
exports.add = function* (user) {
|
||||
return yield* User.add(user);
|
||||
return yield User.add(user);
|
||||
};
|
||||
|
||||
exports.update = function* (user) {
|
||||
return yield* User.update(user);
|
||||
return yield User.update(user);
|
||||
};
|
||||
|
||||
@@ -12,7 +12,10 @@ const db = config.officialNpmReplicate;
|
||||
const lastSeqFile = path.join(config.dataDir, '.cnpmjs.org.last_seq.txt');
|
||||
let _STREAM_ID = 0;
|
||||
|
||||
// debug: curl -v https://replicate.npmjs.com/_changes?since=9052545
|
||||
|
||||
module.exports = function* sync() {
|
||||
const pedding = [];
|
||||
const since = yield getLastSequence();
|
||||
const streamId = _STREAM_ID++;
|
||||
let changesCount = 0;
|
||||
@@ -26,12 +29,24 @@ module.exports = function* sync() {
|
||||
changes.on('data', change => {
|
||||
changesCount++;
|
||||
logger.syncInfo('stream#%d get change#%d: %j', streamId, changesCount, change);
|
||||
syncPackage(change);
|
||||
pedding.push(change);
|
||||
// syncPackage(change);
|
||||
});
|
||||
|
||||
const timer = setInterval(function() {
|
||||
for (var i = 0; i < 100; i++) {
|
||||
var change = pedding.shift();
|
||||
if (!change) {
|
||||
break;
|
||||
}
|
||||
syncPackage(change);
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
try {
|
||||
yield changes.await('error');
|
||||
} catch (err) {
|
||||
clearInterval(timer);
|
||||
// make sure changes steam is destroy
|
||||
changes.destroy();
|
||||
err.message += `, stream#${streamId}, changesCount#${changesCount}`;
|
||||
@@ -41,7 +56,8 @@ module.exports = function* sync() {
|
||||
|
||||
function syncPackage(change) {
|
||||
const url = `${config.handleSyncRegistry}/${change.id}/sync`;
|
||||
urllib.request(url, {
|
||||
// sync upstream and without deps
|
||||
urllib.request(`${url}?sync_upstream=true&nodeps=true`, {
|
||||
method: 'PUT',
|
||||
dataType: 'json',
|
||||
timeout: 10000,
|
||||
@@ -50,7 +66,6 @@ function syncPackage(change) {
|
||||
logger.syncInfo('%s:%s PUT %s error: %s, retry after 5s',
|
||||
change.seq, change.id, url, err);
|
||||
logger.syncError(err);
|
||||
syncPackage(change);
|
||||
setTimeout(() => syncPackage(change), 5000);
|
||||
} else {
|
||||
saveLastSequence(change.seq);
|
||||
|
||||
@@ -148,7 +148,8 @@ function sendMailToAdmin(err, result, syncTime) {
|
||||
if (err) {
|
||||
// ignore 503, 504 error
|
||||
// 504: Gateway Time-out
|
||||
if (err.status === 503 || err.status === 504) {
|
||||
// 502 Bad Gateway
|
||||
if (err.status === 503 || err.status === 504 || err.status === 502) {
|
||||
return;
|
||||
}
|
||||
if (err.name === 'JSONResponseFormatError') {
|
||||
|
||||
@@ -14,7 +14,7 @@ var logger = require('../common/logger');
|
||||
* @param {String} lastSyncModule
|
||||
*/
|
||||
function* getFirstSyncPackages(lastSyncModule) {
|
||||
var pkgs = yield* npmService.getShort();
|
||||
var pkgs = yield npmService.getShort();
|
||||
if (!lastSyncModule) {
|
||||
return pkgs;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ function* getFirstSyncPackages(lastSyncModule) {
|
||||
|
||||
module.exports = function* sync() {
|
||||
var syncTime = Date.now();
|
||||
var info = yield* totalService.getTotalInfo();
|
||||
var info = yield totalService.getTotalInfo();
|
||||
if (!info) {
|
||||
throw new Error('can not found total info');
|
||||
}
|
||||
@@ -36,7 +36,7 @@ module.exports = function* sync() {
|
||||
logger.syncInfo('Last sync time %s', new Date(info.last_sync_time));
|
||||
if (!info.last_sync_time) {
|
||||
logger.syncInfo('First time sync all packages from official registry');
|
||||
packages = yield* getFirstSyncPackages(info.last_sync_module);
|
||||
packages = yield getFirstSyncPackages(info.last_sync_module);
|
||||
} else {
|
||||
var result = yield npmService.fetchUpdatesSince(info.last_sync_time);
|
||||
syncTime = result.lastModified;
|
||||
@@ -66,8 +66,9 @@ module.exports = function* sync() {
|
||||
|
||||
logger.syncInfo('All packages sync done, successes %d, fails %d, updates %d',
|
||||
worker.successes.length, worker.fails.length, worker.updates.length);
|
||||
//only when all succss, set last sync time
|
||||
if (!worker.fails.length) {
|
||||
// only when all succss, set last sync time
|
||||
// or successes > 1000
|
||||
if (!worker.fails.length || worker.successes.length > 1000) {
|
||||
yield totalService.setLastSyncTime(syncTime);
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -78,7 +78,7 @@ module.exports = function* sync() {
|
||||
debug('All packages sync done, successes %d, fails %d',
|
||||
worker.successes.length, worker.fails.length);
|
||||
|
||||
yield* totalService.setLastExistSyncTime(syncTime);
|
||||
yield totalService.setLastExistSyncTime(syncTime);
|
||||
return {
|
||||
successes: worker.successes,
|
||||
fails: worker.fails
|
||||
|
||||
@@ -9,7 +9,7 @@ var SyncModuleWorker = require('../controllers/sync_module_worker');
|
||||
var logger = require('../common/logger');
|
||||
|
||||
module.exports = function* syncPopular() {
|
||||
var packages = yield* npmService.getPopular(config.topPopular);
|
||||
var packages = yield npmService.getPopular(config.topPopular);
|
||||
packages = packages.map(function (r) {
|
||||
return r[0];
|
||||
});
|
||||
|
||||
@@ -1,41 +1,27 @@
|
||||
/**!
|
||||
* cnpmjs.org - test/common/markdown.test.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var utils = require('../utils');
|
||||
var markdown = require('../../common/markdown');
|
||||
|
||||
describe('common/markdown.test.js', function () {
|
||||
it('should render sonido readme', function () {
|
||||
describe('common/markdown.test.js', () => {
|
||||
it('should render sonido readme', () => {
|
||||
var readme = utils.getFileContent('sonido.md');
|
||||
var md = markdown.render(readme);
|
||||
md.should.equal('<p>Configuration Wizard: <!--- This is what the user will see during the configuration -></p>\n');
|
||||
});
|
||||
|
||||
it('should filter xss', function () {
|
||||
it('should filter xss', () => {
|
||||
var html = markdown.render('foo<script>alert(1)</script>/xss\n[foo](/foo) <a onclick="alert(1)">bar</a>\n"\'');
|
||||
html.should.equal('<p>foo<script>alert(1)</script>/xss\n<a href="/foo">foo</a> <a>bar</a>\n"\'</p>\n');
|
||||
markdown.render('[xss link](javascript:alert(2))').should.equal('<p>[xss link](javascript:alert(2))</p>\n');
|
||||
});
|
||||
|
||||
it('should handle eat cpu markdown', function () {
|
||||
it('should handle eat cpu markdown', () => {
|
||||
var readme = utils.getFileContent('eat-cpu.md');
|
||||
markdown.render(readme);
|
||||
});
|
||||
|
||||
it('should not filter < and > on code', function () {
|
||||
it('should not filter < and > on code', () => {
|
||||
var content = utils.getFileContent('code.md');
|
||||
var html = markdown.render(content);
|
||||
html.should.containEql('<pre><code class="language-html"><body>hi</body>');
|
||||
|
||||
108
test/controllers/registry/audit.test.js
Normal file
108
test/controllers/registry/audit.test.js
Normal file
@@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
var should = require('should');
|
||||
var request = require('supertest');
|
||||
var pedding = require('pedding');
|
||||
var app = require('../../../servers/registry');
|
||||
var utils = require('../../utils');
|
||||
|
||||
describe('test/controllers/registry/audit.test.js', function () {
|
||||
it('should get /-/npm/v1/security/audits', function (done) {
|
||||
var reqBody = {
|
||||
"name": "demo-npm",
|
||||
"version": "1.0.0",
|
||||
"requires": {
|
||||
"minimatch": "^1.0.0",
|
||||
"moment": "^2.10.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"lru-cache": {
|
||||
"version": "2.7.3",
|
||||
"integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI="
|
||||
},
|
||||
"minimatch": {
|
||||
"version": "1.0.0",
|
||||
"integrity": "sha1-4N0hILSeG3JM6NcUxSCCKpQ4V20=",
|
||||
"requires": {
|
||||
"lru-cache": "2",
|
||||
"sigmund": "~1.0.0"
|
||||
}
|
||||
},
|
||||
"moment": {
|
||||
"version": "2.22.1",
|
||||
"integrity": "sha512-shJkRTSebXvsVqk56I+lkb2latjBs8I+pc2TzWc545y2iFnSjm7Wg0QMh+ZWcdSLQyGEau5jI8ocnmkyTgr9YQ=="
|
||||
},
|
||||
"sigmund": {
|
||||
"version": "1.0.1",
|
||||
"integrity": "sha1-P\/IfGYytIXX587eBhT\/ZTQ0ZtZA="
|
||||
}
|
||||
},
|
||||
"install": [
|
||||
|
||||
],
|
||||
"remove": [
|
||||
|
||||
],
|
||||
"metadata": {
|
||||
"npm_version": "6.0.1",
|
||||
"node_version": "v8.11.2",
|
||||
"platform": "win32"
|
||||
}
|
||||
};
|
||||
request(app)
|
||||
.post('/-/npm/v1/security/audits')
|
||||
.send(reqBody)
|
||||
.expect(200, done);
|
||||
})
|
||||
|
||||
it('should get /-/npm/v1/security/audits/quick', function (done) {
|
||||
var reqBody = {
|
||||
"name": "demo-npm",
|
||||
"version": "1.0.0",
|
||||
"requires": {
|
||||
"moment": "^2.10.5",
|
||||
"minimatch": "^1.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"lru-cache": {
|
||||
"version": "2.7.3",
|
||||
"integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI="
|
||||
},
|
||||
"minimatch": {
|
||||
"version": "1.0.0",
|
||||
"integrity": "sha1-4N0hILSeG3JM6NcUxSCCKpQ4V20=",
|
||||
"requires": {
|
||||
"lru-cache": "2",
|
||||
"sigmund": "~1.0.0"
|
||||
}
|
||||
},
|
||||
"moment": {
|
||||
"version": "2.22.1",
|
||||
"integrity": "sha512-shJkRTSebXvsVqk56I+lkb2latjBs8I+pc2TzWc545y2iFnSjm7Wg0QMh+ZWcdSLQyGEau5jI8ocnmkyTgr9YQ=="
|
||||
},
|
||||
"sigmund": {
|
||||
"version": "1.0.1",
|
||||
"integrity": "sha1-P\/IfGYytIXX587eBhT\/ZTQ0ZtZA="
|
||||
}
|
||||
},
|
||||
"install": [
|
||||
"minimatch@1.0.0"
|
||||
],
|
||||
"remove": [
|
||||
|
||||
],
|
||||
"metadata": {
|
||||
"npm_version": "6.0.1",
|
||||
"node_version": "v8.11.2",
|
||||
"platform": "win32"
|
||||
}
|
||||
}
|
||||
request(app)
|
||||
.post('/-/npm/v1/security/audits/quick')
|
||||
.send(reqBody)
|
||||
.expect(200, function (err, res) {
|
||||
res.body.metadata.should.Object()
|
||||
done();
|
||||
});
|
||||
})
|
||||
});
|
||||
@@ -44,8 +44,8 @@ describe('controllers/registry/module/config_private_packages.test.js', function
|
||||
.expect(403, function (err, res) {
|
||||
should.not.exist(err);
|
||||
res.body.should.eql({
|
||||
error: 'forbidden',
|
||||
reason: 'cannot modify pre-existing version: 0.0.1'
|
||||
error: '[forbidden] cannot modify pre-existing version: 0.0.1',
|
||||
reason: '[forbidden] cannot modify pre-existing version: 0.0.1',
|
||||
});
|
||||
done();
|
||||
});
|
||||
@@ -58,7 +58,7 @@ describe('controllers/registry/module/config_private_packages.test.js', function
|
||||
.put('/' + pkg.name)
|
||||
.set('authorization', utils.secondUserAuth)
|
||||
.send(pkg)
|
||||
.expect(/forbidden user/)
|
||||
.expect(/not authorized to modify private-package/)
|
||||
.expect(403, done);
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('controllers/registry/module/config_private_packages.test.js', function
|
||||
.put('/' + pkg.name)
|
||||
.set('authorization', utils.adminAuth)
|
||||
.send(pkg)
|
||||
.expect(/forbidden user/)
|
||||
.expect(/not authorized to modify private-package/)
|
||||
.expect(403, done);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,39 +1,23 @@
|
||||
/**!
|
||||
* cnpmjs.org - test/controllers/registry/module/maintainer.test.js
|
||||
*
|
||||
* Copyright(c) fengmk2 and other contributors.
|
||||
* MIT Licensed
|
||||
*
|
||||
* Authors:
|
||||
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var request = require('supertest');
|
||||
var mm = require('mm');
|
||||
var config = require('../../../../config');
|
||||
var app = require('../../../../servers/registry');
|
||||
var utils = require('../../../utils');
|
||||
|
||||
describe('controllers/registry/module/maintainer.test.js', function () {
|
||||
describe('test/controllers/registry/module/maintainer.test.js', function () {
|
||||
var pkgname = '@cnpm/test-package-maintainer';
|
||||
var pkgURL = '/@' + encodeURIComponent(pkgname.substring(1));
|
||||
before(function (done) {
|
||||
app = app.listen(0, function () {
|
||||
// add scope package
|
||||
var pkg = utils.getPackage(pkgname, '0.0.1', utils.admin);
|
||||
// add scope package
|
||||
var pkg = utils.getPackage(pkgname, '0.0.1', utils.admin);
|
||||
|
||||
request(app)
|
||||
.put(pkgURL)
|
||||
.set('authorization', utils.adminAuth)
|
||||
.send(pkg)
|
||||
.expect(201, done);
|
||||
});
|
||||
request(app)
|
||||
.put(pkgURL)
|
||||
.set('authorization', utils.adminAuth)
|
||||
.send(pkg)
|
||||
.expect(201, done);
|
||||
});
|
||||
|
||||
beforeEach(function () {
|
||||
@@ -70,8 +54,8 @@ describe('controllers/registry/module/maintainer.test.js', function () {
|
||||
]
|
||||
})
|
||||
.expect({
|
||||
error: 'invalid user name',
|
||||
reason: 'User: `new-maintainer-not-exists, new-maintainer-not-exists2` not exists'
|
||||
error: '[invalid] User: `new-maintainer-not-exists, new-maintainer-not-exists2` not exists',
|
||||
reason: '[invalid] User: `new-maintainer-not-exists, new-maintainer-not-exists2` not exists',
|
||||
})
|
||||
.expect(403, done);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user