@lbdudc/linea-git 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +47 -2
  2. package/dist/access.d.ts +18 -0
  3. package/dist/access.js +18 -0
  4. package/dist/access.js.map +1 -0
  5. package/dist/auth.d.ts +11 -0
  6. package/dist/auth.js +16 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/changelog/generate.d.ts +18 -0
  9. package/dist/changelog/generate.js +166 -0
  10. package/dist/changelog/generate.js.map +1 -0
  11. package/dist/changelog/index.d.ts +5 -0
  12. package/dist/changelog/index.js +3 -0
  13. package/dist/changelog/index.js.map +1 -0
  14. package/dist/changelog/parse.d.ts +43 -0
  15. package/dist/changelog/parse.js +91 -0
  16. package/dist/changelog/parse.js.map +1 -0
  17. package/dist/changelog/types.d.ts +85 -0
  18. package/dist/changelog/types.js +2 -0
  19. package/dist/changelog/types.js.map +1 -0
  20. package/dist/checkout/credential.d.ts +14 -0
  21. package/dist/checkout/credential.js +29 -0
  22. package/dist/checkout/credential.js.map +1 -0
  23. package/dist/checkout/git.d.ts +78 -0
  24. package/dist/checkout/git.js +191 -0
  25. package/dist/checkout/git.js.map +1 -0
  26. package/dist/checkout/index.d.ts +3 -0
  27. package/dist/checkout/index.js +4 -0
  28. package/dist/checkout/index.js.map +1 -0
  29. package/dist/checkout/sync.d.ts +156 -0
  30. package/dist/checkout/sync.js +211 -0
  31. package/dist/checkout/sync.js.map +1 -0
  32. package/dist/closing.d.ts +1 -0
  33. package/dist/closing.js +14 -0
  34. package/dist/closing.js.map +1 -0
  35. package/dist/config.d.ts +53 -0
  36. package/dist/config.js +40 -0
  37. package/dist/config.js.map +1 -0
  38. package/dist/deletion.d.ts +19 -0
  39. package/dist/deletion.js +27 -0
  40. package/dist/deletion.js.map +1 -0
  41. package/dist/errors.d.ts +26 -0
  42. package/dist/errors.js +47 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/factory.d.ts +20 -0
  45. package/dist/factory.js +46 -0
  46. package/dist/factory.js.map +1 -0
  47. package/dist/github/client.d.ts +44 -0
  48. package/dist/github/client.js +145 -0
  49. package/dist/github/client.js.map +1 -0
  50. package/dist/github/config.d.ts +24 -0
  51. package/dist/github/config.js +11 -0
  52. package/dist/github/config.js.map +1 -0
  53. package/dist/github/provider.d.ts +510 -0
  54. package/dist/github/provider.js +1009 -0
  55. package/dist/github/provider.js.map +1 -0
  56. package/dist/gitlab/client.d.ts +50 -0
  57. package/dist/gitlab/client.js +228 -0
  58. package/dist/gitlab/client.js.map +1 -0
  59. package/dist/gitlab/provider.d.ts +487 -0
  60. package/dist/gitlab/provider.js +719 -0
  61. package/dist/gitlab/provider.js.map +1 -0
  62. package/dist/host.d.ts +27 -0
  63. package/dist/host.js +45 -0
  64. package/dist/host.js.map +1 -0
  65. package/dist/index.d.ts +46 -0
  66. package/dist/index.js +31 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/local/diff.d.ts +3 -0
  69. package/dist/local/diff.js +43 -0
  70. package/dist/local/diff.js.map +1 -0
  71. package/dist/local/git.d.ts +24 -0
  72. package/dist/local/git.js +51 -0
  73. package/dist/local/git.js.map +1 -0
  74. package/dist/local/health.d.ts +36 -0
  75. package/dist/local/health.js +57 -0
  76. package/dist/local/health.js.map +1 -0
  77. package/dist/local/hooks.d.ts +2 -0
  78. package/dist/local/hooks.js +44 -0
  79. package/dist/local/hooks.js.map +1 -0
  80. package/dist/local/http.d.ts +35 -0
  81. package/dist/local/http.js +160 -0
  82. package/dist/local/http.js.map +1 -0
  83. package/dist/local/provider.d.ts +571 -0
  84. package/dist/local/provider.js +1237 -0
  85. package/dist/local/provider.js.map +1 -0
  86. package/dist/local/store.d.ts +136 -0
  87. package/dist/local/store.js +171 -0
  88. package/dist/local/store.js.map +1 -0
  89. package/dist/packages/github-source.d.ts +69 -0
  90. package/dist/packages/github-source.js +133 -0
  91. package/dist/packages/github-source.js.map +1 -0
  92. package/dist/packages/gitlab-source.d.ts +59 -0
  93. package/dist/packages/gitlab-source.js +214 -0
  94. package/dist/packages/gitlab-source.js.map +1 -0
  95. package/dist/packages/index.d.ts +30 -0
  96. package/dist/packages/index.js +45 -0
  97. package/dist/packages/index.js.map +1 -0
  98. package/dist/packages/provider-source.d.ts +34 -0
  99. package/dist/packages/provider-source.js +57 -0
  100. package/dist/packages/provider-source.js.map +1 -0
  101. package/dist/packages/repository-files.d.ts +12 -0
  102. package/dist/packages/repository-files.js +16 -0
  103. package/dist/packages/repository-files.js.map +1 -0
  104. package/dist/provider.d.ts +888 -0
  105. package/dist/provider.js +29 -0
  106. package/dist/provider.js.map +1 -0
  107. package/dist/read-cache.d.ts +5 -0
  108. package/dist/read-cache.js +101 -0
  109. package/dist/read-cache.js.map +1 -0
  110. package/dist/registry/catalog.d.ts +55 -0
  111. package/dist/registry/catalog.js +143 -0
  112. package/dist/registry/catalog.js.map +1 -0
  113. package/dist/registry/kinds.d.ts +21 -0
  114. package/dist/registry/kinds.js +43 -0
  115. package/dist/registry/kinds.js.map +1 -0
  116. package/dist/registry/packages.d.ts +165 -0
  117. package/dist/registry/packages.js +290 -0
  118. package/dist/registry/packages.js.map +1 -0
  119. package/dist/registry/publish.d.ts +35 -0
  120. package/dist/registry/publish.js +155 -0
  121. package/dist/registry/publish.js.map +1 -0
  122. package/dist/registry/release.d.ts +63 -0
  123. package/dist/registry/release.js +79 -0
  124. package/dist/registry/release.js.map +1 -0
  125. package/dist/restoration.d.ts +14 -0
  126. package/dist/restoration.js +33 -0
  127. package/dist/restoration.js.map +1 -0
  128. package/dist/templates.d.ts +8 -0
  129. package/dist/templates.js +39 -0
  130. package/dist/templates.js.map +1 -0
  131. package/dist/testing/contract.d.ts +43 -0
  132. package/dist/testing/contract.js +713 -0
  133. package/dist/testing/contract.js.map +1 -0
  134. package/dist/testing/diff.d.ts +1 -0
  135. package/dist/testing/diff.js +65 -0
  136. package/dist/testing/diff.js.map +1 -0
  137. package/dist/testing/git-http.d.ts +12 -0
  138. package/dist/testing/git-http.js +308 -0
  139. package/dist/testing/git-http.js.map +1 -0
  140. package/dist/testing/github-double.d.ts +151 -0
  141. package/dist/testing/github-double.js +1129 -0
  142. package/dist/testing/github-double.js.map +1 -0
  143. package/dist/testing/gitlab-double.d.ts +161 -0
  144. package/dist/testing/gitlab-double.js +1554 -0
  145. package/dist/testing/gitlab-double.js.map +1 -0
  146. package/dist/testing/index.d.ts +7 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/dist/version.d.ts +2 -0
  150. package/dist/version.js +12 -0
  151. package/dist/version.js.map +1 -0
  152. package/package.json +66 -4
