Repository: gabrielcsapo/node-git-server Branch: main Commit: 2ab22a4d3f1a Files: 54 Total size: 112.7 KB Directory structure: gitextract_zxdd4_k5/ ├── .eslintignore ├── .eslintrc ├── .git-package.meta ├── .github/ │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── .npmignore ├── .prettierrc ├── CHANGELOG.md ├── LICENSE ├── README.md ├── example/ │ ├── certificate.pem │ ├── index.js │ └── privatekey.pem ├── fixtures/ │ └── server/ │ └── tmp/ │ └── test.git/ │ ├── HEAD │ ├── config │ ├── description │ ├── hooks/ │ │ ├── applypatch-msg.sample │ │ ├── commit-msg.sample │ │ ├── post-update.sample │ │ ├── pre-applypatch.sample │ │ ├── pre-commit.sample │ │ ├── pre-push.sample │ │ ├── pre-rebase.sample │ │ ├── pre-receive.sample │ │ ├── prepare-commit-msg.sample │ │ └── update.sample │ ├── info/ │ │ └── exclude │ ├── objects/ │ │ ├── 0e/ │ │ │ └── 60b9add392cd124fbf8e994bdbbde7a3192572 │ │ ├── 2b/ │ │ │ └── e7c65ae93b54b988416f280298b0b8b5f20385 │ │ └── ed/ │ │ └── 88ef46143302c0acc42531f085c49d79ba68ba │ └── refs/ │ └── heads/ │ └── master ├── package.json ├── src/ │ ├── git.test.ts │ ├── git.ts │ ├── http-duplex.test.ts │ ├── http-duplex.ts │ ├── index.ts │ ├── service.ts │ ├── types.ts │ ├── util.test.ts │ └── util.ts ├── tsconfig.json ├── vitest.config.js └── website/ ├── .gitignore ├── README.md ├── babel.config.js ├── docs/ │ └── intro.md ├── docusaurus.config.js ├── package.json ├── src/ │ ├── css/ │ │ └── custom.css │ └── pages/ │ ├── index.js │ └── index.module.css └── static/ └── .nojekyll ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ docs node_modules coverage temp dist etc coverage build fixtures example ================================================ FILE: .eslintrc ================================================ { "parser": "@typescript-eslint/parser", "plugins": [ "prettier", "@typescript-eslint" ], "extends": [ "eslint:recommended", "plugin:prettier/recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ] } ================================================ FILE: .git-package.meta ================================================ ================================================ FILE: .github/workflows/ci.yml ================================================ # This is a basic workflow to help you get started with Actions name: CI # Controls when the workflow will run on: # Triggers the workflow on push or pull request events but only for the main branch push: branches: [main] pull_request: branches: [main] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: lint: name: 'Lint' runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: volta-cli/action@v1 with: node-version: ${{ matrix.node }} - name: install dependencies run: npm i - name: lint run: npm run lint env: CI: true test: name: 'Node ${{ matrix.node }} - ${{ matrix.os }}' runs-on: ${{ matrix.os }}-latest strategy: matrix: node: ['16', 'latest'] os: [ubuntu, macOS, windows] steps: - uses: actions/checkout@v1 - uses: volta-cli/action@v1 with: node-version: ${{ matrix.node }} - name: install dependencies run: npm i - name: test run: npm test env: CI: true gh-release: if: github.event_name != 'pull_request' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: '16.x' - uses: webfactory/ssh-agent@v0.5.3 with: ssh-private-key: ${{ secrets.GH_PAGES_DEPLOY }} - name: Release to GitHub Pages env: USE_SSH: true GIT_USER: git run: | git config --global user.email "gabecsapo@gmail.com" git config --global user.name "Gabriel J. Csapo" npm install npm run build cd website npm install npm run deploy ================================================ FILE: .gitignore ================================================ node_modules .DS_Store npm-debug.log coverage .nyc_output example/test example/tmp package-lock.json .vs/ dist temp etc build-complete.meta ================================================ FILE: .husky/pre-commit ================================================ #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" npm run build npm run lint ================================================ FILE: .npmignore ================================================ .git-package.meta ================================================ FILE: .prettierrc ================================================ { "singleQuote": true } ================================================ FILE: CHANGELOG.md ================================================ # 1.0.0 (07/10/2022) - Removes node support from node@<16 (@gabrielcsapo) - Bugfix: Fix logging on response streams. (#96) (@willstott101) - Avoid using self in service.ts - to avoid issue with through (#95) (@willstott101) - Migrates to typescript (@5GameMaker @gabrielcsapo) - Removes node support from node@<14 # 1.0.0-beta.31 (07/10/2022) - Removes node support from node@<16 (@gabrielcsapo) # 1.0.0-beta.30 (01/26/2022) - Bugfix: Fix logging on response streams. (#96) (@willstott101) # 1.0.0-beta.21 (01/24/2022) - Avoid using self in service.ts - to avoid issue with through (#95) (@willstott101) # 1.0.0-beta.1 (01/02/2022) - Migrates to typescript (@5GameMaker @gabrielcsapo) - Removes node support from node@<14 # 0.6.1 (03/03/2019) - Fixes bug with being able to overwrite git repos that a user doesn't have access to. @masasron # 0.6.0 (03/03/2019) - Augments the authenticate function declaration to accept an object as the first argument and a callback for the second. This allows us to make changes without having to cause breaking changes. - Adds the ability to introspect on the header (fixes #49) # 0.5.1 (03/03/2019) - bump dependencies - tap `^11.0.1` -> `^12.5.3` - tryitout `^2.0.6` -> `^2.1.1` # 0.5.0 (11/27/2018) - adds `log` functionality for event streams and response streams # 0.4.3 (04/30/2018) - removes deprecated `Buffer` interface # 0.4.2 (12/07/2017) - adds https support # 0.4.1 (12/04/2017) - fixes type to be the same as the event names # 0.4.0 (12/03/2017) - [BREAKING] changes the interface for authentication to make it more flexible - when error is sent back to client ensure error is string # 0.3.4 (11/10/2017) - updates duplex lib to fix cork, uncork and add some chaining - adds extensive docs to Git, Util and Service - adds named function to events to trace errors more easily # 0.3.3 (11/05/2017) - Removes dependency on http-duplex package replacing w/ internal replacement lib - updates tryitout@1.0.0 and updates Docs # 0.3.2 (11/02/2017) - fixes pathing issues on non linux/unix based operating systems (windows) # 0.3.1 (10/17/2017) - allow authenticate to handle promises # 0.3.0 - removes authentication logic and makes it a configurable middleware - passes username to listener objects # 0.2.1 (09/15/2017) - fixes bug that would let anyone publish to a repo regardless of permissions that were set - fixes bug in test that didn't properly test auth based operations # 0.2.0 (09/05/2017) - abstracts server into lib/git.js - fixes list to only return valid .git directories - adds tests for basicAuth middleware - isolate helper functions into util.js - refactor unit tests to subside in files they are relevant to - adds jsdoc # 0.1.0 (05/08/2017) - adds basic authentication protection for repositories - updates docs to expose information # 0.0.3 (05/08/2017) - fixes bug with `mkdir` function that caused random directories to be created ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2021 Gabriel Csapo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # node-git-server > 🎡 A configurable git server written in Node.js [![Npm Version](https://img.shields.io/npm/v/node-git-server.svg)](https://www.npmjs.com/package/node-git-server) [![Build Status](https://travis-ci.org/gabrielcsapo/node-git-server.svg?branch=master)](https://travis-ci.org/gabrielcsapo/node-git-server) [![Dependency Status](https://starbuck.gabrielcsapo.com/badge/github/gabrielcsapo/node-git-server/status.svg)](https://starbuck.gabrielcsapo.com/github/gabrielcsapo/node-git-server) [![devDependency Status](https://starbuck.gabrielcsapo.com/badge/github/gabrielcsapo/node-git-server/dev-status.svg)](https://starbuck.gabrielcsapo.com/github/gabrielcsapo/node-git-server#info=devDependencies) [![npm](https://img.shields.io/npm/dt/node-git-server.svg)]() [![npm](https://img.shields.io/npm/dm/node-git-server.svg)]() ## Install ```shell npm install node-git-server ``` ## Usage Please visit our docs [https://gabrielcsapo.github.io/node-git-server](https://gabrielcsapo.github.io/node-git-server)! ## Philosophy This library is aimed to have a zero dependency footprint. If you are reading this and you see dependencies, help to remove them 🐒. ## Thanks This is a hard fork from [pushover](https://github.com/substack/pushover). ================================================ FILE: example/certificate.pem ================================================ -----BEGIN CERTIFICATE----- MIIB0TCCAToCCQCvzaaNTZEFTDANBgkqhkiG9w0BAQUFADAtMQswCQYDVQQGEwJV UzELMAkGA1UECAwCQ0ExETAPBgNVBAcMCFNhbiBKb3NlMB4XDTE3MTIwNzE5MTI0 NloXDTE4MDEwNjE5MTI0NlowLTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMREw DwYDVQQHDAhTYW4gSm9zZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAplVm UrhFbgb+g7gHDjfdTZUwqNnJ6AajytmqmzV7ceTeXKtKfNAN7i2DyFxf/IwQWoxs 0g7MOE8UP19GCInK0I5T9svvbtSVEfxrtGLMBY7qnojN7Q+DIjdvM7f/m5W8oNkQ qb3EzkBKX6A5HobxKqTdu40IBLBkxa0faEmU84MCAwEAATANBgkqhkiG9w0BAQUF AAOBgQAzN5VrWE0bFT/UZgUCHrR6h+EQRfGCybAq6MmS1hEoHkLyLPIjokcRWxFe eufVyxesJaUiO6f3W34J2NoZK4NsEF931t/n12bB8Ku8H1tokNsyWqJns2Whj+bR 012osVh6ghdOvKD0yrnv6oLjMU51A8UKuxh51xoMThU0vBwvDg== -----END CERTIFICATE----- ================================================ FILE: example/index.js ================================================ // You Can Use The Commands Below To Generate A Self Signed Certificate For Use With This Tutorial // These Commands Require That You have 'openssl' installed on your system // openssl genrsa -out privatekey.pem 1024 // openssl req -new -key privatekey.pem -out certrequest.csr // openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem let type = 'http'; process.argv.slice(2).forEach((arg) => { switch (arg) { case 'https': case '--https': type = 'https'; break; } }); const fs = require('fs'); const path = require('path'); const { Git: Server } = require('../'); const port = process.env.PORT || 7005; const repos = new Server(path.normalize(path.resolve(__dirname, 'tmp')), { autoCreate: true, authenticate: ({ type, repo, user, headers }, next) => { console.log(type, repo, headers); // eslint-disable-line if (type == 'push') { // Decide if this user is allowed to perform this action against this repo. user((username, password) => { if (username === '42' && password === '42') { next(); } else { next('wrong password'); } }); } else { // Check these credentials are correct for this user. next(); } }, }); repos.on('push', (push) => { console.log(`push ${push.repo} / ${push.commit} ( ${push.branch} )`); // eslint-disable-line repos.list((err, results) => { push.log(' '); push.log('Hey!'); push.log('Checkout these other repos:'); for (const repo of results) { push.log(`- ${repo}`); } push.log(' '); }); push.accept(); }); repos.on('fetch', (fetch) => { console.log(`username ${fetch.username}`); // eslint-disable-line console.log(`fetch ${fetch.repo}/${fetch.commit}`); // eslint-disable-line fetch.accept(); }); repos.listen( port, { type, key: fs.readFileSync(path.resolve(__dirname, 'privatekey.pem')), cert: fs.readFileSync(path.resolve(__dirname, 'certificate.pem')), }, (error) => { if (error) return console.error( `failed to start git-server because of error ${error}` ); // eslint-disable-line console.log(`node-git-server running at ${type}://localhost:${port}`); // eslint-disable-line repos.list((err, result) => { if (!result) { console.log('No repositories available...'); // eslint-disable-line } else { console.log(result); // eslint-disable-line } }); } ); ================================================ FILE: example/privatekey.pem ================================================ -----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQCmVWZSuEVuBv6DuAcON91NlTCo2cnoBqPK2aqbNXtx5N5cq0p8 0A3uLYPIXF/8jBBajGzSDsw4TxQ/X0YIicrQjlP2y+9u1JUR/Gu0YswFjuqeiM3t D4MiN28zt/+blbyg2RCpvcTOQEpfoDkehvEqpN27jQgEsGTFrR9oSZTzgwIDAQAB AoGAb3gr6qOzY9ksF/nsQIsPtD6XLZFGzkgk3Hyi6QEeiWVn35KriJmlvEikWFIP wZ/cFdKl2uAv3EyitRWUSYSOdcD+tri253WkwpKr8qEq3MKdEsQGZlPiO2MJpWsa 4vsy1bleUxqbB2TYIIXdjgD8TpTCh8sc8pVxEWEuEThxIIECQQDY9TSZkZHqsqpC bK/VUpluj3coZJcczk64ZAdkWYlXfNpvgdT3ViPjpdEYeabzTP0xI7OHkx6fVLiS 87Y6EwWfAkEAxEQKhgj+saudBzl2EUQW5qntdJh3Fr+OLErSHb4M5E/nWvxW6il0 XWRE3b7KrikThPkwUtXPTBNGiZ7D1dvfnQJAHMLk5jbWETb+OzANX0pD7NQ4B7LO FZOD/A3GrRbxjhePHZkokmFpAJTK02PNLhPWvNzuv9pRBO5GSbTlQ22iIQJAQiEy 8oqhVrgeRsrjr1mj5cCn07tzlOSiQOZM+dyJd3w81flkR64EGVupoJWisSACBbH4 yFBmcpmkEMa/8ZUOOQJAfAqyF5aCRh4MbPT7pCGSf0gckc3p6qISb1Zodh7GLSdb f/VvQzhRG3MKnSl+ZQ+GQT+F+FeZl0/ZPjVRYG/Avw== -----END RSA PRIVATE KEY----- ================================================ FILE: fixtures/server/tmp/test.git/HEAD ================================================ ref: refs/heads/master ================================================ FILE: fixtures/server/tmp/test.git/config ================================================ [core] repositoryformatversion = 0 filemode = true bare = true ignorecase = true precomposeunicode = true ================================================ FILE: fixtures/server/tmp/test.git/description ================================================ Unnamed repository; edit this file 'description' to name the repository. ================================================ FILE: fixtures/server/tmp/test.git/hooks/applypatch-msg.sample ================================================ #!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} : ================================================ FILE: fixtures/server/tmp/test.git/hooks/commit-msg.sample ================================================ #!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 } ================================================ FILE: fixtures/server/tmp/test.git/hooks/post-update.sample ================================================ #!/bin/sh # # An example hook script to prepare a packed repository for use over # dumb transports. # # To enable this hook, rename this file to "post-update". exec git update-server-info ================================================ FILE: fixtures/server/tmp/test.git/hooks/pre-applypatch.sample ================================================ #!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup precommit="$(git rev-parse --git-path hooks/pre-commit)" test -x "$precommit" && exec "$precommit" ${1+"$@"} : ================================================ FILE: fixtures/server/tmp/test.git/hooks/pre-commit.sample ================================================ #!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against -- ================================================ FILE: fixtures/server/tmp/test.git/hooks/pre-push.sample ================================================ #!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0 ================================================ FILE: fixtures/server/tmp/test.git/hooks/pre-rebase.sample ================================================ #!/bin/sh # # Copyright (c) 2006, 2008 Junio C Hamano # # The "pre-rebase" hook is run just before "git rebase" starts doing # its job, and can prevent the command from running by exiting with # non-zero status. # # The hook is called with the following parameters: # # $1 -- the upstream the series was forked from. # $2 -- the branch being rebased (or empty when rebasing the current branch). # # This sample shows how to prevent topic branches that are already # merged to 'next' branch from getting rebased, because allowing it # would result in rebasing already published history. publish=next basebranch="$1" if test "$#" = 2 then topic="refs/heads/$2" else topic=`git symbolic-ref HEAD` || exit 0 ;# we do not interrupt rebasing detached HEAD fi case "$topic" in refs/heads/??/*) ;; *) exit 0 ;# we do not interrupt others. ;; esac # Now we are dealing with a topic branch being rebased # on top of master. Is it OK to rebase it? # Does the topic really exist? git show-ref -q "$topic" || { echo >&2 "No such branch $topic" exit 1 } # Is topic fully merged to master? not_in_master=`git rev-list --pretty=oneline ^master "$topic"` if test -z "$not_in_master" then echo >&2 "$topic is fully merged to master; better remove it." exit 1 ;# we could allow it, but there is no point. fi # Is topic ever merged to next? If so you should not be rebasing it. only_next_1=`git rev-list ^master "^$topic" ${publish} | sort` only_next_2=`git rev-list ^master ${publish} | sort` if test "$only_next_1" = "$only_next_2" then not_in_topic=`git rev-list "^$topic" master` if test -z "$not_in_topic" then echo >&2 "$topic is already up-to-date with master" exit 1 ;# we could allow it, but there is no point. else exit 0 fi else not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"` /usr/bin/perl -e ' my $topic = $ARGV[0]; my $msg = "* $topic has commits already merged to public branch:\n"; my (%not_in_next) = map { /^([0-9a-f]+) /; ($1 => 1); } split(/\n/, $ARGV[1]); for my $elem (map { /^([0-9a-f]+) (.*)$/; [$1 => $2]; } split(/\n/, $ARGV[2])) { if (!exists $not_in_next{$elem->[0]}) { if ($msg) { print STDERR $msg; undef $msg; } print STDERR " $elem->[1]\n"; } } ' "$topic" "$not_in_next" "$not_in_master" exit 1 fi exit 0 ################################################################ This sample hook safeguards topic branches that have been published from being rewound. The workflow assumed here is: * Once a topic branch forks from "master", "master" is never merged into it again (either directly or indirectly). * Once a topic branch is fully cooked and merged into "master", it is deleted. If you need to build on top of it to correct earlier mistakes, a new topic branch is created by forking at the tip of the "master". This is not strictly necessary, but it makes it easier to keep your history simple. * Whenever you need to test or publish your changes to topic branches, merge them into "next" branch. The script, being an example, hardcodes the publish branch name to be "next", but it is trivial to make it configurable via $GIT_DIR/config mechanism. With this workflow, you would want to know: (1) ... if a topic branch has ever been merged to "next". Young topic branches can have stupid mistakes you would rather clean up before publishing, and things that have not been merged into other branches can be easily rebased without affecting other people. But once it is published, you would not want to rewind it. (2) ... if a topic branch has been fully merged to "master". Then you can delete it. More importantly, you should not build on top of it -- other people may already want to change things related to the topic as patches against your "master", so if you need further changes, it is better to fork the topic (perhaps with the same name) afresh from the tip of "master". Let's look at this example: o---o---o---o---o---o---o---o---o---o "next" / / / / / a---a---b A / / / / / / / / c---c---c---c B / / / / \ / / / / b---b C \ / / / / / \ / ---o---o---o---o---o---o---o---o---o---o---o "master" A, B and C are topic branches. * A has one fix since it was merged up to "next". * B has finished. It has been fully merged up to "master" and "next", and is ready to be deleted. * C has not merged to "next" at all. We would want to allow C to be rebased, refuse A, and encourage B to be deleted. To compute (1): git rev-list ^master ^topic next git rev-list ^master next if these match, topic has not merged in next at all. To compute (2): git rev-list master..topic if this is empty, it is fully merged to "master". ================================================ FILE: fixtures/server/tmp/test.git/hooks/pre-receive.sample ================================================ #!/bin/sh # # An example hook script to make use of push options. # The example simply echoes all push options that start with 'echoback=' # and rejects all pushes when the "reject" push option is used. # # To enable this hook, rename this file to "pre-receive". if test -n "$GIT_PUSH_OPTION_COUNT" then i=0 while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" do eval "value=\$GIT_PUSH_OPTION_$i" case "$value" in echoback=*) echo "echo from the pre-receive-hook: ${value#*=}" >&2 ;; reject) exit 1 esac i=$((i + 1)) done fi ================================================ FILE: fixtures/server/tmp/test.git/hooks/prepare-commit-msg.sample ================================================ #!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first comments out the # "Conflicts:" part of a merge commit. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. case "$2,$3" in merge,) /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;; # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$1" ;; *) ;; esac # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" ================================================ FILE: fixtures/server/tmp/test.git/hooks/update.sample ================================================ #!/bin/sh # # An example hook script to block unannotated tags from entering. # Called by "git receive-pack" with arguments: refname sha1-old sha1-new # # To enable this hook, rename this file to "update". # # Config # ------ # hooks.allowunannotated # This boolean sets whether unannotated tags will be allowed into the # repository. By default they won't be. # hooks.allowdeletetag # This boolean sets whether deleting tags will be allowed in the # repository. By default they won't be. # hooks.allowmodifytag # This boolean sets whether a tag may be modified after creation. By default # it won't be. # hooks.allowdeletebranch # This boolean sets whether deleting branches will be allowed in the # repository. By default they won't be. # hooks.denycreatebranch # This boolean sets whether remotely creating branches will be denied # in the repository. By default this is allowed. # # --- Command line refname="$1" oldrev="$2" newrev="$3" # --- Safety check if [ -z "$GIT_DIR" ]; then echo "Don't run this script from the command line." >&2 echo " (if you want, you could supply GIT_DIR then run" >&2 echo " $0 )" >&2 exit 1 fi if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then echo "usage: $0 " >&2 exit 1 fi # --- Config allowunannotated=$(git config --bool hooks.allowunannotated) allowdeletebranch=$(git config --bool hooks.allowdeletebranch) denycreatebranch=$(git config --bool hooks.denycreatebranch) allowdeletetag=$(git config --bool hooks.allowdeletetag) allowmodifytag=$(git config --bool hooks.allowmodifytag) # check for no description projectdesc=$(sed -e '1q' "$GIT_DIR/description") case "$projectdesc" in "Unnamed repository"* | "") echo "*** Project description file hasn't been set" >&2 exit 1 ;; esac # --- Check types # if $newrev is 0000...0000, it's a commit to delete a ref. zero="0000000000000000000000000000000000000000" if [ "$newrev" = "$zero" ]; then newrev_type=delete else newrev_type=$(git cat-file -t $newrev) fi case "$refname","$newrev_type" in refs/tags/*,commit) # un-annotated tag short_refname=${refname##refs/tags/} if [ "$allowunannotated" != "true" ]; then echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2 echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2 exit 1 fi ;; refs/tags/*,delete) # delete tag if [ "$allowdeletetag" != "true" ]; then echo "*** Deleting a tag is not allowed in this repository" >&2 exit 1 fi ;; refs/tags/*,tag) # annotated tag if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1 then echo "*** Tag '$refname' already exists." >&2 echo "*** Modifying a tag is not allowed in this repository." >&2 exit 1 fi ;; refs/heads/*,commit) # branch if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then echo "*** Creating a branch is not allowed in this repository" >&2 exit 1 fi ;; refs/heads/*,delete) # delete branch if [ "$allowdeletebranch" != "true" ]; then echo "*** Deleting a branch is not allowed in this repository" >&2 exit 1 fi ;; refs/remotes/*,commit) # tracking branch ;; refs/remotes/*,delete) # delete tracking branch if [ "$allowdeletebranch" != "true" ]; then echo "*** Deleting a tracking branch is not allowed in this repository" >&2 exit 1 fi ;; *) # Anything else (is there anything else?) echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2 exit 1 ;; esac # --- Finished exit 0 ================================================ FILE: fixtures/server/tmp/test.git/info/exclude ================================================ # git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~ ================================================ FILE: fixtures/server/tmp/test.git/refs/heads/master ================================================ 0e60b9add392cd124fbf8e994bdbbde7a3192572 ================================================ FILE: package.json ================================================ { "name": "node-git-server", "version": "1.0.0", "description": "🎡 A configurable git server written in Node.js", "author": "Gabriel J. Csapo ", "contributors": [ { "name": "echopoint", "email": "echopoint@tutanota.com" }, { "name": "Buj Itself", "email": "primary@buj-dev.site" } ], "license": "MIT", "bugs": { "url": "https://github.com/gabrielcsapo/node-git-server/issues" }, "homepage": "https://github.com/gabrielcsapo/node-git-server#readme", "repository": { "type": "git", "url": "git+https://github.com/gabrielcsapo/node-git-server.git" }, "main": "dist/index.js", "engine": { "node": ">= 16" }, "scripts": { "lint": "eslint .", "test": "vitest src/*.test.ts", "build": "echo \"\" > ./build-complete.meta && tsc", "prepublish": "npm run build", "coverage": "vitest --coverage", "install": "( [ -f ./git-package.meta ] && [ ! -f ./build-complete.meta ] && echo \"\" > ./build-complete.meta && npm install . && tsc ) || echo \"\" > ./build-complete.meta", "prepare": "husky install" }, "dependencies": { "through": "^2.3.8" }, "devDependencies": { "@types/node": "^18.0.3", "@types/node-fetch": "^2.6.2", "@types/through": "^0.0.30", "@typescript-eslint/eslint-plugin": "^5.30.5", "@typescript-eslint/parser": "^5.30.5", "eslint": "^8.19.0", "eslint-config-prettier": "^8.5.0", "eslint-plugin-prettier": "^4.2.1", "husky": "^8.0.1", "node-fetch": "^3.2.6", "prettier": "^2.7.1", "typescript": "^4.7.4", "vitest": "^0.18.0" }, "volta": { "node": "16.15.1" } } ================================================ FILE: src/git.test.ts ================================================ import fs from 'fs'; import path from 'path'; import { spawn, exec, SpawnOptionsWithoutStdio } from 'child_process'; import http from 'http'; import { Git } from './git'; const wrapCallback = (func: { (callback: any): void }) => { return new Promise((resolve) => { func(resolve); }); }; describe('git', () => { test('create, push to, and clone a repo', async () => { expect.assertions(11); let lastCommit: string; const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; const server = http .createServer((req, res) => { repos.handle(req, res); }) .listen(port); repos.on('push', (push) => { expect(push.repo).toBe('xyz/doom'); expect(push.commit).toBe(lastCommit); expect(push.branch).toBe('master'); expect(push.headers.host).toBe('localhost:' + port); expect(push.method).toBe('POST'); expect(push.url).toBe('/xyz/doom/git-receive-pack'); push.accept(); }); await wrapCallback((callback: () => void) => { repos.mkdir('xyz'); callback(); }); await wrapCallback((callback: () => void) => { repos.create('xyz/doom', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on('exit', () => { exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => { lastCommit = stdout.split(/\s+/)[1]; callback(); }); }); }); await wrapCallback((callback: () => void) => { spawn( 'git', ['push', 'http://localhost:' + port + '/xyz/doom', 'master'], { cwd: srcDir } ).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['clone', 'http://localhost:' + port + '/xyz/doom'], { cwd: dstDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); const ex = fs.existsSync(dstDir + '/doom/a.txt'); expect(ex).toBeTruthy(); server.close(); }); test('create, push to, and clone a repo successful', async () => { expect.assertions(8); const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; const server = http.createServer((req, res) => { repos.handle(req, res); }); server.listen(port); repos.on('push', (push) => { expect(push.repo).toBe('doom'); push.accept(); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => { expect(!err).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on( 'exit', (code) => { expect(code).toBe(0); callback(); } ); }); await wrapCallback((callback: () => void) => { spawn('git', ['push', 'http://localhost:' + port + '/doom', 'master'], { cwd: srcDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['clone', 'http://localhost:' + port + '/doom'], { cwd: dstDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.stat(dstDir + '/doom/a.txt', (ex) => { expect(!ex).toBeTruthy(); callback(); }); }); server.close(); }); test('clone into programatic directories', async () => { expect.assertions(19); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const targetDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); fs.mkdirSync(targetDir, '0700'); const server = new Git((dir?: string) => { expect(dir).toBe('doom.git'); return path.join(targetDir, dir || ''); }); server.listen(port); server.on('push', (push) => { expect(push.repo).toBe('doom.git'); push.accept(); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => { expect(!err).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn( 'git', ['push', 'http://localhost:' + port + '/doom.git', 'master'], { cwd: srcDir, } ).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['clone', 'http://localhost:' + port + '/doom.git'], { cwd: dstDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.stat(dstDir + '/doom/a.txt', (ex) => { expect(!ex).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { fs.stat(targetDir + '/doom.git/HEAD', (ex) => { expect(!ex).toBeTruthy(); callback(); }); }); server.close(); }); test('test tagging', async () => { expect.assertions(27); const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; let lastCommit: string; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; const server = http.createServer((req, res) => { repos.handle(req, res); }); server.listen(port); repos.on('push', (push) => { expect(push.repo).toBe('doom'); expect(push.commit).toBe(lastCommit); expect(push.branch).toBe('master'); expect(push.headers.host).toBe('localhost:' + port); expect(push.method).toBe('POST'); expect(push.url).toBe('/doom/git-receive-pack'); push.accept(); }); let firstTag = true; repos.on('tag', (tag) => { expect(tag.repo).toBe('doom'); expect(tag.version).toBe('0.0.' + (firstTag ? 1 : 2)); expect(tag.headers.host).toBe('localhost:' + port); expect(tag.method).toBe('POST'); expect(tag.url).toBe('/doom/git-receive-pack'); tag.accept(); firstTag = false; }); await wrapCallback((callback: () => void) => { repos.create('doom', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => { expect(!err).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on( 'exit', (code) => { expect(code).toBe(0); callback(); } ); }); await wrapCallback((callback: () => void) => { spawn('git', ['tag', '0.0.1'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'efgh', (err) => { expect(!err).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on('exit', () => { exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => { lastCommit = stdout.split(/\s+/)[1]; callback(); }); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['tag', '0.0.2'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn( 'git', ['push', '--tags', 'http://localhost:' + port + '/doom', 'master'], { cwd: srcDir } ).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['clone', 'http://localhost:' + port + '/doom'], { cwd: dstDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.exists(dstDir + '/doom/a.txt', (ex) => { expect(ex).toBeTruthy(); callback(); }); }); server.close(); }); describe('repos list', () => { const workingRepoDir = path.resolve( __dirname, '..', 'fixtures', 'server', 'tmp' ); const notWorkingRepoDir = path.resolve( __dirname, '..', 'fixtures', 'server', 'temp' ); test('should return back with one directory in server', async () => { expect.assertions(2); await new Promise((resolve) => { const repos = new Git(workingRepoDir, { autoCreate: true, }); repos.list((err, results) => { expect(err).toBeFalsy(); expect(['test.git']).toEqual(results); resolve('passed'); }); }); }, 15000); test('should return back error directory does not exist', async () => { expect.assertions(2); await new Promise((resolve) => { const repos = new Git(notWorkingRepoDir, { autoCreate: true, }); repos.list((err, results) => { expect(err !== null).toBeTruthy(); expect(results === undefined).toBeTruthy(); resolve('passed'); }); }); }); }); test('create, push to, and clone a repo reject', async () => { expect.assertions(12); function _spawn( cmd: string, args: any[] | readonly string[] | undefined, opts: SpawnOptionsWithoutStdio | undefined ) { const ps = spawn(cmd, args, opts); ps.on('error', (err) => { console.error( // eslint-disable-line err.message + ' while executing: ' + cmd + ' ' + args?.join(' ') ); }); return ps; } let lastCommit: string; const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; const server = http.createServer((req, res) => { repos.handle(req, res); }); server.listen(port); repos.on('push', (push) => { expect(push.repo).toBe('doom'); expect(push.commit).toBe(lastCommit); expect(push.branch).toBe('master'); expect(push.headers.host).toBe('localhost:' + port); expect(push.method).toBe('POST'); expect(push.url).toBe('/doom/git-receive-pack'); push.reject(500, 'ACCESS DENIED'); }); await wrapCallback((callback: () => void) => { repos.create('doom', () => { callback(); }); }); await wrapCallback((callback: () => void) => { _spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', (err) => { expect(!err).toBeTruthy(); callback(); }); }); await wrapCallback((callback: () => void) => { _spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { _spawn('git', ['commit', '-am', 'a!!'], { cwd: srcDir }).on( 'exit', () => { exec('git log | head -n1', { cwd: srcDir }, (err, stdout) => { lastCommit = stdout.split(/\s+/)[1]; callback(); }); } ); }); await wrapCallback((callback: () => void) => { _spawn('git', ['push', 'http://localhost:' + port + '/doom', 'master'], { cwd: srcDir, }).on('exit', (code) => { expect(code).not.toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { const glog = _spawn('git', ['log'], { cwd: repoDir + '/doom.git', }); glog.on('exit', (code) => { expect(code).toBe(128); callback(); }); let data = ''; glog.stderr.on('data', (buf) => (data += buf)); glog.stderr.on('end', () => { const res = /fatal: bad default revision 'HEAD'/.test(data) || /fatal: your current branch 'master' does not have any commits yet/.test( data ); expect(res).toBeTruthy(); }); }); server.close(); }); test('create git server via listen() command', async () => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; expect(repos.listen(port)).toBe(repos); await wrapCallback((callback: () => void) => { spawn('git', ['clone', 'http://localhost:' + port + '/doom'], { cwd: dstDir, }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); repos.close(); }); test('should return promise that resolves when server is closed if no callback specified', async () => { await new Promise((resolve) => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; fs.mkdirSync(repoDir, '0700'); const repos = new Git(repoDir); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.listen(port, undefined, () => { repos.close().then(() => { resolve('passed'); }); }); }); }); test('should be able to protect certain routes', async () => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, authenticate: ({ type, repo, user }, next) => { if (type === 'fetch' && repo === 'doom') { user((username, password) => { if (username == 'root' && password == 'root') { next(); } else { next(new Error('that is not the correct password')); } }); } else { next(new Error('that is not the correct password')); } }, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.listen(port); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:root@localhost:${port}/doom.git`], { cwd: dstDir } ); clone.on('close', function (code) { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:world@localhost:${port}/doom.git doom1`], { cwd: dstDir } ); let error = ''; clone.stderr.on('data', (d) => { error += d.toString('utf8'); }); clone.on('close', function (code) { expect(error).toBe( `Cloning into 'doom.git doom1'...\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\n` ); expect(code).toBe(128); callback(); }); }); repos.close(); }); test('should be able to access headers in authenticate', async () => { expect.assertions(13); const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, authenticate: ({ type, repo, user, headers }, next) => { if (type === 'fetch' && repo === 'doom') { expect(headers['host']).toBeTruthy(); expect(headers['user-agent']).toBeTruthy(); expect(headers['accept']).toBeTruthy(); expect(headers['pragma']).toBeTruthy(); expect(headers['accept-encoding']).toBeTruthy(); user((username, password) => { if (username == 'root' && password == 'root') { next(); } else { next(new Error('that is not the correct password')); } }); } else { next(new Error('that is not the correct password')); } }, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.listen(port); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:root@localhost:${port}/doom.git`], { cwd: dstDir } ); clone.on('close', function (code) { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:world@localhost:${port}/doom.git doom1`], { cwd: dstDir } ); let error = ''; clone.stderr.on('data', (d) => { error += d.toString('utf8'); }); clone.on('close', function (code) { expect(error).toBe( `Cloning into 'doom.git doom1'...\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\n` ); expect(code).toBe(128); callback(); }); }); repos.close(); }); test('should be able to protect certain routes with a promised authenticate', async () => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, authenticate: ({ type, repo, user }) => { return new Promise(function (resolve, reject) { if (type === 'fetch' && repo === 'doom') { user((username, password) => { if (username == 'root' && password == 'root') { return resolve(void 0); } else { return reject('that is not the correct password'); } }); } else { return reject('that is not the correct password'); } }); }, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.listen(port); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:root@localhost:${port}/doom.git`], { cwd: dstDir } ); clone.on('close', function (code) { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { const clone = spawn( 'git', ['clone', `http://root:world@localhost:${port}/doom.git doom1`], { cwd: dstDir } ); let error = ''; clone.stderr.on('data', (d) => { error += d.toString('utf8'); }); clone.on('close', function (code) { expect(error).toBe( `Cloning into 'doom.git doom1'...\nfatal: unable to access 'http://localhost:${port}/doom.git doom1/': URL using bad/illegal format or missing URL\n` ); expect(code).toBe(128); callback(); }); }); repos.close(); }); test('should be able to send custom messages to git client (main stream)', async () => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.on('push', (push) => { push.log(' '); push.log('Have a great day!'); push.log(' '); push.accept(); }); repos.listen(port); await wrapCallback((callback: () => void) => { repos.create('doom', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-m', 'a!!'], { cwd: srcDir }).on('exit', () => { callback(); }); }); await wrapCallback((callback: () => void) => { const logs: any[] = []; const push = spawn( 'git', ['push', 'http://localhost:' + port + '/doom.git', 'master'], { cwd: srcDir } ); push.stdout.on('data', (data) => { if (data.toString() !== '') { logs.push(data.toString()); } }); push.stderr.on('data', (data) => { if (data.toString() !== '') { logs.push(data.toString()); } }); push.on('exit', () => { expect( logs.join(' ').indexOf('remote: Have a great day!') > -1 ).toBeTruthy(); callback(); }); }); repos.close(); }); test('should be able to send custom messages to git client (response stream)', async () => { const repoDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString( 16 )}`; const srcDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; const dstDir = `/tmp/${Math.floor(Math.random() * (1 << 30)).toString(16)}`; fs.mkdirSync(repoDir, '0700'); fs.mkdirSync(srcDir, '0700'); fs.mkdirSync(dstDir, '0700'); const repos = new Git(repoDir, { autoCreate: true, }); const port = Math.floor(Math.random() * ((1 << 16) - 1e4)) + 1e4; repos.on('push', (push) => { console.log(`push ${push.repo}/${push.commit}`); // eslint-disable-line push.on('response', (stream: { log: (arg0: string) => void }) => { stream.log(' '); stream.log('Have a great day!'); stream.log(' '); }); push.accept(); }); repos.listen(port); await wrapCallback((callback: () => void) => { repos.create('doom', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['init'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { fs.writeFile(srcDir + '/a.txt', 'abcd', () => { callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['add', 'a.txt'], { cwd: srcDir }).on('exit', (code) => { expect(code).toBe(0); callback(); }); }); await wrapCallback((callback: () => void) => { spawn('git', ['commit', '-m', 'a!!'], { cwd: srcDir }).on('exit', () => { callback(); }); }); await wrapCallback((callback: () => void) => { const logs: any[] = []; const push = spawn( 'git', ['push', 'http://localhost:' + port + '/doom.git', 'master'], { cwd: srcDir } ); push.stdout.on('data', (data) => { if (data.toString() !== '') { logs.push(data.toString()); } }); push.stderr.on('data', (data) => { if (data.toString() !== '') { logs.push(data.toString()); } }); push.on('exit', () => { expect( logs.join(' ').indexOf('remote: Have a great day!') > -1 ).toBeTruthy(); callback(); }); }); repos.close(); }); }); ================================================ FILE: src/git.ts ================================================ import fs from 'fs'; import path from 'path'; import http, { ServerOptions } from 'http'; import https from 'https'; import url from 'url'; import qs from 'querystring'; import { HttpDuplex } from './http-duplex'; import { spawn } from 'child_process'; import { EventEmitter } from 'events'; import { parseGitName, createAction, infoResponse, basicAuth, noCache, } from './util'; import { ServiceString } from './types'; const services = ['upload-pack', 'receive-pack']; interface GitServerOptions extends ServerOptions { type: 'http' | 'https'; } export interface GitOptions { autoCreate?: boolean; authenticate?: ( options: GitAuthenticateOptions, callback: (error?: Error) => void | undefined ) => void | Promise | undefined; checkout?: boolean; } export interface GitAuthenticateOptions { type: string; repo: string; user: (() => Promise<[string | undefined, string | undefined]>) & (( callback: ( username?: string | undefined, password?: string | undefined ) => void ) => void); headers: http.IncomingHttpHeaders; } /** * An http duplex object (see below) with these extra properties: */ export interface TagData extends HttpDuplex { repo: string; // The string that defines the repo commit: string; // The string that defines the commit sha version: string; // The string that defines the tag being pushed } /** * Is a http duplex object (see below) with these extra properties */ export interface PushData extends HttpDuplex { repo: string; // The string that defines the repo commit: string; // The string that defines the commit sha branch: string; // The string that defines the branch } /** * an http duplex object (see below) with these extra properties */ export interface FetchData extends HttpDuplex { repo: string; // The string that defines the repo commit: string; // The string that defines the commit sha } /** * an http duplex object (see below) with these extra properties */ export interface InfoData extends HttpDuplex { repo: string; // The string that defines the repo } /** * an http duplex object (see below) with these extra properties */ export interface HeadData extends HttpDuplex { repo: string; // The string that defines the repo } export interface GitEvents { /** * @example * repos.on('push', function (push) { ... } * * Emitted when somebody does a `git push` to the repo. * * Exactly one listener must call `push.accept()` or `push.reject()`. If there are * no listeners, `push.accept()` is called automatically. **/ on(event: 'push', listener: (push: PushData) => void): this; /** * @example * repos.on('tag', function (tag) { ... } * * Emitted when somebody does a `git push --tags` to the repo. * Exactly one listener must call `tag.accept()` or `tag.reject()`. If there are * No listeners, `tag.accept()` is called automatically. **/ on(event: 'tag', listener: (tag: TagData) => void): this; /** * @example * repos.on('fetch', function (fetch) { ... } * * Emitted when somebody does a `git fetch` to the repo (which happens whenever you * do a `git pull` or a `git clone`). * * Exactly one listener must call `fetch.accept()` or `fetch.reject()`. If there are * no listeners, `fetch.accept()` is called automatically. **/ on(event: 'fetch', listener: (fetch: FetchData) => void): this; /** * @example * repos.on('info', function (info) { ... } * * Emitted when the repo is queried for info before doing other commands. * * Exactly one listener must call `info.accept()` or `info.reject()`. If there are * no listeners, `info.accept()` is called automatically. **/ on(event: 'info', listener: (info: InfoData) => void): this; /** * @example * repos.on('head', function (head) { ... } * * Emitted when the repo is queried for HEAD before doing other commands. * * Exactly one listener must call `head.accept()` or `head.reject()`. If there are * no listeners, `head.accept()` is called automatically. * **/ on(event: 'head', listener: (head: HeadData) => void): this; } export class Git extends EventEmitter implements GitEvents { dirMap: (dir?: string) => string; authenticate: | (( options: GitAuthenticateOptions, callback: (error?: Error) => void | undefined ) => void | Promise | undefined) | undefined; autoCreate: boolean; checkout: boolean | undefined; server: https.Server | http.Server | undefined; /** * * Handles invoking the git-*-pack binaries * @param repoDir - Create a new repository collection from the directory `repoDir`. `repoDir` should be entirely empty except for git repo directories. If `repoDir` is a function, `repoDir(repo)` will be used to dynamically resolve project directories. The return value of `repoDir(repo)` should be a string path specifying where to put the string `repo`. Make sure to return the same value for `repo` every time since `repoDir(repo)` will be called multiple times. * @param options - options that can be applied on the new instance being created * @param options.autoCreate - By default, repository targets will be created if they don't exist. You can disable that behavior with `options.autoCreate = true` * @param options.authenticate - a function that has the following arguments ({ type, repo, username, password, headers }, next) and will be called when a request comes through if set * authenticate: ({ type, repo, username, password, headers }, next) => { console.log(type, repo, username, password); next(); } // alternatively you can also pass authenticate a promise authenticate: ({ type, repo, username, password, headers }, next) => { console.log(type, repo, username, password); return new Promise((resolve, reject) => { if(username === 'foo') { return resolve(); } return reject("sorry you don't have access to this content"); }); } * @param options.checkout - If `opts.checkout` is true, create and expected checked-out repos instead of bare repos */ constructor( repoDir: string | ((dir?: string) => string), options: GitOptions = {} ) { super(); if (typeof repoDir === 'function') { this.dirMap = repoDir; } else { this.dirMap = (dir?: string): string => { return path.normalize( (dir ? path.join(repoDir, dir) : repoDir) as string ); }; } if (options.authenticate) { this.authenticate = options.authenticate; } this.autoCreate = options.autoCreate === false ? false : true; this.checkout = options.checkout; } /** * Get a list of all the repositories * @param {Function} callback function to be called when repositories have been found `function(error, repos)` */ list(callback: (error: Error | undefined, repos?: string[]) => void): void; list(): Promise; list( callback?: (error: Error | undefined, repos?: string[]) => void ): Promise | void { const execf = (res: (repos: string[]) => void, rej: (err: Error) => void) => fs.readdir(this.dirMap(), (error, results) => { if (error) return rej(error); const repos = results.filter((r) => { return r.substring(r.length - 3, r.length) == 'git'; }, []); res(repos); }); if (callback) return execf( (repos) => callback(void 0, repos), (err) => callback(err, void 0) ); else return new Promise((res, rej) => execf(res, rej)); } /** * Find out whether `repoName` exists in the callback `cb(exists)`. * @param repo - name of the repo * @param callback - function to be called when finished */ exists(repo: string): boolean { return fs.existsSync(this.dirMap(repo)); } /** * Create a subdirectory `dir` in the repo dir with a callback. * @param dir - directory name * @param callback - callback to be called when finished */ mkdir(dir: string) { fs.mkdirSync(path.dirname(dir), { recursive: true }); } /** * Create a new bare repository `repoName` in the instance repository directory. * @param repo - the name of the repo * @param callback - Optionally get a callback `cb(err)` to be notified when the repository was created. */ create(repo: string, callback: (error?: Error) => void) { function next(self: Git) { let ps; let _error = ''; const dir = self.dirMap(repo); if (self.checkout) { ps = spawn('git', ['init', dir]); } else { ps = spawn('git', ['init', '--bare', dir]); } ps.stderr.on('data', function (chunk: string) { _error += chunk; }); ps.on('exit', (code) => { if (!callback) { return; } else if (code) { callback(new Error(_error)); } else { callback(); } }); } if (typeof callback !== 'function') callback = () => { return; }; if (!/\.git$/.test(repo)) repo += '.git'; const exists = this.exists(repo); if (!exists) { this.mkdir(repo); } next(this); } /** * returns the typeof service being process. This will respond with either fetch or push. * @param service - the service type */ getType(service: string): string { switch (service) { case 'upload-pack': return 'fetch'; case 'receive-pack': return 'push'; default: return 'unknown'; } } /** * Handle incoming HTTP requests with a connect-style middleware * @param http request object * @param http response object */ handle(req: http.IncomingMessage, res: http.ServerResponse) { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; const handlers = [ (req: http.IncomingMessage, res: http.ServerResponse) => { if (req.method !== 'GET') return false; // eslint-disable-next-line @typescript-eslint/no-this-alias const u = url.parse(req?.url || ''); const m = u.pathname?.match(/\/(.+)\/info\/refs$/); if (!m) return false; if (/\.\./.test(m[1])) return false; const repo = m[1]; const params = qs.parse(u?.query || ''); if (!params.service || typeof params.service !== 'string') { res.statusCode = 400; res.end('service parameter required'); return; } const service = params.service.replace(/^git-/, ''); if (services.indexOf(service) < 0) { res.statusCode = 405; res.end('service not available'); return; } const repoName = parseGitName(m[1]); const next = (error?: Error | void) => { if (error) { res.setHeader('Content-Type', 'text/plain'); res.setHeader( 'WWW-Authenticate', 'Basic realm="authorization needed"' ); res.writeHead(401); res.end(typeof error === 'string' ? error : error.toString()); return; } else { return infoResponse(this, repo, service as ServiceString, req, res); } }; // check if the repo is authenticated if (this.authenticate) { const type = this.getType(service); const headers = req.headers; const user = ( callback?: (username?: string, password?: string) => void ) => callback ? basicAuth(req, res, callback) : new Promise<[string | undefined, string | undefined]>( (resolve) => basicAuth(req, res, (u, p) => resolve([u, p])) ); const promise = this.authenticate( { type, repo: repoName, user: user as unknown as GitAuthenticateOptions['user'], headers, }, (error?: Error) => { return next(error); } ); if (promise instanceof Promise) { return promise.then(next).catch(next); } } else { return next(); } }, (req: http.IncomingMessage, res: http.ServerResponse) => { if (req.method !== 'GET') return false; const u = url.parse(req.url || ''); const m = u.pathname?.match(/^\/(.+)\/HEAD$/); if (!m) return false; if (/\.\./.test(m[1])) return false; const repo = m[1]; const next = () => { const file = this.dirMap(path.join(m[1], 'HEAD')); const exists = this.exists(file); if (exists) { fs.createReadStream(file).pipe(res); } else { res.statusCode = 404; res.end('not found'); } }; const exists = this.exists(repo); const anyListeners = self.listeners('head').length > 0; const dup = new HttpDuplex(req, res); dup.exists = exists; dup.repo = repo; dup.cwd = this.dirMap(repo); dup.accept = dup.emit.bind(dup, 'accept'); dup.reject = dup.emit.bind(dup, 'reject'); dup.once('reject', (code: number) => { dup.statusCode = code || 500; dup.end(); }); if (!exists && self.autoCreate) { dup.once('accept', (dir: string) => { self.create(dir || repo, next); }); self.emit('head', dup); if (!anyListeners) dup.accept(); } else if (!exists) { res.statusCode = 404; res.setHeader('content-type', 'text/plain'); res.end('repository not found'); } else { dup.once('accept', next); self.emit('head', dup); if (!anyListeners) dup.accept(); } }, (req: http.IncomingMessage, res: http.ServerResponse) => { if (req.method !== 'POST') return false; const m = req.url?.match(/\/(.+)\/git-(.+)/); if (!m) return false; if (/\.\./.test(m[1])) return false; const repo = m[1], service = m[2]; if (services.indexOf(service) < 0) { res.statusCode = 405; res.end('service not available'); return; } res.setHeader( 'content-type', 'application/x-git-' + service + '-result' ); noCache(res); const action = createAction( { repo: repo, service: service as ServiceString, cwd: self.dirMap(repo), }, req, res ); action.on('header', () => { const evName = action.evName; if (evName) { const anyListeners = self.listeners(evName).length > 0; self.emit(evName, action); if (!anyListeners) action.accept(); } }); }, (req: http.IncomingMessage, res: http.ServerResponse) => { if (req.method !== 'GET' && req.method !== 'POST') { res.statusCode = 405; res.end('method not supported'); } else { return false; } }, (req: http.IncomingMessage, res: http.ServerResponse) => { res.statusCode = 404; res.end('not found'); }, ]; res.setHeader('connection', 'close'); (function next(ix) { const x = handlers[ix].call(self, req, res); if (x === false) next(ix + 1); })(0); } /** * starts a git server on the given port * @param port - the port to start the server on * @param options - the options to add extended functionality to the server * @param options.type - this is either https or http (the default is http) * @param options.key - private key in PEM format for the https server * @param options.cert - cert chains in PEM format for the https server * @param callback - the function to call when server is started or error has occurred */ listen(port: number, options?: GitServerOptions, callback?: () => void): Git { if (!options) { options = { type: 'http' }; } const createServer = options.type == 'http' ? http.createServer : https.createServer.bind(this, options); this.server = createServer((req, res) => { this.handle(req, res); }); this.server.listen(port, callback); return this; } /** * closes the server instance * @param will resolve or reject when the server closes or fails to close. */ close(): Promise { return new Promise((resolve, reject) => { this.server?.close((err) => { err ? reject(err) : resolve('Success'); }); }); } } ================================================ FILE: src/http-duplex.test.ts ================================================ import { HttpDuplex } from './http-duplex'; import http, { Server } from 'http'; import fetch from 'node-fetch'; import { readFileSync } from 'fs'; import { AddressInfo } from 'net'; // eslint-disable-next-line no-undef const selfSrc = readFileSync(__filename); declare global { interface Object { serialize(): string; filterKeys(keys: string): object; } interface String { format(...args: any[]): string; streamlineLineEndings(ending?: string): string; streamlineSpace(): string; streamline(ending?: string): string; } } Object.prototype.serialize = (): string => { return JSON.stringify(this, null, 4); }; Object.prototype.filterKeys = function (key: string) { Object.keys(this).forEach((i) => { if (i == key) delete (this as any)[i]; }); return this; }; String.prototype.format = function () { // eslint-disable-next-line prefer-rest-params const args = Array.from(arguments); return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; String.prototype.streamlineLineEndings = function (ending = '\n') { return this.replace(/[\r\n,\r,\n]+/g, ending); }; String.prototype.streamlineSpace = function () { return this.replace(/[\f\t\v ]{2,}/g, ' '); }; String.prototype.streamline = function (ending = '\n') { return this.streamlineSpace().streamlineLineEndings(ending); }; describe('http-duplex', () => { let server: Server; beforeEach(() => { console.log('create server'); server = http.createServer(function (req, res) { const dup = new HttpDuplex(req, res); console.log(dup.method + ' ' + dup.url); // eslint-disable-line switch (dup.url) { case '/': dup.setHeader('content-type', 'text/plain'); if (dup.method === 'POST') { dup.end(dup.headers['content-length']); } else { dup.end(readFileSync(__filename)); } break; case '/info': if (dup.method == 'GET') { dup.setHeader('content-type', 'text/plain'); const output = ( 'Method: {0}\n' + 'Path: {1}\n' + 'Status: {2}\n' + 'Http Version 1: {3}\n' + 'Http Version 2: {4}\n' + 'Headers: \n{5}\n' + 'Trailers: {6}\n' + 'Complete: {7}\n' + 'Readable: {8}\n' + 'Writeable: {9}\n' + 'Connection: {10}\n' + 'Socket: {11}\n' ).format( dup.method, dup.url, dup.statusCode, dup.httpVersion, '{0}.{1}'.format(dup.httpVersionMajor, dup.httpVersionMinor), JSON.stringify(dup.headers), JSON.stringify(dup.trailers), dup.complete, dup.readable, dup.writable, dup.connection, dup.socket ); dup.end(output.streamline()); } else { dup.statusCode = 400; dup.end('Bad Request'); } break; default: dup.statusCode = 404; dup.end("File doesn't exist"); break; } }); server.listen(); }); afterEach(() => { server.close(); }); test('should be able to handle requests', async () => { expect.assertions(3); await new Promise((resolve) => { server.on('error', (e) => { console.log('error', e); }); server.on('listening', async function () { const { port } = server.address() as AddressInfo; const u = `http://localhost:${port}/`; const response = await fetch(u); const body = await response.text(); expect(String(body)).toBe(String(selfSrc)); const response1 = await fetch(u, { method: 'POST', body: 'beep boop\n', headers: { 'Content-Type': 'text/plain' }, }); const body1 = await response1.text(); expect(body1).toBe('10'); const response2 = await fetch(u + 'info'); const body2 = await response2.text(); expect(String(body2.streamline())).toMatchInlineSnapshot(` "Method: GET Path: /info Status: 200 Http Version 1: 1.1 Http Version 2: 1.1 Headers: {\\"accept\\":\\"*/*\\" \\"user-agent\\":\\"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)\\" \\"accept-encoding\\":\\"gzip deflate\\" \\"connection\\":\\"close\\" \\"host\\":\\"localhost:${port}\\"} Trailers: {} Complete: false Readable: true Writeable: true Connection: [object Object] Socket: [object Object] " `); resolve('passed'); }); }); }); }); ================================================ FILE: src/http-duplex.ts ================================================ import http from 'http'; import EventEmitter from 'events'; export class HttpDuplex extends EventEmitter { setHeader(arg0: string, arg1: string) { throw new Error('Method not implemented.'); } end(reason?: any) { throw new Error('Method not implemented.'); } destroy() { throw new Error('Method not implemented.'); } accept() { throw new Error('Method not implemented.'); } reject(code: number, msg: string) { throw new Error('Method not implemented.'); } /** * A IncomingMessage created by http.Server or http.ClientRequest usually passed as the * first parameter to the 'request' and 'response' events. Implements Readable Stream interface * but may not be a decendant thereof. * @see {@link https://nodejs.org/api/http.html#http_event_request|request} * @see {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage|http.IncomingMessage} * */ req: http.IncomingMessage; /** * Created http.server. Passed as the second parameter to the 'request' event. * The response implements Writable Stream interface but isn't a descendent thereof. * @see {@link https://nodejs.org/api/http.html#http_event_request|request} * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse} */ res: http.ServerResponse; cwd: string | undefined; repo: string | undefined; exists: boolean | undefined; /** * Constructs a proxy object over input and output resulting in a unified stream. * Generally meant to combine request and response streams in the http.request event * @see {@link https://nodejs.org/api/http.html#http_event_request|request} * @see {@link https://nodejs.org/api/http.html#http_class_http_incomingmessage|http.IncomingMessage} * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse} * @example A simple example is shown below ```js http.createServer(function (req, res) { var dup = new HttpDuplex(req, res); res.end("Request: " + req.method + " " + req.url); }).listen(80); ``` */ constructor(input: http.IncomingMessage, output: http.ServerResponse) { super(); this.req = input; this.res = output; // request / input proxy events ['data', 'end', 'error', 'close'].forEach((name) => { this.req.on(name, this.emit.bind(this, name)); }); // respone / output proxy events ['error', 'drain'].forEach((name) => { this.res.on(name, this.emit.bind(this, name)); }); } get complete() { return this.req.complete; } /** * Reference to the underlying socket for the request connection. * @readonly * @see {@link https://nodejs.org/api/http.html#http_request_socket|request.Socket} */ get connection() { return this.req.connection; } /** * Request/response headers. Key-value pairs of header names and values. Header names are always lower-case. * @readonly * @see {@link https://nodejs.org/api/http.html#http_message_headers|message.headers} */ get headers() { return this.req.headers; } /** * Requested HTTP Version sent by the client. Usually either '1.0' or '1.1' * @see {@link https://nodejs.org/api/http.html#http_message_httpversion|message.httpVersion} * @readonly */ get httpVersion() { return this.req.httpVersion; } /** * First integer in the httpVersion string * @see httpVersion * @readonly */ get httpVersionMajor() { return this.req.httpVersionMajor; } /** * Second integer ni the httpVersion string * @see httpVersion * @readonly */ get httpVersionMinor() { return this.req.httpVersionMinor; } /** * Request method of the incoming request. * @see {@link https://nodejs.org/api/http.html#http_event_request|request} * @see {@link https://nodejs.org/api/http.html#http_class_http_serverresponse|http.ServerResponse} * @example 'GET', 'DELETE' * @readonly */ get method() { return this.req.method; } /** * Is this stream readable. * @readonly */ get readable() { return this.req.readable; } /** * net.Socket object associated with the connection. * @see {@link https://nodejs.org/api/net.html#net_class_net_socket|net.Socket} * @readonly */ get socket() { return this.req.socket; } /** * The HTTP status code. Generally assigned before sending headers for a response to a client. * @see {@link https://nodejs.org/api/http.html#http_response_statuscode|response.statusCode} * @example request.statusCode = 404; */ get statusCode() { return this.res.statusCode; } set statusCode(val) { this.res.statusCode = val; } /** * Controls the status message sent to the client as long as an explicit call to response.writeHead() isn't made * If ignored or the value is undefined, the default message corresponding to the status code will be used. * @see {@link https://nodejs.org/api/http.html#http_response_statusmessage|response.statusMessage} * @example request.statusMessage = 'Document Not found'; */ get statusMessage() { return this.res.statusMessage; } set statusMessage(val) { this.res.statusMessage = val; } /** * Request/response trailer headers. Just like {@link headers} except these are only written * after the initial response to the client. * This object is only populated at the 'end' event and only work if a 'transfer-encoding: chunked' * header is sent in the initial response. * @readonly * @see headers * @see addTrailers * @see {@link https://nodejs.org/api/http.html#http_message_trailers|message.trailers} * @see {@link https://nodejs.org/api/http.html#http_response_addtrailers_headers|response.addTrailers} */ get trailers() { return this.req.trailers; } /** * Request URL string. * @example A request made as: * GET /info?check=none HTTP/1.1 * @example Will return the string * '/info?check=none' * @readonly */ get url() { return this.req.url; } // output / response wrapping get writable() { return this.res.writable; } /** * Sends a response header to the client request. Must only be called one time and before calling response.end(). * @param statusCode 3-digit HTTP status code, like 404 * @param statusMessage - An optional human readable status message to send with the status code * @param headers - An object containing the response headers to send * @see {@link https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers|response.writeHead} * @example var content = 'Under Construction...'; * response.writeHead(200, { * 'Content-Length': Buffer.byteLength(content), * 'Content-Type': 'text/plain' * }); * response.end(content); */ writeHead(statusCode: number, statusMessage: string, headers: string[]) { this.res.writeHead(statusCode, statusMessage, headers); return this; } /** * Buffers written data in memory. This data will be flushed when either the uncork or end methods are called. * @see uncork * @see {@link https://nodejs.org/api/stream.html#stream_writable_cork|stream.Writeable.cork} * @example * request.cork(); * request.write('buffer data '); * request.write('before sending '); * request.uncork(); */ cork() { this.res.socket?.cork(); return this; } /** * Flushes all data buffered since cork() was called. * @see cork * @see {@link https://nodejs.org/api/stream.html#stream_writable_uncork|stream.Writeable.uncork} */ uncork() { this.res.socket?.uncork(); return this; } } // proxy request methods ['pause', 'resume', 'setEncoding'].forEach(function (name) { (HttpDuplex.prototype as any)[name] = function () { // eslint-disable-next-line prefer-rest-params return (this.req as any)[name].apply(this.req, Array.from(arguments)); }; }); // proxy respone methods [ 'setDefaultEncoding', 'write', 'end', 'flush', 'writeHeader', 'writeContinue', 'setHeader', 'getHeader', 'removeHeader', 'addTrailers', ].forEach(function (name) { (HttpDuplex.prototype as any)[name] = function () { // eslint-disable-next-line prefer-rest-params return (this.res as any)[name].apply(this.res, Array.from(arguments)); }; }); /** * Destroys object and it's bound streams */ HttpDuplex.prototype.destroy = function () { this.req.destroy(); this.res.destroy(); }; ================================================ FILE: src/index.ts ================================================ export * from './git'; export * from './http-duplex'; export * from './service'; export * from './types'; export * from './util'; ================================================ FILE: src/service.ts ================================================ import http from 'http'; import zlib from 'zlib'; import through from 'through'; import util from 'util'; import os from 'os'; import { spawn } from 'child_process'; import { HttpDuplex } from './http-duplex'; import { ServiceString } from './types'; import { packSideband } from './util'; const headerRegex: { [key: string]: string } = { 'receive-pack': '([0-9a-fA-F]+) ([0-9a-fA-F]+) refs\/(heads|tags)\/(.*?)( |00|\u0000)|^(0000)$', // eslint-disable-line 'upload-pack': '^\\S+ ([0-9a-fA-F]+)', }; const decoder: { [key: string]: () => zlib.Gunzip | zlib.Deflate } = { gzip: (): zlib.Gunzip => zlib.createGunzip(), deflate: (): zlib.Deflate => zlib.createDeflate(), }; export interface ServiceOptions { repo: string; cwd: string; service: ServiceString; } export class Service extends HttpDuplex { status: string; repo: string; service: string; cwd: string; logs: string[]; last: string | undefined; commit: string | undefined; evName: string | undefined; username: string | undefined; /** * Handles invoking the git-*-pack binaries * @param opts - options to bootstrap the service object * @param req - http request object * @param res - http response */ constructor( opts: ServiceOptions, req: http.IncomingMessage, res: http.ServerResponse ) { super(req, res); let data = ''; this.status = 'pending'; this.repo = opts.repo; this.service = opts.service; this.cwd = opts.cwd; this.logs = []; const buffered = through().pause(); // stream needed to receive data after decoding, but before accepting const ts = through(); const encoding = req.headers['content-encoding']; if (encoding && decoder[encoding]) { // data is compressed with gzip or deflate req.pipe(decoder[encoding]()).pipe(ts).pipe(buffered); } else { // data is not compressed req.pipe(ts).pipe(buffered); } if (req.headers['authorization']) { const tokens = req.headers['authorization'].split(' '); if (tokens[0] === 'Basic') { const splitHash = Buffer.from(tokens[1], 'base64') .toString('utf8') .split(':'); this.username = splitHash.shift(); } } ts.once('data', (chunk: string) => { data += chunk; const ops = data.match(new RegExp(headerRegex[this.service], 'gi')); if (!ops) return; data = ''; ops.forEach((op) => { let type; const m = op.match(new RegExp(headerRegex[this.service])); if (!m) return; if (this.service === 'receive-pack') { this.last = m[1]; this.commit = m[2]; if (m[3] == 'heads') { type = 'branch'; this.evName = 'push'; } else { type = 'version'; this.evName = 'tag'; } const headers: { [key: string]: string } = { last: this.last, commit: this.commit, }; headers[type] = (this as any)[type] = m[4]; this.emit('header', headers); } else if (this.service === 'upload-pack') { this.commit = m[1]; this.evName = 'fetch'; this.emit('header', { commit: this.commit, }); } }); }); this.once('accept', () => { process.nextTick(() => { const cmd = os.platform() == 'win32' ? ['git', opts.service, '--stateless-rpc', opts.cwd] : ['git-' + opts.service, '--stateless-rpc', opts.cwd]; const ps = spawn(cmd[0], cmd.slice(1)); ps.on('error', (error: Error) => { this.emit( 'error', new Error(`${error.message} running command ${cmd.join(' ')}`) ); }); this.emit('service', ps); const respStream = through( // write (c: any) => { if (this.listeners('response').length === 0) { if (this.logs.length > 0) { while (this.logs.length > 0) { respStream.queue(this.logs.pop()); } } return respStream.queue(c); } // prevent git from sending the close signal if (c.length === 4 && c.toString() === '0000') return; respStream.queue(c); }, // read () => { if (this.listeners('response').length > 0) return; respStream.queue(null); } ); (respStream as any).log = this.log.bind(this); this.emit('response', respStream, function endResponse() { (res as any).queue(Buffer.from('0000')); (res as any).queue(null); }); ps.stdout.pipe(respStream).pipe(res); buffered.pipe(ps.stdin); buffered.resume(); ps.on('exit', () => { if (this.logs.length > 0) { while (this.logs.length > 0) { respStream.queue(this.logs.pop()); } respStream.queue(Buffer.from('0000')); respStream.queue(null); } this.emit('exit'); }); }); }); this.once('reject', function onReject(code: number, msg: string) { res.statusCode = code; res.end(msg); }); } log() { // eslint-disable-next-line prefer-rest-params const _log = util.format(...arguments); const SIDEBAND = String.fromCharCode(2); // PROGRESS const message = `${SIDEBAND}${_log}\n`; const formattedMessage = Buffer.from(packSideband(message)); this.logs.unshift(formattedMessage.toString()); } /** * reject request in flight * @param code - http response code * @param msg - message that should be displayed on the client */ reject(code: number, msg: string) { if (this.status !== 'pending') return; if (msg === undefined && typeof code === 'string') { msg = code; code = 500; } this.status = 'rejected'; this.emit('reject', code || 500, msg); } /** * accepts request to access resource */ accept() { if (this.status !== 'pending') return; this.status = 'accepted'; this.emit('accept'); } } ================================================ FILE: src/types.ts ================================================ export type ServiceString = 'upload-pack' | 'receive-pack'; ================================================ FILE: src/util.test.ts ================================================ import { basicAuth, noCache, parseGitName } from './util'; describe('util', () => { describe('basicAuth', () => { test('should send back basic auth headers', async () => { await new Promise((resolve, reject) => { const headers: any = {}; const req: any = { headers: {}, }; const res: any = { writeHead: function (_code: number) { code = _code; }, setHeader: function (key: string | number, value: any) { headers[key] = value; }, end: function (_status: number) { status = _status; expect(code).toBe(401); expect(headers).toEqual({ 'Content-Type': 'text/plain', 'WWW-Authenticate': 'Basic realm="authorization needed"', }); expect(status).toBe('401 Unauthorized'); resolve('passed'); }, }; let code = 0; let status = 0; basicAuth(req, res, () => { reject('should not have entered this callback'); }); }); }); test('should accept headers and call callback', async () => { await new Promise((resolve) => { const req: any = { headers: { authorization: 'Basic T3BlbjpTZXNhbWU=', }, }; const res: any = {}; basicAuth(req, res, (username, password) => { expect(username).toBe('Open'); expect(password).toBe('Sesame'); resolve('passed'); }); }); }); }); describe('noCache', () => { test('should honor noCache', () => { const headers: any = { 'persisted-header': 'I have been here foreveeeerrr', }; const res: any = { setHeader: function (key: string | number, value: any) { headers[key] = value; }, }; noCache(res); expect(headers).toEqual({ 'persisted-header': 'I have been here foreveeeerrr', expires: 'Fri, 01 Jan 1980 00:00:00 GMT', pragma: 'no-cache', 'cache-control': 'no-cache, max-age=0, must-revalidate', }); }); }); describe('parseGitName', () => { test('should remove .git from repo name', () => { expect(parseGitName('test.git')).toBe('test'); }); test('should remove .git from the end of repo name but not in the middle', () => { expect(parseGitName('test.git.git')).toBe('test.git'); }); test("if .git does not exist in the string, don't remove it", () => { expect(parseGitName('test')).toBe('test'); }); }); }); ================================================ FILE: src/util.ts ================================================ import http from 'http'; import { spawn } from 'child_process'; import { Git } from './git'; import { HttpDuplex } from './http-duplex'; import { Service, ServiceOptions } from './service'; import { ServiceString } from './types'; export function packSideband(s: string): string { const n = (4 + s.length).toString(16); return Array(4 - n.length + 1).join('0') + n + s; } /** * adds headers to the response object to add cache control * @param res - http response */ export function noCache(res: http.ServerResponse) { res.setHeader('expires', 'Fri, 01 Jan 1980 00:00:00 GMT'); res.setHeader('pragma', 'no-cache'); res.setHeader('cache-control', 'no-cache, max-age=0, must-revalidate'); } /** * sets and parses basic auth headers if they exist * @param req - http request object * @param res - http response * @param callback - function(username, password) */ export function basicAuth( req: http.IncomingMessage, res: http.ServerResponse, callback: (username?: string, password?: string) => void ) { if (!req.headers['authorization']) { res.setHeader('Content-Type', 'text/plain'); res.setHeader('WWW-Authenticate', 'Basic realm="authorization needed"'); res.writeHead(401); res.end('401 Unauthorized'); } else { const tokens = req.headers['authorization'].split(' '); if (tokens[0] === 'Basic') { const splitHash = Buffer.from(tokens[1], 'base64') .toString('utf8') .split(':'); const username = splitHash.shift(); const password = splitHash.join(':'); callback(username, password); } } } /** * execute given git operation and respond * @param dup - duplex object to catch errors * @param service - the method that is responding infoResponse (push, pull, clone) * @param repoLocation - the repo path on disk * @param res - http response */ export function serviceRespond( dup: HttpDuplex | Git, service: ServiceString, repoLocation: string, res: http.ServerResponse ) { res.write(packSideband('# service=git-' + service + '\n')); res.write('0000'); const isWin = /^win/.test(process.platform); const cmd = isWin ? ['git', service, '--stateless-rpc', '--advertise-refs', repoLocation] : ['git-' + service, '--stateless-rpc', '--advertise-refs', repoLocation]; const ps = spawn(cmd[0], cmd.slice(1)); ps.on('error', (err) => { dup.emit( 'error', new Error(`${err.message} running command ${cmd.join(' ')}`) ); }); ps.stdout.pipe(res); } /** * sends http response using the appropriate output from service call * @param git - an instance of git object * @param repo - the repository * @param service - the method that is responding infoResponse (push, pull, clone) * @param req - http request object * @param res - http response */ export function infoResponse( git: Git, repo: string, service: ServiceString, req: http.IncomingMessage, res: http.ServerResponse ) { function next() { res.setHeader( 'content-type', 'application/x-git-' + service + '-advertisement' ); noCache(res); serviceRespond(git, service, git.dirMap(repo), res); } const dup = new HttpDuplex(req, res); dup.cwd = git.dirMap(repo); dup.repo = repo; dup.accept = dup.emit.bind(dup, 'accept'); dup.reject = dup.emit.bind(dup, 'reject'); dup.once('reject', (code: number) => { res.statusCode = code || 500; res.end(); }); const anyListeners = git.listeners('info').length > 0; const exists = git.exists(repo); dup.exists = exists; if (!exists && git.autoCreate) { dup.once('accept', () => { git.create(repo, next); }); git.emit('info', dup); if (!anyListeners) dup.accept(); } else if (!exists) { res.statusCode = 404; res.setHeader('content-type', 'text/plain'); res.end('repository not found'); } else { dup.once('accept', next); git.emit('info', dup); if (!anyListeners) dup.accept(); } } /** * parses a git string and returns the repo name * @param repo - the raw repo name containing .git */ export function parseGitName(repo: string): string { const locationOfGit = repo.lastIndexOf('.git'); return repo.slice(0, locationOfGit > 0 ? locationOfGit : repo.length); } /** * responds with the correct service depending on the action * @param opts - options to pass Service * @param req - http request object * @param res - http response */ export function createAction( opts: ServiceOptions, req: http.IncomingMessage, res: http.ServerResponse ): Service { const service = new Service(opts, req, res); // TODO: see if this works or not // Object.keys(opts).forEach((key) => { // service[key] = opts[key]; // }); return service; } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "declaration": true, "declarationMap": true, "lib": ["esnext"], "target": "es2020", "module": "commonjs", "outDir": "dist", "rootDir": "src", "strict": true, "noImplicitAny": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "types": ["node", "vitest/globals", "node-fetch"], "allowJs": true, "checkJs": false }, "include": ["src"] } ================================================ FILE: vitest.config.js ================================================ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { clearMocks: true, globals: true, environment: 'node', testTimeout: 150000, }, }); ================================================ FILE: website/.gitignore ================================================ # Dependencies /node_modules # Production /build # Generated files .docusaurus .cache-loader # Misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: website/README.md ================================================ # Website This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment ``` $ GIT_USER= USE_SSH=true yarn deploy ``` If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. ================================================ FILE: website/babel.config.js ================================================ /* eslint-disable no-undef */ module.exports = { presets: [require.resolve('@docusaurus/core/lib/babel/preset')], }; ================================================ FILE: website/docs/intro.md ================================================ # Introduction ## Install ```bash npm install node-git-server ``` ## Usage ### Simple ```typescript import { Git } from 'node-git-server'; import { join } from 'path'; const port = !process.env.PORT || isNaN(process.env.PORT) ? 7005 : parseInt(process.env.PORT); const repos = new Git(join(__dirname, '../repo'), { autoCreate: true, }); repos.on('push', (push) => { console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`); push.accept(); }); repos.on('fetch', (fetch) => { console.log(`fetch ${fetch.commit}`); fetch.accept(); }); repos.listen(port, () => { console.log(`node-git-server running at http://localhost:${port}`); }); ``` then start up the node-git-server server... ```bash $ node example/index.js node-git-server running at http://localhost:7005 ``` meanwhile... ```bash $ git push http://localhost:7005/beep master Counting objects: 356, done. Delta compression using up to 2 threads. Compressing objects: 100% (133/133), done. Writing objects: 100% (356/356), 46.20 KiB, done. Total 356 (delta 210), reused 355 (delta 210) To http://localhost:7005/beep * [new branch] master -> master ``` ### Sending logs ```typescript import { Git } from 'node-git-server'; import { join } from 'path'; const port = !process.env.PORT || isNaN(process.env.PORT) ? 7005 : parseInt(process.env.PORT); const repos = new Git(join(__dirname, '../repo'), { autoCreate: true, }); repos.on('push', async (push) => { console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`); push.log(); push.log('Hey!'); push.log('Checkout these other repos:'); for (const repo of await repo.list()) { push.log(`- ${repo}`); } push.log(); push.accept(); }); repos.on('fetch', (fetch) => { console.log(`fetch ${fetch.commit}`); fetch.accept(); }); repos.listen(port, () => { console.log(`node-git-server running at http://localhost:${port}`); }); ``` then start up the node-git-server server... ```bash $ node example/index.js node-git-server running at http://localhost:7005 ``` meanwhile... ```bash $ git push http://localhost:7005/beep master Counting objects: 356, done. Delta compression using up to 2 threads. Compressing objects: 100% (133/133), done. Writing objects: 100% (356/356), 46.20 KiB, done. Total 356 (delta 210), reused 355 (delta 210) remote: remote: Hey! remote: Checkout these other repos: remote: - test.git remote: To http://localhost:7005/test 77bb26e..22918d5 master -> master ``` #### Authentication ```typescript import { Git } from 'node-git-server'; import { join } from 'path'; const port = !process.env.PORT || isNaN(process.env.PORT) ? 7005 : parseInt(process.env.PORT); const repos = new Git(join(__dirname, '../repo'), { autoCreate: true, autheficate: ({ type, user }, next) => type == 'push' ? user(([username, password]) => { console.log(username, password); next(); }) : next(), }); repos.on('push', (push) => { console.log(`push ${push.repo}/${push.commit} ( ${push.branch} )`); push.accept(); }); repos.on('fetch', (fetch) => { console.log(`fetch ${fetch.commit}`); fetch.accept(); }); repos.listen(port, () => { console.log(`node-git-server running at http://localhost:${port}`); }); ``` then start up the node-git-server server... ```bash $ node example/index.js node-git-server running at http://localhost:7005 ``` meanwhile... ```bash $ git push http://localhost:7005/beep master Counting objects: 356, done. Delta compression using up to 2 threads. Compressing objects: 100% (133/133), done. Writing objects: 100% (356/356), 46.20 KiB, done. Total 356 (delta 210), reused 355 (delta 210) To http://localhost:7005/beep * [new branch] master -> master ``` ## Example Running the following command will start up a simple http server: ```bash node example/index.js ``` If you want to try using https run the following ```bash node example/index.js --https ``` > When running https with self-signed certs there are two ways to override the git-clients behavior using `git config http.sslVerify false` or `git config --global http.sslCAInfo /path/to/cert.pem` For more information please visit the [docs](http://www.gabrielcsapo.com/node-git-server/code/index.html) ================================================ FILE: website/docusaurus.config.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable no-undef */ // @ts-check // Note: type annotations allow type checking and IDEs autocompletion const path = require('path'); const lightCodeTheme = require('prism-react-renderer/themes/github'); const darkCodeTheme = require('prism-react-renderer/themes/dracula'); /** @type {import('@docusaurus/types').Config} */ const config = { title: 'node-git-server', tagline: '🎡 A configurable git server written in Node.js', url: 'https://gabrielcsapo.github.io', baseUrl: '/node-git-server/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'img/favicon.ico', organizationName: 'gabrielcsapo', projectName: 'node-git-server', plugins: [ [ require.resolve('docusaurus-plugin-search-local'), { highlightSearchTermsOnTargetPage: true, docsRouteBasePath: ['docs', 'api'], }, ], [ 'docusaurus-plugin-typedoc-api', { projectRoot: path.join(__dirname, '..'), packages: ['.'], }, ], ], presets: [ [ '@docusaurus/preset-classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { editUrl: 'https://github.com/gabrielcsapo/node-git-server/edit/main/website/', }, blog: { showReadingTime: true, editUrl: 'https://github.com/gabrielcsapo/node-git-server/edit/main/website/blog/', }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ navbar: { title: 'node-git-server', logo: { alt: 'node-git-server logo', src: 'img/apple-touch-icon.png', }, items: [ { type: 'doc', docId: 'intro', position: 'left', label: 'Documentation', }, { to: 'api', label: 'API', position: 'left', }, { href: 'https://github.com/gabrielcsapo/node-git-server', label: 'GitHub', position: 'right', }, ], }, footer: { style: 'dark', links: [ { title: 'Docs', items: [ { label: 'Getting Started', to: '/docs/intro', }, ], }, { title: 'More', items: [ { label: 'GitHub', href: 'https://github.com/gabrielcsapo/node-git-server', }, ], }, ], copyright: `Copyright © ${new Date().getFullYear()} node-git-server, Inc. Built with Docusaurus.`, }, prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, }, }), }; module.exports = config; ================================================ FILE: website/package.json ================================================ { "name": "node-git-server", "version": "0.0.0", "private": true, "scripts": { "docusaurus": "docusaurus", "start": "docusaurus start", "build": "docusaurus build", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", "serve": "docusaurus serve", "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids" }, "dependencies": { "@docusaurus/core": "2.0.1", "@docusaurus/preset-classic": "2.0.1", "docusaurus-plugin-typedoc-api": "^2.3.0", "@mdx-js/react": "^1.6.21", "@svgr/webpack": "^5.5.0", "clsx": "^1.1.1", "docusaurus-plugin-search-local": "^0.8.2", "file-loader": "^6.2.0", "prism-react-renderer": "^1.2.1", "react": "^17.0.1", "react-dom": "^17.0.1", "url-loader": "^4.1.1" }, "browserslist": { "production": [ ">0.5%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "volta": { "node": "16.15.1" } } ================================================ FILE: website/src/css/custom.css ================================================ /** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ /* You can override the default Infima variables here. */ :root { --ifm-color-primary: #25c2a0; --ifm-color-primary-dark: rgb(33, 175, 144); --ifm-color-primary-darker: rgb(31, 165, 136); --ifm-color-primary-darkest: rgb(26, 136, 112); --ifm-color-primary-light: rgb(70, 203, 174); --ifm-color-primary-lighter: rgb(102, 212, 189); --ifm-color-primary-lightest: rgb(146, 224, 208); --ifm-code-font-size: 95%; } .docusaurus-highlight-code-line { background-color: rgba(0, 0, 0, 0.1); display: block; margin: 0 calc(-1 * var(--ifm-pre-padding)); padding: 0 var(--ifm-pre-padding); } html[data-theme='dark'] .docusaurus-highlight-code-line { background-color: rgba(0, 0, 0, 0.3); } .main-wrapper { display: flex; } ================================================ FILE: website/src/pages/index.js ================================================ import React from 'react'; import clsx from 'clsx'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import styles from './index.module.css'; function HomepageHeader() { const { siteConfig } = useDocusaurusContext(); return (

{siteConfig.title}

{siteConfig.tagline}

Quick Start
); } export default function Home() { const { siteConfig } = useDocusaurusContext(); return ( ); } ================================================ FILE: website/src/pages/index.module.css ================================================ /** * CSS files with the .module.css suffix will be treated as CSS modules * and scoped locally. */ .heroBanner { padding: 4rem 0; text-align: center; position: relative; overflow: hidden; display: flex; width: 100%; height: 100vh; } @media screen and (max-width: 966px) { .heroBanner { padding: 2rem; } } .buttons { display: flex; align-items: center; justify-content: center; } ================================================ FILE: website/static/.nojekyll ================================================