@@ -0,0 +1,57 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { STALE_MS } from './store.js';
4
+ const pidOf = (file) => {
5
+ try {
6
+ const pid = Number.parseInt(fs.readFileSync(file, 'utf8'), 10);
7
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ };
13
+ /**
14
+ * Looks at the folder of the local host without changing anything (no folder made, no lock taken, no state rewritten): for readiness
15
+ * checks. Never throws.
16
+ */
17
+ export const inspectLocalStore = (dataDir, { parse = false, now = Date.now() } = {}) => {
18
+ const dir = path.resolve(dataDir);
19
+ const file = path.join(dir, 'state.json');
20
+ const lockFile = `${file}.lock`;
21
+ const exists = fs.existsSync(dir);
22
+ let writable = false;
23
+ try {
24
+ fs.accessSync(dir, fs.constants.W_OK);
25
+ writable = true;
26
+ }
27
+ catch { /* stays false */ }
28
+ const state = { exists: false, bytes: null, modifiedAt: null, valid: null };
29
+ try {
30
+ const stat = fs.statSync(file);
31
+ state.exists = true;
32
+ state.bytes = stat.size;
33
+ state.modifiedAt = stat.mtime.toISOString();
34
+ if (parse) {
35
+ try {
36
+ JSON.parse(fs.readFileSync(file, 'utf8'));
37
+ state.valid = true;
38
+ }
39
+ catch {
40
+ state.valid = false;
41
+ }
42
+ }
43
+ }
44
+ catch { /* no state yet: a new folder */ }
45
+ const lock = { held: false, pid: null, ownedByThisProcess: false, ageMs: null, stale: false };
46
+ try {
47
+ const stat = fs.statSync(lockFile);
48
+ lock.held = true;
49
+ lock.ageMs = Math.max(0, now - stat.mtimeMs);
50
+ lock.stale = lock.ageMs > STALE_MS;
51
+ lock.pid = pidOf(lockFile);
52
+ lock.ownedByThisProcess = lock.pid === process.pid;
53
+ }
54
+ catch { /* not held */ }
55
+ return { dir, exists, writable, state, lock, ok: exists && writable && state.valid !== false && !lock.stale };
56
+ };
57
+ //# sourceMappingURL=health.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.js","sourceRoot":"","sources":["../../src/local/health.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AA+BrC,MAAM,KAAK,GAAG,CAAC,IAAY,EAAiB,EAAE;IAC5C,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAA;QAC9D,OAAO,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAA;IACtD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC,CAAA;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,OAAe,EAAE,EAAE,KAAK,GAAG,KAAK,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,KAAwC,EAAE,EAAoB,EAAE;IAClJ,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;IACjC,MAAM,IA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E,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA;IACvH,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,CAAA;QAC5C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAA;QAClC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC1B,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,GAAG,KAAK,OAAO,CAAC,GAAG,CAAA;IACpD,CAAC;IAAC,MAAM,CAAC,CAAC,cAAc,CAAC,CAAC;IAE1B,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,IAAI,QAAQ,IAAI,KAAK,CAAC,KAAK,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAA;AAC/G,CAAC,CAAA","sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport { STALE_MS } from './store.js'\n\n/** What `inspectLocalStore` reports about the folder of the local host. */\nexport interface LocalStoreHealth {\n /** The folder (resolved). */\n dir: string\n exists: boolean\n /** Whether this process can write in it. */\n writable: boolean\n state: {\n exists: boolean\n bytes: number | null\n modifiedAt: string | null\n /** Whether `state.json` parses; null when not asked for (`parse: true`). */\n valid: boolean | null\n }\n /**\n * The lock file that guards `state.json` against a second process. It is taken for each change and released after it, so it is\n * normally not held. `stale` is a lock older than the takeover time, left by a process that died.\n */\n lock: {\n held: boolean\n pid: number | null\n ownedByThisProcess: boolean\n ageMs: number | null\n stale: boolean\n }\n /** Whether everything above is as it should be: folder writable, state readable, no stale lock. */\n ok: boolean\n}\n\nconst pidOf = (file: string): number | null => {\n try {\n const pid = Number.parseInt(fs.readFileSync(file, 'utf8'), 10)\n return Number.isInteger(pid) && pid > 0 ? pid : null\n } catch {\n return null\n }\n}\n\n/**\n * Looks at the folder of the local host without changing anything (no folder made, no lock taken, no state rewritten): for readiness\n * checks. Never throws.\n */\nexport const inspectLocalStore = (dataDir: string, { parse = false, now = Date.now() }: { parse?: boolean, now?: number } = {}): LocalStoreHealth => {\n const dir = path.resolve(dataDir)\n const file = path.join(dir, 'state.json')\n const lockFile = `${file}.lock`\n\n const exists = fs.existsSync(dir)\n let writable = false\n try {\n fs.accessSync(dir, fs.constants.W_OK)\n writable = true\n } catch { /* stays false */ }\n\n const state: LocalStoreHealth['state'] = { exists: false, bytes: null, modifiedAt: null, valid: null }\n try {\n const stat = fs.statSync(file)\n state.exists = true\n state.bytes = stat.size\n state.modifiedAt = stat.mtime.toISOString()\n if (parse) {\n try {\n JSON.parse(fs.readFileSync(file, 'utf8'))\n state.valid = true\n } catch {\n state.valid = false\n }\n }\n } catch { /* no state yet: a new folder */ }\n\n const lock: LocalStoreHealth['lock'] = { held: false, pid: null, ownedByThisProcess: false, ageMs: null, stale: false }\n try {\n const stat = fs.statSync(lockFile)\n lock.held = true\n lock.ageMs = Math.max(0, now - stat.mtimeMs)\n lock.stale = lock.ageMs > STALE_MS\n lock.pid = pidOf(lockFile)\n lock.ownedByThisProcess = lock.pid === process.pid\n } catch { /* not held */ }\n\n return { dir, exists, writable, state, lock, ok: exists && writable && state.valid !== false && !lock.stale }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ /** The folder of the hooks every repository of `dataDir` uses (`core.hooksPath`); written again when it is not as it should be. */
2
+ export declare const ensureHooks: (dataDir: string) => string;
@@ -0,0 +1,44 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * What git itself refuses on a push, whoever pushes: the default branch cannot be deleted or rewritten (a force-push), and pushing to
5
+ * it needs maintainer access (`LINEA_PUSH_LEVEL`, which the HTTP layer sets from the person's level in the repository). Other branches
6
+ * are the pusher's own business. LINEA's own writes go through `update-ref`, which runs no hooks.
7
+ */
8
+ const PRE_RECEIVE = `#!/bin/sh
9
+ zero=0000000000000000000000000000000000000000
10
+ head=$(git symbolic-ref HEAD 2>/dev/null)
11
+ while read old new ref; do
12
+ [ "$ref" = "$head" ] || continue
13
+ if [ "$new" = "$zero" ]; then
14
+ echo "LINEA: the default branch cannot be deleted" >&2
15
+ exit 1
16
+ fi
17
+ if [ "\${LINEA_PUSH_LEVEL:-0}" -lt 40 ]; then
18
+ echo "LINEA: pushing to the default branch needs maintainer access" >&2
19
+ exit 1
20
+ fi
21
+ if [ "$old" != "$zero" ] && ! git merge-base --is-ancestor "$old" "$new" 2>/dev/null; then
22
+ echo "LINEA: the default branch cannot be force-pushed" >&2
23
+ exit 1
24
+ fi
25
+ done
26
+ exit 0
27
+ `;
28
+ /** The folder of the hooks every repository of `dataDir` uses (`core.hooksPath`); written again when it is not as it should be. */
29
+ export const ensureHooks = (dataDir) => {
30
+ const dir = path.join(dataDir, 'hooks');
31
+ const file = path.join(dir, 'pre-receive');
32
+ let current = '';
33
+ try {
34
+ current = fs.readFileSync(file, 'utf8');
35
+ }
36
+ catch { /* not there yet */ }
37
+ if (current !== PRE_RECEIVE) {
38
+ fs.mkdirSync(dir, { recursive: true });
39
+ fs.writeFileSync(file, PRE_RECEIVE, { mode: 0o755 });
40
+ fs.chmodSync(file, 0o755);
41
+ }
42
+ return dir;
43
+ };
44
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/local/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAE5B;;;;GAIG;AACH,MAAM,WAAW,GAAG;;;;;;;;;;;;;;;;;;;CAmBnB,CAAA;AAED,mIAAmI;AACnI,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,OAAe,EAAU,EAAE;IACrD,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IACvC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,CAAA;IAC1C,IAAI,OAAO,GAAG,EAAE,CAAA;IAChB,IAAI,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IAAC,CAAC;IAAC,MAAM,CAAC,CAAC,mBAAmB,CAAC,CAAC;IAC7E,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;QAC5B,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;QACtC,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAA;QACpD,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;IAC3B,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA","sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\n/**\n * What git itself refuses on a push, whoever pushes: the default branch cannot be deleted or rewritten (a force-push), and pushing to\n * it needs maintainer access (`LINEA_PUSH_LEVEL`, which the HTTP layer sets from the person's level in the repository). Other branches\n * are the pusher's own business. LINEA's own writes go through `update-ref`, which runs no hooks.\n */\nconst PRE_RECEIVE = `#!/bin/sh\nzero=0000000000000000000000000000000000000000\nhead=$(git symbolic-ref HEAD 2>/dev/null)\nwhile read old new ref; do\n [ \"$ref\" = \"$head\" ] || continue\n if [ \"$new\" = \"$zero\" ]; then\n echo \"LINEA: the default branch cannot be deleted\" >&2\n exit 1\n fi\n if [ \"\\${LINEA_PUSH_LEVEL:-0}\" -lt 40 ]; then\n echo \"LINEA: pushing to the default branch needs maintainer access\" >&2\n exit 1\n fi\n if [ \"$old\" != \"$zero\" ] && ! git merge-base --is-ancestor \"$old\" \"$new\" 2>/dev/null; then\n echo \"LINEA: the default branch cannot be force-pushed\" >&2\n exit 1\n fi\ndone\nexit 0\n`\n\n/** The folder of the hooks every repository of `dataDir` uses (`core.hooksPath`); written again when it is not as it should be. */\nexport const ensureHooks = (dataDir: string): string => {\n const dir = path.join(dataDir, 'hooks')\n const file = path.join(dir, 'pre-receive')\n let current = ''\n try { current = fs.readFileSync(file, 'utf8') } catch { /* not there yet */ }\n if (current !== PRE_RECEIVE) {\n fs.mkdirSync(dir, { recursive: true })\n fs.writeFileSync(file, PRE_RECEIVE, { mode: 0o755 })\n fs.chmodSync(file, 0o755)\n }\n return dir\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { LocalProvider, type LocalUser } from './provider.js';
3
+ export interface LocalGitHttpOptions {
4
+ provider: LocalProvider;
5
+ /** Whose git credentials these are (the account's username, and the password or personal git token it gave): `null` refuses. */
6
+ authenticate: (username: string, password: string) => LocalUser | null | Promise<LocalUser | null>;
7
+ /** Called after a push was received, with the repository and who pushed. */
8
+ onPush?: ((push: {
9
+ repositoryId: number;
10
+ repositoryPath: string;
11
+ username: string;
12
+ }) => void | Promise<void>) | undefined;
13
+ /** Called when credentials were wrong, to count attempts (`ip`, the username tried). */
14
+ onFailure?: ((attempt: {
15
+ ip: string;
16
+ username: string;
17
+ }) => void) | undefined;
18
+ /** Refuses a request before anything is checked (a rate limit): the reason to answer 429 with, or null. */
19
+ throttle?: ((request: {
20
+ ip: string;
21
+ username: string;
22
+ }) => string | null) | undefined;
23
+ /** A transfer that moves nothing for this long is cut (default 10 minutes). */
24
+ idleTimeoutMs?: number | undefined;
25
+ /** The most a single push may send (git's `receive.maxInputSize`); none by default. */
26
+ maxPushBytes?: number | undefined;
27
+ }
28
+ /**
29
+ * Git over HTTP for the repositories of the local host, so `git clone`, `git pull` and `git push` (and the CLI, and the agents) work on
30
+ * them as on any other host. The transport is `git http-backend`, the CGI git ships with: the protocol is git's own. It is mounted at
31
+ * a path (`/git`) and sees the rest of the URL: `/<group>/<name>.git/info/refs?service=git-upload-pack`.
32
+ *
33
+ * Every request asks for credentials (Basic); `authenticate` says whose they are.
34
+ */
35
+ export declare const createLocalGitHttp: ({ provider, authenticate, onPush, onFailure, throttle, idleTimeoutMs, maxPushBytes }: LocalGitHttpOptions) => (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -0,0 +1,160 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { ACCESS } from '../access.js';
4
+ import { cleanEnv } from './git.js';
5
+ import { ensureHooks } from './hooks.js';
6
+ import { LocalProvider, slug } from './provider.js';
7
+ // the repository ends at the last `.git` that is followed by what git asks for (so a group may be called `a.git`)
8
+ const REQUEST = /^\/(.+)\.git(\/(?:info\/refs|git-upload-pack|git-receive-pack|HEAD|objects\/.*))?$/;
9
+ const refuse = (res, status, message, challenge = false) => {
10
+ res.writeHead(status, { 'Content-Type': 'text/plain', ...(challenge ? { 'WWW-Authenticate': 'Basic realm="LINEA git"' } : {}) });
11
+ res.end(`${message}\n`);
12
+ };
13
+ /**
14
+ * Git over HTTP for the repositories of the local host, so `git clone`, `git pull` and `git push` (and the CLI, and the agents) work on
15
+ * them as on any other host. The transport is `git http-backend`, the CGI git ships with: the protocol is git's own. It is mounted at
16
+ * a path (`/git`) and sees the rest of the URL: `/<group>/<name>.git/info/refs?service=git-upload-pack`.
17
+ *
18
+ * Every request asks for credentials (Basic); `authenticate` says whose they are.
19
+ */
20
+ export const createLocalGitHttp = ({ provider, authenticate, onPush, onFailure, throttle, idleTimeoutMs = 10 * 60 * 1000, maxPushBytes }) => async (req, res) => {
21
+ const url = new URL(req.url ?? '/', 'http://localhost');
22
+ let pathname;
23
+ try {
24
+ pathname = decodeURIComponent(url.pathname);
25
+ }
26
+ catch {
27
+ return refuse(res, 400, 'Malformed address');
28
+ }
29
+ const match = REQUEST.exec(pathname);
30
+ if (!match)
31
+ return refuse(res, 404, 'Not a repository');
32
+ const header = req.headers.authorization ?? '';
33
+ const [scheme, encoded] = header.split(' ');
34
+ if (scheme?.toLowerCase() !== 'basic' || !encoded)
35
+ return refuse(res, 401, 'Sign in to fetch or push', true);
36
+ const [username = '', ...rest] = Buffer.from(encoded, 'base64').toString('utf8').split(':');
37
+ const ip = req.socket.remoteAddress ?? '127.0.0.1';
38
+ const blocked = throttle?.({ ip, username });
39
+ if (blocked)
40
+ return refuse(res, 429, blocked);
41
+ const user = await authenticate(username, rest.join(':'));
42
+ if (!user) {
43
+ onFailure?.({ ip, username });
44
+ return refuse(res, 401, 'Wrong username or password', true);
45
+ }
46
+ const repositoryPath = match[1];
47
+ const lookup = await provider.store.read((state) => {
48
+ for (const repository of state.repositories) {
49
+ const namespace = state.namespaces.find((candidate) => candidate.id === repository.namespaceId);
50
+ if (namespace && `${namespace.path}/${slug(repository.name)}` === repositoryPath)
51
+ return { state, repository };
52
+ }
53
+ return null;
54
+ });
55
+ if (!lookup)
56
+ return refuse(res, 404, 'There is no such repository');
57
+ const found = lookup.repository;
58
+ // the same levels the API uses: reading needs a reporter, pushing a developer; the hook adds the rules of the default branch
59
+ const isPush = pathname.endsWith('/git-receive-pack') || url.searchParams.get('service') === 'git-receive-pack';
60
+ const level = provider.levelFor(lookup.state, found, user);
61
+ if (level < (isPush ? ACCESS.DEVELOPER : ACCESS.REPORTER))
62
+ return refuse(res, 403, isPush ? 'You are not allowed to push here' : 'You are not allowed to read this repository');
63
+ const root = path.join(provider.store.dir, 'repos');
64
+ const env = cleanEnv({
65
+ GIT_PROJECT_ROOT: root,
66
+ GIT_HTTP_EXPORT_ALL: '1',
67
+ PATH_INFO: `/${found.id}.git${match[2] ?? ''}`,
68
+ REQUEST_METHOD: req.method ?? 'GET',
69
+ QUERY_STRING: url.searchParams.toString(),
70
+ CONTENT_TYPE: req.headers['content-type'] ?? '',
71
+ REMOTE_USER: user.username,
72
+ REMOTE_ADDR: ip,
73
+ GIT_COMMITTER_NAME: user.username,
74
+ GIT_COMMITTER_EMAIL: `${user.username}@linea.local`,
75
+ // the rules every push meets, set here and not in each repository (so repositories made before them have them too)
76
+ GIT_CONFIG_COUNT: maxPushBytes ? '2' : '1',
77
+ GIT_CONFIG_KEY_0: 'core.hooksPath',
78
+ GIT_CONFIG_VALUE_0: ensureHooks(provider.store.dir),
79
+ ...(maxPushBytes ? { GIT_CONFIG_KEY_1: 'receive.maxInputSize', GIT_CONFIG_VALUE_1: String(maxPushBytes) } : {}),
80
+ LINEA_PUSH_LEVEL: String(level)
81
+ });
82
+ if (req.headers['content-length'])
83
+ env['CONTENT_LENGTH'] = req.headers['content-length'];
84
+ if (req.headers['content-encoding'])
85
+ env['HTTP_CONTENT_ENCODING'] = String(req.headers['content-encoding']);
86
+ const closesIssues = isPush && req.method === 'POST';
87
+ const headBefore = closesIssues ? await provider.defaultBranchHead(found.id).catch(() => null) : null;
88
+ const child = spawn('git', ['http-backend'], { env, windowsHide: true });
89
+ child.stderr.resume();
90
+ child.stdin.on('error', () => undefined);
91
+ // a client that goes away takes its git with it, and a transfer that stops is cut: nothing is left waiting for ever
92
+ let idle;
93
+ const touch = () => {
94
+ clearTimeout(idle);
95
+ idle = setTimeout(() => child.kill('SIGKILL'), idleTimeoutMs);
96
+ };
97
+ touch();
98
+ const stop = () => { if (child.exitCode === null && child.signalCode === null)
99
+ child.kill('SIGKILL'); };
100
+ req.on('aborted', stop);
101
+ res.on('close', () => { if (!res.writableEnded)
102
+ stop(); });
103
+ req.on('data', touch);
104
+ req.pipe(child.stdin);
105
+ // the CGI answers with its headers (one of them `Status`), a blank line and the body
106
+ let head = Buffer.alloc(0);
107
+ let sent = false;
108
+ const send = (chunk) => {
109
+ // a slow client slows git down, not the memory of the server
110
+ if (!res.write(chunk)) {
111
+ child.stdout.pause();
112
+ res.once('drain', () => child.stdout.resume());
113
+ }
114
+ };
115
+ child.stdout.on('data', (chunk) => {
116
+ touch();
117
+ if (sent) {
118
+ send(chunk);
119
+ return;
120
+ }
121
+ head = Buffer.concat([head, chunk]);
122
+ const end = head.indexOf('\r\n\r\n');
123
+ if (end < 0)
124
+ return;
125
+ const headers = {};
126
+ let status = 200;
127
+ for (const line of head.subarray(0, end).toString('utf8').split('\r\n')) {
128
+ const colon = line.indexOf(':');
129
+ if (colon < 0)
130
+ continue;
131
+ const name = line.slice(0, colon).trim();
132
+ const value = line.slice(colon + 1).trim();
133
+ if (name.toLowerCase() === 'status')
134
+ status = Number.parseInt(value, 10) || 200;
135
+ else
136
+ headers[name] = value;
137
+ }
138
+ res.writeHead(status, headers);
139
+ sent = true;
140
+ send(head.subarray(end + 4));
141
+ });
142
+ child.on('error', () => { clearTimeout(idle); if (!sent)
143
+ refuse(res, 500, 'git is not available'); });
144
+ child.on('close', (code) => {
145
+ clearTimeout(idle);
146
+ if (!sent)
147
+ refuse(res, 500, 'git http-backend answered nothing');
148
+ else
149
+ res.end();
150
+ // only a push that git accepted is an event
151
+ if (code === 0 && closesIssues) {
152
+ void provider.defaultBranchHead(found.id)
153
+ .then((headAfter) => (headAfter && headAfter !== headBefore ? provider.closeIssuesOfPush({ repositoryId: found.id, before: headBefore, after: headAfter }) : []))
154
+ .catch(() => undefined);
155
+ }
156
+ if (code === 0 && isPush && onPush && req.method === 'POST')
157
+ void Promise.resolve(onPush({ repositoryId: found.id, repositoryPath, username: user.username })).catch(() => undefined);
158
+ });
159
+ };
160
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/local/http.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,YA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AC,CAAC;iBAChK,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAA;QAC3B,CAAC;QACD,IAAI,IAAI,KAAK,CAAC,IAAI,MAAM,IAAI,MAAM,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM;YAAE,KAAK,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAA;IACvL,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { spawn } from 'node:child_process'\nimport path from 'node:path'\nimport { ACCESS } from '../access.js'\nimport { cleanEnv } from './git.js'\nimport { ensureHooks } from './hooks.js'\nimport { LocalProvider, slug, type LocalUser } from './provider.js'\n\nexport interface LocalGitHttpOptions {\n provider: LocalProvider\n /** Whose git credentials these are (the account's username, and the password or personal git token it gave): `null` refuses. */\n authenticate: (username: string, password: string) => LocalUser | null | Promise<LocalUser | null>\n /** Called after a push was received, with the repository and who pushed. */\n onPush?: ((push: { repositoryId: number, repositoryPath: string, username: string }) => void | Promise<void>) | undefined\n /** Called when credentials were wrong, to count attempts (`ip`, the username tried). */\n onFailure?: ((attempt: { ip: string, username: string }) => void) | undefined\n /** Refuses a request before anything is checked (a rate limit): the reason to answer 429 with, or null. */\n throttle?: ((request: { ip: string, username: string }) => string | null) | undefined\n /** A transfer that moves nothing for this long is cut (default 10 minutes). */\n idleTimeoutMs?: number | undefined\n /** The most a single push may send (git's `receive.maxInputSize`); none by default. */\n maxPushBytes?: number | undefined\n}\n\n// the repository ends at the last `.git` that is followed by what git asks for (so a group may be called `a.git`)\nconst REQUEST = /^\\/(.+)\\.git(\\/(?:info\\/refs|git-upload-pack|git-receive-pack|HEAD|objects\\/.*))?$/\n\nconst refuse = (res: ServerResponse, status: number, message: string, challenge = false): void => {\n res.writeHead(status, { 'Content-Type': 'text/plain', ...(challenge ? { 'WWW-Authenticate': 'Basic realm=\"LINEA git\"' } : {}) })\n res.end(`${message}\\n`)\n}\n\n/**\n * Git over HTTP for the repositories of the local host, so `git clone`, `git pull` and `git push` (and the CLI, and the agents) work on\n * them as on any other host. The transport is `git http-backend`, the CGI git ships with: the protocol is git's own. It is mounted at\n * a path (`/git`) and sees the rest of the URL: `/<group>/<name>.git/info/refs?service=git-upload-pack`.\n *\n * Every request asks for credentials (Basic); `authenticate` says whose they are.\n */\nexport const createLocalGitHttp = ({ provider, authenticate, onPush, onFailure, throttle, idleTimeoutMs = 10 * 60 * 1000, maxPushBytes }: LocalGitHttpOptions) =>\n async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const url = new URL(req.url ?? '/', 'http://localhost')\n let pathname: string\n try {\n pathname = decodeURIComponent(url.pathname)\n } catch {\n return refuse(res, 400, 'Malformed address')\n }\n const match = REQUEST.exec(pathname)\n if (!match) return refuse(res, 404, 'Not a repository')\n\n const header = req.headers.authorization ?? ''\n const [scheme, encoded] = header.split(' ')\n if (scheme?.toLowerCase() !== 'basic' || !encoded) return refuse(res, 401, 'Sign in to fetch or push', true)\n const [username = '', ...rest] = Buffer.from(encoded, 'base64').toString('utf8').split(':')\n const ip = req.socket.remoteAddress ?? '127.0.0.1'\n const blocked = throttle?.({ ip, username })\n if (blocked) return refuse(res, 429, blocked)\n const user = await authenticate(username, rest.join(':'))\n if (!user) {\n onFailure?.({ ip, username })\n return refuse(res, 401, 'Wrong username or password', true)\n }\n\n const repositoryPath = match[1] as string\n const lookup = await provider.store.read((state) => {\n for (const repository of state.repositories) {\n const namespace = state.namespaces.find((candidate) => candidate.id === repository.namespaceId)\n if (namespace && `${namespace.path}/${slug(repository.name)}` === repositoryPath) return { state, repository }\n }\n return null\n })\n if (!lookup) return refuse(res, 404, 'There is no such repository')\n const found = lookup.repository\n\n // the same levels the API uses: reading needs a reporter, pushing a developer; the hook adds the rules of the default branch\n const isPush = pathname.endsWith('/git-receive-pack') || url.searchParams.get('service') === 'git-receive-pack'\n const level = provider.levelFor(lookup.state, found, user)\n if (level < (isPush ? ACCESS.DEVELOPER : ACCESS.REPORTER)) return refuse(res, 403, isPush ? 'You are not allowed to push here' : 'You are not allowed to read this repository')\n\n const root = path.join(provider.store.dir, 'repos')\n const env = cleanEnv({\n GIT_PROJECT_ROOT: root,\n GIT_HTTP_EXPORT_ALL: '1',\n PATH_INFO: `/${found.id}.git${match[2] ?? ''}`,\n REQUEST_METHOD: req.method ?? 'GET',\n QUERY_STRING: url.searchParams.toString(),\n CONTENT_TYPE: req.headers['content-type'] ?? '',\n REMOTE_USER: user.username,\n REMOTE_ADDR: ip,\n GIT_COMMITTER_NAME: user.username,\n GIT_COMMITTER_EMAIL: `${user.username}@linea.local`,\n // the rules every push meets, set here and not in each repository (so repositories made before them have them too)\n GIT_CONFIG_COUNT: maxPushBytes ? '2' : '1',\n GIT_CONFIG_KEY_0: 'core.hooksPath',\n GIT_CONFIG_VALUE_0: ensureHooks(provider.store.dir),\n ...(maxPushBytes ? { GIT_CONFIG_KEY_1: 'receive.maxInputSize', GIT_CONFIG_VALUE_1: String(maxPushBytes) } : {}),\n LINEA_PUSH_LEVEL: String(level)\n }) as Record<string, string>\n if (req.headers['content-length']) env['CONTENT_LENGTH'] = req.headers['content-length']\n if (req.headers['content-encoding']) env['HTTP_CONTENT_ENCODING'] = String(req.headers['content-encoding'])\n\n const closesIssues = isPush && req.method === 'POST'\n const headBefore = closesIssues ? await provider.defaultBranchHead(found.id).catch(() => null) : null\n\n const child = spawn('git', ['http-backend'], { env, windowsHide: true })\n child.stderr.resume()\n child.stdin.on('error', () => undefined)\n\n // a client that goes away takes its git with it, and a transfer that stops is cut: nothing is left waiting for ever\n let idle: NodeJS.Timeout | undefined\n const touch = (): void => {\n clearTimeout(idle)\n idle = setTimeout(() => child.kill('SIGKILL'), idleTimeoutMs)\n }\n touch()\n const stop = (): void => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') }\n req.on('aborted', stop)\n res.on('close', () => { if (!res.writableEnded) stop() })\n req.on('data', touch)\n req.pipe(child.stdin)\n\n // the CGI answers with its headers (one of them `Status`), a blank line and the body\n let head = Buffer.alloc(0)\n let sent = false\n const send = (chunk: Buffer): void => {\n // a slow client slows git down, not the memory of the server\n if (!res.write(chunk)) {\n child.stdout.pause()\n res.once('drain', () => child.stdout.resume())\n }\n }\n child.stdout.on('data', (chunk: Buffer) => {\n touch()\n if (sent) { send(chunk); return }\n head = Buffer.concat([head, chunk])\n const end = head.indexOf('\\r\\n\\r\\n')\n if (end < 0) return\n const headers: Record<string, string> = {}\n let status = 200\n for (const line of head.subarray(0, end).toString('utf8').split('\\r\\n')) {\n const colon = line.indexOf(':')\n if (colon < 0) continue\n const name = line.slice(0, colon).trim()\n const value = line.slice(colon + 1).trim()\n if (name.toLowerCase() === 'status') status = Number.parseInt(value, 10) || 200\n else headers[name] = value\n }\n res.writeHead(status, headers)\n sent = true\n send(head.subarray(end + 4))\n })\n child.on('error', () => { clearTimeout(idle); if (!sent) refuse(res, 500, 'git is not available') })\n child.on('close', (code) => {\n clearTimeout(idle)\n if (!sent) refuse(res, 500, 'git http-backend answered nothing')\n else res.end()\n // only a push that git accepted is an event\n if (code === 0 && closesIssues) {\n void provider.defaultBranchHead(found.id)\n .then((headAfter) => (headAfter && headAfter !== headBefore ? provider.closeIssuesOfPush({ repositoryId: found.id, before: headBefore, after: headAfter }) : []))\n .catch(() => undefined)\n }\n if (code === 0 && isPush && onPush && req.method === 'POST') void Promise.resolve(onPush({ repositoryId: found.id, repositoryPath, username: user.username })).catch(() => undefined)\n })\n }\n"]}