@leed-ai/git-gateway-worker 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.
- package/LICENSE +201 -0
- package/README.md +49 -2
- package/dist/audit/audit-recorder.d.ts +2 -0
- package/dist/audit/audit-recorder.js +53 -0
- package/dist/audit/audit-recorder.js.map +1 -0
- package/dist/audit/push-report.d.ts +13 -0
- package/dist/audit/push-report.js +66 -0
- package/dist/audit/push-report.js.map +1 -0
- package/dist/audit-recorder-K1Ns3tfC.d.ts +31 -0
- package/dist/auth/authenticate.d.ts +14 -0
- package/dist/auth/authenticate.js +59 -0
- package/dist/auth/authenticate.js.map +1 -0
- package/dist/auth/authorize.d.ts +12 -0
- package/dist/auth/authorize.js +57 -0
- package/dist/auth/authorize.js.map +1 -0
- package/dist/auth/read-token-auth.d.ts +60 -0
- package/dist/auth/read-token-auth.js +83 -0
- package/dist/auth/read-token-auth.js.map +1 -0
- package/dist/cache/decision-cache.d.ts +2 -0
- package/dist/cache/decision-cache.js +45 -0
- package/dist/cache/decision-cache.js.map +1 -0
- package/dist/commit-workflow-schemas-BWlg7bZR.d.ts +95 -0
- package/dist/decision-cache-87U32iSj.d.ts +24 -0
- package/dist/gateway-app.d.ts +69 -0
- package/dist/gateway-app.js +80 -0
- package/dist/gateway-app.js.map +1 -0
- package/dist/gateway-context-Boh9I0mk.d.ts +54 -0
- package/dist/gateway-env-DnsBU4Pq.d.ts +40 -0
- package/dist/gateway-worker.d.ts +13 -0
- package/dist/gateway-worker.js +22 -0
- package/dist/gateway-worker.js.map +1 -0
- package/dist/git-route-Spxi09Rm.d.ts +22 -0
- package/dist/health.d.ts +6 -0
- package/dist/health.js +16 -0
- package/dist/health.js.map +1 -0
- package/dist/logger-BZ1zyKLb.d.ts +27 -0
- package/dist/logging/logger.d.ts +2 -0
- package/dist/logging/logger.js +15 -0
- package/dist/logging/logger.js.map +1 -0
- package/dist/on-push-DTREOB__.d.ts +62 -0
- package/dist/policy/branch-policy.d.ts +24 -0
- package/dist/policy/branch-policy.js +125 -0
- package/dist/policy/branch-policy.js.map +1 -0
- package/dist/policy/enforce-branch-policy.d.ts +30 -0
- package/dist/policy/enforce-branch-policy.js +214 -0
- package/dist/policy/enforce-branch-policy.js.map +1 -0
- package/dist/policy/fast-forward.d.ts +32 -0
- package/dist/policy/fast-forward.js +95 -0
- package/dist/policy/fast-forward.js.map +1 -0
- package/dist/policy/ref-pattern.d.ts +7 -0
- package/dist/policy/ref-pattern.js +25 -0
- package/dist/policy/ref-pattern.js.map +1 -0
- package/dist/policy/rule-branch-policy.d.ts +17 -0
- package/dist/policy/rule-branch-policy.js +69 -0
- package/dist/policy/rule-branch-policy.js.map +1 -0
- package/dist/proxy/defer.d.ts +8 -0
- package/dist/proxy/defer.js +15 -0
- package/dist/proxy/defer.js.map +1 -0
- package/dist/proxy/forward-read.d.ts +11 -0
- package/dist/proxy/forward-read.js +53 -0
- package/dist/proxy/forward-read.js.map +1 -0
- package/dist/proxy/gateway-deps.d.ts +39 -0
- package/dist/proxy/gateway-deps.js +0 -0
- package/dist/proxy/gateway-env.d.ts +2 -0
- package/dist/proxy/gateway-env.js +0 -0
- package/dist/proxy/git-responses.d.ts +25 -0
- package/dist/proxy/git-responses.js +83 -0
- package/dist/proxy/git-responses.js.map +1 -0
- package/dist/proxy/git-route.d.ts +2 -0
- package/dist/proxy/git-route.js +34 -0
- package/dist/proxy/git-route.js.map +1 -0
- package/dist/proxy/push-events.d.ts +28 -0
- package/dist/proxy/push-events.js +65 -0
- package/dist/proxy/push-events.js.map +1 -0
- package/dist/proxy/push-guard.d.ts +43 -0
- package/dist/proxy/push-guard.js +81 -0
- package/dist/proxy/push-guard.js.map +1 -0
- package/dist/proxy/push-options.d.ts +16 -0
- package/dist/proxy/push-options.js +33 -0
- package/dist/proxy/push-options.js.map +1 -0
- package/dist/proxy/receive-pack.d.ts +17 -0
- package/dist/proxy/receive-pack.js +244 -0
- package/dist/proxy/receive-pack.js.map +1 -0
- package/dist/proxy/request-log.d.ts +13 -0
- package/dist/proxy/request-log.js +41 -0
- package/dist/proxy/request-log.js.map +1 -0
- package/dist/proxy/resolve-route.d.ts +9 -0
- package/dist/proxy/resolve-route.js +22 -0
- package/dist/proxy/resolve-route.js.map +1 -0
- package/dist/proxy/upstream-call.d.ts +23 -0
- package/dist/proxy/upstream-call.js +63 -0
- package/dist/proxy/upstream-call.js.map +1 -0
- package/dist/proxy/upstream.d.ts +2 -0
- package/dist/proxy/upstream.js +68 -0
- package/dist/proxy/upstream.js.map +1 -0
- package/dist/push-event-f-5TsFUY.d.ts +15 -0
- package/dist/push-policy/changed-paths.d.ts +26 -0
- package/dist/push-policy/changed-paths.js +117 -0
- package/dist/push-policy/changed-paths.js.map +1 -0
- package/dist/push-policy/pushed-objects.d.ts +30 -0
- package/dist/push-policy/pushed-objects.js +76 -0
- package/dist/push-policy/pushed-objects.js.map +1 -0
- package/dist/push-policy/run-push-policy.d.ts +35 -0
- package/dist/push-policy/run-push-policy.js +77 -0
- package/dist/push-policy/run-push-policy.js.map +1 -0
- package/dist/push-policy/tree-diff.d.ts +21 -0
- package/dist/push-policy/tree-diff.js +78 -0
- package/dist/push-policy/tree-diff.js.map +1 -0
- package/dist/push-policy/uncheckable.d.ts +14 -0
- package/dist/push-policy/uncheckable.js +25 -0
- package/dist/push-policy/uncheckable.js.map +1 -0
- package/dist/rpc/branch-methods.d.ts +16 -0
- package/dist/rpc/branch-methods.js +43 -0
- package/dist/rpc/branch-methods.js.map +1 -0
- package/dist/rpc/commit-attempt.d.ts +27 -0
- package/dist/rpc/commit-attempt.js +85 -0
- package/dist/rpc/commit-attempt.js.map +1 -0
- package/dist/rpc/commit-graph.d.ts +20 -0
- package/dist/rpc/commit-graph.js +38 -0
- package/dist/rpc/commit-graph.js.map +1 -0
- package/dist/rpc/commit-method.d.ts +13 -0
- package/dist/rpc/commit-method.js +30 -0
- package/dist/rpc/commit-method.js.map +1 -0
- package/dist/rpc/commit-source.d.ts +12 -0
- package/dist/rpc/commit-source.js +9 -0
- package/dist/rpc/commit-source.js.map +1 -0
- package/dist/rpc/gateway-context.d.ts +2 -0
- package/dist/rpc/gateway-context.js +30 -0
- package/dist/rpc/gateway-context.js.map +1 -0
- package/dist/rpc/gateway-rpc.d.ts +10 -0
- package/dist/rpc/gateway-rpc.js +48 -0
- package/dist/rpc/gateway-rpc.js.map +1 -0
- package/dist/rpc/gateway-service.d.ts +24 -0
- package/dist/rpc/gateway-service.js +63 -0
- package/dist/rpc/gateway-service.js.map +1 -0
- package/dist/rpc/history-page.d.ts +35 -0
- package/dist/rpc/history-page.js +122 -0
- package/dist/rpc/history-page.js.map +1 -0
- package/dist/rpc/lifecycle-methods.d.ts +12 -0
- package/dist/rpc/lifecycle-methods.js +39 -0
- package/dist/rpc/lifecycle-methods.js.map +1 -0
- package/dist/rpc/paint-down.d.ts +17 -0
- package/dist/rpc/paint-down.js +96 -0
- package/dist/rpc/paint-down.js.map +1 -0
- package/dist/rpc/promote-attempt.d.ts +21 -0
- package/dist/rpc/promote-attempt.js +55 -0
- package/dist/rpc/promote-attempt.js.map +1 -0
- package/dist/rpc/push-ref.d.ts +21 -0
- package/dist/rpc/push-ref.js +47 -0
- package/dist/rpc/push-ref.js.map +1 -0
- package/dist/rpc/read-methods.d.ts +17 -0
- package/dist/rpc/read-methods.js +94 -0
- package/dist/rpc/read-methods.js.map +1 -0
- package/dist/rpc/read-token.d.ts +39 -0
- package/dist/rpc/read-token.js +107 -0
- package/dist/rpc/read-token.js.map +1 -0
- package/dist/rpc/repo-access.d.ts +36 -0
- package/dist/rpc/repo-access.js +75 -0
- package/dist/rpc/repo-access.js.map +1 -0
- package/dist/rpc/sync-attempt.d.ts +23 -0
- package/dist/rpc/sync-attempt.js +105 -0
- package/dist/rpc/sync-attempt.js.map +1 -0
- package/dist/sync-workflow-schemas-DCNmNE5-.d.ts +57 -0
- package/dist/upstream-DvqMCj5N.d.ts +15 -0
- package/dist/workflow-starter-BqhwX6oA.d.ts +45 -0
- package/dist/workflows/commit-workflow-schemas.d.ts +2 -0
- package/dist/workflows/commit-workflow-schemas.js +84 -0
- package/dist/workflows/commit-workflow-schemas.js.map +1 -0
- package/dist/workflows/commit-workflow.d.ts +16 -0
- package/dist/workflows/commit-workflow.js +22 -0
- package/dist/workflows/commit-workflow.js.map +1 -0
- package/dist/workflows/on-push.d.ts +2 -0
- package/dist/workflows/on-push.js +90 -0
- package/dist/workflows/on-push.js.map +1 -0
- package/dist/workflows/push-event.d.ts +2 -0
- package/dist/workflows/push-event.js +28 -0
- package/dist/workflows/push-event.js.map +1 -0
- package/dist/workflows/run-commit-workflow.d.ts +15 -0
- package/dist/workflows/run-commit-workflow.js +49 -0
- package/dist/workflows/run-commit-workflow.js.map +1 -0
- package/dist/workflows/run-sync-workflow.d.ts +14 -0
- package/dist/workflows/run-sync-workflow.js +67 -0
- package/dist/workflows/run-sync-workflow.js.map +1 -0
- package/dist/workflows/step-errors.d.ts +15 -0
- package/dist/workflows/step-errors.js +24 -0
- package/dist/workflows/step-errors.js.map +1 -0
- package/dist/workflows/step-runner.d.ts +31 -0
- package/dist/workflows/step-runner.js +6 -0
- package/dist/workflows/step-runner.js.map +1 -0
- package/dist/workflows/sync-branch-workflow.d.ts +15 -0
- package/dist/workflows/sync-branch-workflow.js +21 -0
- package/dist/workflows/sync-branch-workflow.js.map +1 -0
- package/dist/workflows/sync-workflow-schemas.d.ts +2 -0
- package/dist/workflows/sync-workflow-schemas.js +104 -0
- package/dist/workflows/sync-workflow-schemas.js.map +1 -0
- package/dist/workflows/workflow-instance-id.d.ts +12 -0
- package/dist/workflows/workflow-instance-id.js +33 -0
- package/dist/workflows/workflow-instance-id.js.map +1 -0
- package/dist/workflows/workflow-runtime.d.ts +7 -0
- package/dist/workflows/workflow-runtime.js +11 -0
- package/dist/workflows/workflow-runtime.js.map +1 -0
- package/dist/workflows/workflow-starter.d.ts +2 -0
- package/dist/workflows/workflow-starter.js +40 -0
- package/dist/workflows/workflow-starter.js.map +1 -0
- package/package.json +381 -4
- package/src/audit/audit-recorder.ts +74 -0
- package/src/audit/push-report.ts +60 -0
- package/src/auth/authenticate.ts +68 -0
- package/src/auth/authorize.ts +57 -0
- package/src/auth/read-token-auth.ts +119 -0
- package/src/cache/decision-cache.ts +57 -0
- package/src/gateway-app.ts +147 -0
- package/src/gateway-worker.ts +32 -0
- package/src/health.ts +12 -0
- package/src/logging/logger.ts +40 -0
- package/src/policy/branch-policy.ts +119 -0
- package/src/policy/enforce-branch-policy.ts +213 -0
- package/src/policy/fast-forward.ts +136 -0
- package/src/policy/ref-pattern.ts +24 -0
- package/src/policy/rule-branch-policy.ts +76 -0
- package/src/proxy/defer.ts +18 -0
- package/src/proxy/forward-read.ts +52 -0
- package/src/proxy/gateway-deps.ts +43 -0
- package/src/proxy/gateway-env.ts +43 -0
- package/src/proxy/git-responses.ts +89 -0
- package/src/proxy/git-route.ts +49 -0
- package/src/proxy/push-events.ts +91 -0
- package/src/proxy/push-guard.ts +109 -0
- package/src/proxy/push-options.ts +38 -0
- package/src/proxy/receive-pack.ts +257 -0
- package/src/proxy/request-log.ts +44 -0
- package/src/proxy/resolve-route.ts +24 -0
- package/src/proxy/upstream-call.ts +71 -0
- package/src/proxy/upstream.ts +76 -0
- package/src/push-policy/changed-paths.ts +143 -0
- package/src/push-policy/pushed-objects.ts +88 -0
- package/src/push-policy/run-push-policy.ts +99 -0
- package/src/push-policy/tree-diff.ts +107 -0
- package/src/push-policy/uncheckable.ts +27 -0
- package/src/rpc/branch-methods.ts +57 -0
- package/src/rpc/commit-attempt.ts +87 -0
- package/src/rpc/commit-graph.ts +44 -0
- package/src/rpc/commit-method.ts +36 -0
- package/src/rpc/commit-source.ts +15 -0
- package/src/rpc/gateway-context.ts +77 -0
- package/src/rpc/gateway-rpc.ts +65 -0
- package/src/rpc/gateway-service.ts +85 -0
- package/src/rpc/history-page.ts +163 -0
- package/src/rpc/lifecycle-methods.ts +50 -0
- package/src/rpc/paint-down.ts +120 -0
- package/src/rpc/promote-attempt.ts +52 -0
- package/src/rpc/push-ref.ts +54 -0
- package/src/rpc/read-methods.ts +111 -0
- package/src/rpc/read-token.ts +135 -0
- package/src/rpc/repo-access.ts +112 -0
- package/src/rpc/sync-attempt.ts +84 -0
- package/src/workflows/commit-workflow-schemas.ts +95 -0
- package/src/workflows/commit-workflow.ts +39 -0
- package/src/workflows/on-push.ts +128 -0
- package/src/workflows/push-event.ts +41 -0
- package/src/workflows/run-commit-workflow.ts +45 -0
- package/src/workflows/run-sync-workflow.ts +52 -0
- package/src/workflows/step-errors.ts +26 -0
- package/src/workflows/step-runner.ts +36 -0
- package/src/workflows/sync-branch-workflow.ts +40 -0
- package/src/workflows/sync-workflow-schemas.ts +122 -0
- package/src/workflows/workflow-instance-id.ts +26 -0
- package/src/workflows/workflow-runtime.ts +13 -0
- package/src/workflows/workflow-starter.ts +69 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { RpcOutput, RpcParsedInput } from '@leed-ai/git-gateway-contract/git-gateway';
|
|
3
|
+
import { remoteUrlOf } from '@leed-ai/git-gateway-contract/reference/repo-state';
|
|
4
|
+
|
|
5
|
+
import type { GatewayContext } from './gateway-context.ts';
|
|
6
|
+
import { mintReadToken } from './read-token.ts';
|
|
7
|
+
import { requireRepo } from './repo-access.ts';
|
|
8
|
+
|
|
9
|
+
/** createRepo(): an empty repository on the backend; repo_exists when the name is taken. */
|
|
10
|
+
export async function gatewayCreateRepo(
|
|
11
|
+
context: GatewayContext,
|
|
12
|
+
{ repo, defaultBranch }: RpcParsedInput<'createRepo'>,
|
|
13
|
+
): Promise<RpcOutput<'createRepo'>> {
|
|
14
|
+
const info = await context.backend.createRepo(repo, { defaultBranch });
|
|
15
|
+
return {
|
|
16
|
+
name: info.name,
|
|
17
|
+
defaultBranch: info.defaultBranch,
|
|
18
|
+
// A host that does not report creation times created the repository just now.
|
|
19
|
+
createdAt: info.createdAt ?? context.now().toISOString(),
|
|
20
|
+
remoteUrl: remoteUrlOf(context.config, info.name),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** deleteRepo(): deletes the repository; `deleted` is false when there was none. */
|
|
25
|
+
export async function gatewayDeleteRepo(
|
|
26
|
+
context: GatewayContext,
|
|
27
|
+
{ repo }: RpcParsedInput<'deleteRepo'>,
|
|
28
|
+
): Promise<RpcOutput<'deleteRepo'>> {
|
|
29
|
+
if ((await context.backend.repoInfo(repo)) === null) return { deleted: false };
|
|
30
|
+
await context.backend.deleteRepo(repo);
|
|
31
|
+
return { deleted: true };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* mintReadToken(): a signed, short-lived credential that reads one repository through the
|
|
36
|
+
* gateway (see `verifyReadToken`). It is not a storage-host credential and grants no write.
|
|
37
|
+
*/
|
|
38
|
+
export async function gatewayMintReadToken(
|
|
39
|
+
context: GatewayContext,
|
|
40
|
+
{ repo, ttlSeconds }: RpcParsedInput<'mintReadToken'>,
|
|
41
|
+
): Promise<RpcOutput<'mintReadToken'>> {
|
|
42
|
+
await requireRepo(context, repo);
|
|
43
|
+
const minted = await mintReadToken({
|
|
44
|
+
repo,
|
|
45
|
+
ttlSeconds,
|
|
46
|
+
secret: context.readTokenSecret,
|
|
47
|
+
now: context.now(),
|
|
48
|
+
});
|
|
49
|
+
return { ...minted, remoteUrl: remoteUrlOf(context.config, repo) };
|
|
50
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';
|
|
3
|
+
|
|
4
|
+
import { type CommitSource, dateOrder } from './commit-source.ts';
|
|
5
|
+
|
|
6
|
+
/** Reached from the first commit. */
|
|
7
|
+
const ONE = 1;
|
|
8
|
+
/** Reached from the second commit. */
|
|
9
|
+
const TWO = 2;
|
|
10
|
+
/** Reached through a common ancestor, so an ancestor of one: never a best common ancestor. */
|
|
11
|
+
const STALE = 4;
|
|
12
|
+
const BOTH = ONE | TWO;
|
|
13
|
+
|
|
14
|
+
/** What one paint-down walk found. */
|
|
15
|
+
interface Painted {
|
|
16
|
+
/** True when the walk stopped because `stopAt` was reached from the second commit. */
|
|
17
|
+
readonly stopped: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Common ancestors met before the walk ended that were not found to sit beneath another one.
|
|
20
|
+
* Every best common ancestor is among them; a few non-best ones may be too.
|
|
21
|
+
*/
|
|
22
|
+
readonly candidates: readonly Commit[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Git's paint-down-to-common walk. Both commits are walked back together, newest committer date
|
|
27
|
+
* first, each commit painted with the side(s) it was reached from. A commit reached from both is a
|
|
28
|
+
* common ancestor, and everything beneath it is painted stale. The walk ends once every queued
|
|
29
|
+
* commit is stale: any commit not yet reached then lies beneath a common ancestor, so it can be
|
|
30
|
+
* neither a best common ancestor nor on the way to one. Only the history between the two heads
|
|
31
|
+
* and their merge base is read, never the whole history — unless the histories are unrelated.
|
|
32
|
+
* When `stopAt` is given, the walk ends as soon as that commit is reached from the second commit.
|
|
33
|
+
*/
|
|
34
|
+
async function paintDown(
|
|
35
|
+
source: CommitSource,
|
|
36
|
+
one: Commit,
|
|
37
|
+
two: Commit,
|
|
38
|
+
stopAt: string | null,
|
|
39
|
+
): Promise<Painted> {
|
|
40
|
+
const flags = new Map<string, number>();
|
|
41
|
+
const commits = new Map<string, Commit>();
|
|
42
|
+
const queue: Commit[] = [];
|
|
43
|
+
const reachedBoth: Commit[] = [];
|
|
44
|
+
const paint = (commit: Commit, add: number): void => {
|
|
45
|
+
const had = flags.get(commit.sha) ?? 0;
|
|
46
|
+
if ((had & add) === add) return;
|
|
47
|
+
flags.set(commit.sha, had | add);
|
|
48
|
+
commits.set(commit.sha, commit);
|
|
49
|
+
if (!queue.some((queued) => queued.sha === commit.sha)) queue.push(commit);
|
|
50
|
+
};
|
|
51
|
+
const isStale = (commit: Commit): boolean => ((flags.get(commit.sha) ?? 0) & STALE) !== 0;
|
|
52
|
+
const stopped = (): boolean => stopAt !== null && ((flags.get(stopAt) ?? 0) & TWO) !== 0;
|
|
53
|
+
|
|
54
|
+
paint(one, ONE);
|
|
55
|
+
paint(two, TWO);
|
|
56
|
+
while (!stopped() && queue.some((commit) => !isStale(commit))) {
|
|
57
|
+
let newest = 0;
|
|
58
|
+
queue.forEach((commit, index) => {
|
|
59
|
+
const best = queue[newest];
|
|
60
|
+
if (best !== undefined && dateOrder(commit, best) > 0) newest = index;
|
|
61
|
+
});
|
|
62
|
+
const [commit] = queue.splice(newest, 1);
|
|
63
|
+
if (commit === undefined) break;
|
|
64
|
+
let carried = flags.get(commit.sha) ?? 0;
|
|
65
|
+
if ((carried & (BOTH | STALE)) === BOTH) {
|
|
66
|
+
if (!reachedBoth.some((found) => found.sha === commit.sha)) reachedBoth.push(commit);
|
|
67
|
+
carried |= STALE;
|
|
68
|
+
}
|
|
69
|
+
const parents = await Promise.all(
|
|
70
|
+
commit.parents.map(async (sha) => commits.get(sha) ?? source.commit(sha)),
|
|
71
|
+
);
|
|
72
|
+
for (const parent of parents) if (parent !== null) paint(parent, carried);
|
|
73
|
+
}
|
|
74
|
+
return { stopped: stopped(), candidates: reachedBoth.filter((commit) => !isStale(commit)) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* True when `ancestor` is reachable from `descendant` (a commit contains itself), as the
|
|
79
|
+
* reference's `contains` answers it; false when either commit is missing. Reads only the history
|
|
80
|
+
* between the two commits and their merge base, whichever way the answer goes.
|
|
81
|
+
*/
|
|
82
|
+
export async function isAncestor(
|
|
83
|
+
source: CommitSource,
|
|
84
|
+
descendant: string,
|
|
85
|
+
ancestor: string,
|
|
86
|
+
): Promise<boolean> {
|
|
87
|
+
const [below, above] = await Promise.all([source.commit(ancestor), source.commit(descendant)]);
|
|
88
|
+
if (below === null || above === null) return false;
|
|
89
|
+
if (below.sha === above.sha) return true;
|
|
90
|
+
return (await paintDown(source, below, above, below.sha)).stopped;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Every best common ancestor of two commits — a common ancestor no other common ancestor descends
|
|
95
|
+
* from — ranked as the reference's `mergeBase` ranks them: newest committer date first, then the
|
|
96
|
+
* lowest id. Empty when the histories are unrelated or either commit is missing.
|
|
97
|
+
*/
|
|
98
|
+
export async function bestCommonAncestors(source: CommitSource, a: string, b: string): Promise<Commit[]> {
|
|
99
|
+
const [first, second] = await Promise.all([source.commit(a), source.commit(b)]);
|
|
100
|
+
if (first === null || second === null) return [];
|
|
101
|
+
const { candidates } = await paintDown(source, first, second, null);
|
|
102
|
+
const best: Commit[] = [];
|
|
103
|
+
for (const candidate of candidates) {
|
|
104
|
+
let beneathAnother = false;
|
|
105
|
+
for (const other of candidates) {
|
|
106
|
+
if (other.sha === candidate.sha) continue;
|
|
107
|
+
if (await isAncestor(source, other.sha, candidate.sha)) {
|
|
108
|
+
beneathAnother = true;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!beneathAnother) best.push(candidate);
|
|
113
|
+
}
|
|
114
|
+
return best.toSorted((x, y) => dateOrder(y, x) || (x.sha < y.sha ? -1 : 1));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The best common ancestor of two commits as the reference's `mergeBase` picks it, or null. */
|
|
118
|
+
export async function mergeBaseOf(source: CommitSource, a: string, b: string): Promise<string | null> {
|
|
119
|
+
return (await bestCommonAncestors(source, a, b))[0]?.sha ?? null;
|
|
120
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { RpcOutput, RpcParsedInput } from '@leed-ai/git-gateway-contract/git-gateway';
|
|
3
|
+
import { gatewayError } from '@leed-ai/git-gateway-contract/gateway-error';
|
|
4
|
+
import { ZERO_SHA } from '@leed-ai/git-gateway-contract/schemas/sha';
|
|
5
|
+
import { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';
|
|
6
|
+
|
|
7
|
+
import { CommitGraph } from './commit-graph.ts';
|
|
8
|
+
import type { GatewayContext } from './gateway-context.ts';
|
|
9
|
+
import { pushRefUpdate } from './push-ref.ts';
|
|
10
|
+
import { branchHead, branchRef, requireBranchHead } from './repo-access.ts';
|
|
11
|
+
|
|
12
|
+
/** promote() input after parsing. */
|
|
13
|
+
export type PromoteParams = RpcParsedInput<'promote'>;
|
|
14
|
+
|
|
15
|
+
/** The outcome of one promote attempt. */
|
|
16
|
+
export type PromoteAttempt =
|
|
17
|
+
| { readonly kind: 'done'; readonly output: RpcOutput<'promote'> }
|
|
18
|
+
/** `into` moved between the checks and the push; `intoHead` is what the push named. */
|
|
19
|
+
| { readonly kind: 'stale'; readonly intoHead: string | null };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One attempt at promote(): refuses unless `sha` is the head of `from` (not_head_of_source) and
|
|
23
|
+
* contains the head of `into` (not_fast_forward); otherwise moves `into` to `sha` with an update
|
|
24
|
+
* naming its current head (or creates it). Never merges, never forces.
|
|
25
|
+
*/
|
|
26
|
+
export async function attemptPromote(context: GatewayContext, input: PromoteParams): Promise<PromoteAttempt> {
|
|
27
|
+
const { repo, from, into, sha } = input;
|
|
28
|
+
const fromHead = await requireBranchHead(context, repo, from);
|
|
29
|
+
if (fromHead !== sha) {
|
|
30
|
+
throw gatewayError('not_head_of_source', `${sha} is not the head of ${from}`, {
|
|
31
|
+
from,
|
|
32
|
+
sha,
|
|
33
|
+
head: fromHead,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const intoHead = await branchHead(context, repo, into);
|
|
37
|
+
if (intoHead === sha) return { kind: 'done', output: { status: 'up_to_date', head: sha } };
|
|
38
|
+
if (intoHead !== null && !(await new CommitGraph(context, repo).contains(sha, intoHead))) {
|
|
39
|
+
throw gatewayError('not_fast_forward', `${sha} does not contain the head of ${into}`, {
|
|
40
|
+
into,
|
|
41
|
+
sha,
|
|
42
|
+
head: intoHead,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const refUpdate = { ref: branchRef(into), oldSha: intoHead ?? ZERO_SHA, newSha: sha };
|
|
46
|
+
const pushed = await pushRefUpdate(context, repo, refUpdate, []);
|
|
47
|
+
if (pushed.status === 'ok') return { kind: 'done', output: { status: 'promoted', refUpdate } };
|
|
48
|
+
if ((await branchHead(context, repo, into)) === intoHead) {
|
|
49
|
+
throw storageUnavailable(`push to ${refUpdate.ref}`, pushed.reason);
|
|
50
|
+
}
|
|
51
|
+
return { kind: 'stale', intoHead };
|
|
52
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { RefUpdate } from '@leed-ai/git-gateway-contract/schemas/ref-update';
|
|
3
|
+
import { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';
|
|
4
|
+
import { isCoreError } from '@leed-ai/git-gateway-core/core-error';
|
|
5
|
+
import type { GitObject } from '@leed-ai/git-gateway-core/schemas/git-object';
|
|
6
|
+
import { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';
|
|
7
|
+
|
|
8
|
+
import type { GatewayContext } from './gateway-context.ts';
|
|
9
|
+
|
|
10
|
+
/** What became of one pushed ref update. */
|
|
11
|
+
export type PushOutcome =
|
|
12
|
+
| { readonly status: 'ok' }
|
|
13
|
+
/** The host refused the update: normally because the ref no longer names `oldSha`. */
|
|
14
|
+
| { readonly status: 'refused'; readonly reason: string };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Pushes one ref update with the objects it needs, in one git-receive-pack request through a
|
|
18
|
+
* freshly minted write remote. The update names the old id, so the host refuses it when the ref
|
|
19
|
+
* moved in the meantime: nothing is ever overwritten and nothing is forced. Transport failures
|
|
20
|
+
* and a pack the host could not unpack throw storage_unavailable; the credential never leaves
|
|
21
|
+
* this function. An accepted update is passed to the deployment's onPush hook.
|
|
22
|
+
*/
|
|
23
|
+
export async function pushRefUpdate(
|
|
24
|
+
context: GatewayContext,
|
|
25
|
+
repo: string,
|
|
26
|
+
update: RefUpdate,
|
|
27
|
+
objects: readonly GitObject[],
|
|
28
|
+
): Promise<PushOutcome> {
|
|
29
|
+
const remote = await context.backend.gitRemote(repo, 'write');
|
|
30
|
+
const client = new GitHttpClient(remote, context.fetch === undefined ? {} : { fetch: context.fetch });
|
|
31
|
+
let report;
|
|
32
|
+
try {
|
|
33
|
+
report = await client.push([update], objects);
|
|
34
|
+
} catch (thrown) {
|
|
35
|
+
if (isCoreError(thrown)) throw storageUnavailable(`push to ${update.ref}`, thrown);
|
|
36
|
+
throw thrown;
|
|
37
|
+
}
|
|
38
|
+
if (report.unpack !== 'ok') throw storageUnavailable(`push to ${update.ref}`, `unpack ${report.unpack}`);
|
|
39
|
+
const status = report.refs.find((entry) => entry.ref === update.ref);
|
|
40
|
+
if (status === undefined) throw storageUnavailable(`push to ${update.ref}`, 'no status for the ref');
|
|
41
|
+
if (status.status !== 'ok') return { status: 'refused', reason: status.reason };
|
|
42
|
+
await notifyPush(context, repo, update);
|
|
43
|
+
return { status: 'ok' };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Tells the deployment's onPush hook about an accepted update; a hook failure is reported, not thrown. */
|
|
47
|
+
async function notifyPush(context: GatewayContext, repo: string, update: RefUpdate): Promise<void> {
|
|
48
|
+
if (context.onPush === undefined) return;
|
|
49
|
+
try {
|
|
50
|
+
await context.onPush({ repo, updates: [update], pushedAt: context.now().toISOString() });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
context.onPushError(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import type { RpcOutput, RpcParsedInput } from '@leed-ai/git-gateway-contract/git-gateway';
|
|
3
|
+
import { byteOrder, encodeContent } from '@leed-ai/git-gateway-contract/reference/bytes';
|
|
4
|
+
import type { TreeEntry } from '@leed-ai/git-gateway-contract/schemas/tree-entry';
|
|
5
|
+
import { storageUnavailable } from '@leed-ai/git-gateway-contract/storage/storage-errors';
|
|
6
|
+
|
|
7
|
+
import { CommitGraph } from './commit-graph.ts';
|
|
8
|
+
import type { GatewayContext } from './gateway-context.ts';
|
|
9
|
+
import { historyPage } from './history-page.ts';
|
|
10
|
+
import { branchHead, entryAt, requireRevision, resolveRevision } from './repo-access.ts';
|
|
11
|
+
|
|
12
|
+
const join = (dir: string, name: string): string => (dir === '' ? name : `${dir}/${name}`);
|
|
13
|
+
|
|
14
|
+
/** readFile(): the file at a path, or null when the path is absent or not a file. */
|
|
15
|
+
export async function gatewayReadFile(
|
|
16
|
+
context: GatewayContext,
|
|
17
|
+
{ repo, ref, path, encoding }: RpcParsedInput<'readFile'>,
|
|
18
|
+
): Promise<RpcOutput<'readFile'>> {
|
|
19
|
+
const commit = await requireRevision(context, repo, ref);
|
|
20
|
+
const entry = await entryAt(context, repo, commit.tree, path);
|
|
21
|
+
if (entry === null || entry.type !== 'blob') return null;
|
|
22
|
+
const data = await context.backend.readBlob(repo, entry.sha);
|
|
23
|
+
if (data === null) throw storageUnavailable(`read ${path}`, `blob ${entry.sha} is missing`);
|
|
24
|
+
return {
|
|
25
|
+
path,
|
|
26
|
+
commit: commit.sha,
|
|
27
|
+
sha: entry.sha,
|
|
28
|
+
size: data.length,
|
|
29
|
+
executable: entry.mode === '100755',
|
|
30
|
+
...encodeContent(data, encoding),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Every entry beneath a tree, one level or all levels, with full paths, sorted in byte order. */
|
|
35
|
+
async function listEntries(
|
|
36
|
+
context: GatewayContext,
|
|
37
|
+
repo: string,
|
|
38
|
+
tree: string,
|
|
39
|
+
dir: string,
|
|
40
|
+
recursive: boolean,
|
|
41
|
+
): Promise<TreeEntry[]> {
|
|
42
|
+
const listed: TreeEntry[] = [];
|
|
43
|
+
let pending = [{ sha: tree, path: dir }];
|
|
44
|
+
while (pending.length > 0) {
|
|
45
|
+
const levels = await Promise.all(
|
|
46
|
+
pending.map(async (at) => ({ at, entries: await context.backend.readTree(repo, at.sha) })),
|
|
47
|
+
);
|
|
48
|
+
pending = [];
|
|
49
|
+
for (const { at, entries } of levels) {
|
|
50
|
+
for (const entry of entries ?? []) {
|
|
51
|
+
const path = join(at.path, entry.name);
|
|
52
|
+
listed.push({ ...entry, path });
|
|
53
|
+
if (recursive && entry.type === 'tree') pending.push({ sha: entry.sha, path });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return listed.toSorted((a, b) => byteOrder(a.path, b.path));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** listTree(): a directory listing, or null when the path is absent or not a directory. */
|
|
61
|
+
export async function gatewayListTree(
|
|
62
|
+
context: GatewayContext,
|
|
63
|
+
{ repo, ref, path, recursive }: RpcParsedInput<'listTree'>,
|
|
64
|
+
): Promise<RpcOutput<'listTree'>> {
|
|
65
|
+
const commit = await requireRevision(context, repo, ref);
|
|
66
|
+
let tree = commit.tree;
|
|
67
|
+
if (path !== undefined) {
|
|
68
|
+
const entry = await entryAt(context, repo, commit.tree, path);
|
|
69
|
+
if (entry === null || entry.type !== 'tree') return null;
|
|
70
|
+
tree = entry.sha;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
commit: commit.sha,
|
|
74
|
+
path: path ?? null,
|
|
75
|
+
entries: await listEntries(context, repo, tree, path ?? '', recursive),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** resolveRef(): the commit a branch or commit id names, or null. */
|
|
80
|
+
export async function gatewayResolveRef(
|
|
81
|
+
context: GatewayContext,
|
|
82
|
+
{ repo, ref }: RpcParsedInput<'resolveRef'>,
|
|
83
|
+
): Promise<RpcOutput<'resolveRef'>> {
|
|
84
|
+
const commit = await resolveRevision(context, repo, ref);
|
|
85
|
+
return commit === null ? null : { sha: commit.sha };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* log(): a page of the history reachable from a revision, in the reference's order (newest
|
|
90
|
+
* committer date first, never a parent before its child), reading only as far back as the page
|
|
91
|
+
* needs (see {@link historyPage}).
|
|
92
|
+
*/
|
|
93
|
+
export async function gatewayLog(
|
|
94
|
+
context: GatewayContext,
|
|
95
|
+
{ repo, ref, limit, offset, since }: RpcParsedInput<'log'>,
|
|
96
|
+
): Promise<RpcOutput<'log'>> {
|
|
97
|
+
const start = await requireRevision(context, repo, ref);
|
|
98
|
+
return historyPage(new CommitGraph(context, repo), start, { limit, offset, since });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** commitExists(): whether the commit exists, and is reachable from `branch` when one is named. */
|
|
102
|
+
export async function gatewayCommitExists(
|
|
103
|
+
context: GatewayContext,
|
|
104
|
+
{ repo, sha, branch }: RpcParsedInput<'commitExists'>,
|
|
105
|
+
): Promise<RpcOutput<'commitExists'>> {
|
|
106
|
+
const graph = new CommitGraph(context, repo);
|
|
107
|
+
if ((await graph.commit(sha)) === null) return { exists: false };
|
|
108
|
+
if (branch === undefined) return { exists: true };
|
|
109
|
+
const head = await branchHead(context, repo, branch);
|
|
110
|
+
return { exists: head !== null && (await graph.contains(head, sha)) };
|
|
111
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { utf8 } from '@leed-ai/git-gateway-contract/reference/bytes';
|
|
3
|
+
import { RepoName } from '@leed-ai/git-gateway-contract/schemas/names';
|
|
4
|
+
import { bytesToHex } from '@leed-ai/git-gateway-core/bytes';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
|
|
7
|
+
/** Every read token starts with this prefix, so secret scanners and the proxy can recognise one. */
|
|
8
|
+
export const READ_TOKEN_PREFIX = 'ggr_';
|
|
9
|
+
|
|
10
|
+
/** The secret read tokens are signed with. */
|
|
11
|
+
export const ReadTokenSecret = z
|
|
12
|
+
.string()
|
|
13
|
+
.min(32)
|
|
14
|
+
.max(4096)
|
|
15
|
+
.meta({
|
|
16
|
+
id: 'ReadTokenSecret',
|
|
17
|
+
title: 'Read-token secret',
|
|
18
|
+
description:
|
|
19
|
+
'The HMAC-SHA256 key that signs and verifies read tokens: 32–4096 characters of high-entropy secret, set as a Worker secret. Rotating it invalidates every token issued.',
|
|
20
|
+
examples: ['0123456789abcdef0123456789abcdef'],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** What a read token asserts. */
|
|
24
|
+
export const ReadTokenClaims = z
|
|
25
|
+
.object({
|
|
26
|
+
v: z.literal(1).describe('Token format version; always 1.'),
|
|
27
|
+
repo: RepoName.describe('The one repository the token may clone and fetch.'),
|
|
28
|
+
iat: z.int().min(0).describe('When the token was issued, in whole seconds since the Unix epoch.'),
|
|
29
|
+
exp: z
|
|
30
|
+
.int()
|
|
31
|
+
.min(0)
|
|
32
|
+
.describe('When the token stops working, in whole seconds since the Unix epoch; after `iat`.'),
|
|
33
|
+
jti: z
|
|
34
|
+
.string()
|
|
35
|
+
.regex(/^[0-9a-f]{32}$/)
|
|
36
|
+
.describe('Random token id, 32 lowercase hex digits, so two tokens issued together differ.'),
|
|
37
|
+
})
|
|
38
|
+
.strict()
|
|
39
|
+
.refine((claims) => claims.exp > claims.iat, { message: 'exp must be after iat', path: ['exp'] })
|
|
40
|
+
.meta({
|
|
41
|
+
id: 'ReadTokenClaims',
|
|
42
|
+
title: 'Read-token claims',
|
|
43
|
+
description:
|
|
44
|
+
'What a read token from mintReadToken() asserts: read access to one repository until `exp`. Signed with HMAC-SHA256; carries no storage-host credential.',
|
|
45
|
+
examples: [
|
|
46
|
+
{ v: 1, repo: 'acme-raw-content', iat: 1_795_000_000, exp: 1_795_003_600, jti: '0'.repeat(32) },
|
|
47
|
+
],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
/** Read-token claims, inferred from {@link ReadTokenClaims}. */
|
|
51
|
+
export type ReadTokenClaims = z.infer<typeof ReadTokenClaims>;
|
|
52
|
+
|
|
53
|
+
function base64Url(bytes: Uint8Array): string {
|
|
54
|
+
let binary = '';
|
|
55
|
+
for (const byte of bytes) binary += String.fromCodePoint(byte);
|
|
56
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function fromBase64Url(text: string): Uint8Array | null {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) return null;
|
|
61
|
+
try {
|
|
62
|
+
const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/'));
|
|
63
|
+
return Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function hmacKey(secret: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {
|
|
70
|
+
const key = utf8(ReadTokenSecret.parse(secret));
|
|
71
|
+
return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Options of {@link mintReadToken}. */
|
|
75
|
+
export interface MintReadTokenOptions {
|
|
76
|
+
readonly repo: string;
|
|
77
|
+
readonly ttlSeconds: number;
|
|
78
|
+
readonly secret: string;
|
|
79
|
+
readonly now: Date;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Issues a read token for one repository: `ggr_<claims>.<signature>`, both base64url, the claims
|
|
84
|
+
* JSON signed with HMAC-SHA256 under `secret`. The token is a credential: return it to the caller
|
|
85
|
+
* and nowhere else (never into a log or a Workflow step result).
|
|
86
|
+
*/
|
|
87
|
+
export async function mintReadToken(
|
|
88
|
+
options: MintReadTokenOptions,
|
|
89
|
+
): Promise<{ token: string; expiresAt: string }> {
|
|
90
|
+
const iat = Math.floor(options.now.getTime() / 1000);
|
|
91
|
+
const claims = ReadTokenClaims.parse({
|
|
92
|
+
v: 1,
|
|
93
|
+
repo: options.repo,
|
|
94
|
+
iat,
|
|
95
|
+
exp: iat + options.ttlSeconds,
|
|
96
|
+
jti: bytesToHex(crypto.getRandomValues(new Uint8Array(16))),
|
|
97
|
+
});
|
|
98
|
+
const payload = base64Url(utf8(JSON.stringify(claims)));
|
|
99
|
+
const key = await hmacKey(options.secret, 'sign');
|
|
100
|
+
const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, utf8(payload)));
|
|
101
|
+
return {
|
|
102
|
+
token: `${READ_TOKEN_PREFIX}${payload}.${base64Url(signature)}`,
|
|
103
|
+
expiresAt: new Date(claims.exp * 1000).toISOString(),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Checks a read token: its signature under `secret` (compared in constant time by WebCrypto),
|
|
109
|
+
* its claims and its expiry against `now`. Returns the claims of a valid token and null for
|
|
110
|
+
* anything else — malformed, forged, signed with another secret or expired. An authenticator
|
|
111
|
+
* grants read access to `claims.repo` and nothing more.
|
|
112
|
+
*/
|
|
113
|
+
export async function verifyReadToken(
|
|
114
|
+
token: string,
|
|
115
|
+
secret: string,
|
|
116
|
+
now: Date = new Date(),
|
|
117
|
+
): Promise<ReadTokenClaims | null> {
|
|
118
|
+
if (!token.startsWith(READ_TOKEN_PREFIX) || token.length > 4096) return null;
|
|
119
|
+
const [payload, signature, ...rest] = token.slice(READ_TOKEN_PREFIX.length).split('.');
|
|
120
|
+
if (payload === undefined || signature === undefined || rest.length > 0) return null;
|
|
121
|
+
const signatureBytes = fromBase64Url(signature);
|
|
122
|
+
const payloadBytes = fromBase64Url(payload);
|
|
123
|
+
if (signatureBytes === null || payloadBytes === null) return null;
|
|
124
|
+
const key = await hmacKey(secret, 'verify');
|
|
125
|
+
if (!(await crypto.subtle.verify('HMAC', key, signatureBytes, utf8(payload)))) return null;
|
|
126
|
+
let decoded: unknown;
|
|
127
|
+
try {
|
|
128
|
+
decoded = JSON.parse(new TextDecoder().decode(payloadBytes));
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
const claims = ReadTokenClaims.safeParse(decoded);
|
|
133
|
+
if (!claims.success) return null;
|
|
134
|
+
return claims.data.exp * 1000 > now.getTime() ? claims.data : null;
|
|
135
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { gatewayError } from '@leed-ai/git-gateway-contract/gateway-error';
|
|
3
|
+
import type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';
|
|
4
|
+
import { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';
|
|
5
|
+
import { repoNotFound } from '@leed-ai/git-gateway-contract/storage/storage-errors';
|
|
6
|
+
import type { StorageRepoInfo } from '@leed-ai/git-gateway-contract/storage/storage-repo-info';
|
|
7
|
+
import type { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';
|
|
8
|
+
import { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';
|
|
9
|
+
import type { TreeReader } from '@leed-ai/git-gateway-core/tree/tree-reader';
|
|
10
|
+
|
|
11
|
+
import type { GatewayContext } from './gateway-context.ts';
|
|
12
|
+
|
|
13
|
+
/** The fully qualified ref of a branch. */
|
|
14
|
+
export const branchRef = (branch: string): string => `refs/heads/${branch}`;
|
|
15
|
+
|
|
16
|
+
/** The repository's description, or repo_not_found. */
|
|
17
|
+
export async function requireRepo(context: GatewayContext, repo: string): Promise<StorageRepoInfo> {
|
|
18
|
+
const info = await context.backend.repoInfo(repo);
|
|
19
|
+
if (info === null) throw repoNotFound(repo);
|
|
20
|
+
return info;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The head of a branch, or null when it does not exist. */
|
|
24
|
+
export function branchHead(context: GatewayContext, repo: string, branch: string): Promise<string | null> {
|
|
25
|
+
return context.backend.resolveRef(repo, branchRef(branch));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The head of a branch, or ref_not_found naming it. */
|
|
29
|
+
export async function requireBranchHead(
|
|
30
|
+
context: GatewayContext,
|
|
31
|
+
repo: string,
|
|
32
|
+
branch: string,
|
|
33
|
+
): Promise<string> {
|
|
34
|
+
const head = await branchHead(context, repo, branch);
|
|
35
|
+
if (head === null) throw gatewayError('ref_not_found', `Branch not found: ${branch}`, { ref: branch });
|
|
36
|
+
return head;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A commit the repository must have (it was named by a ref), or storage_unavailable. */
|
|
40
|
+
export async function requireCommit(context: GatewayContext, repo: string, sha: string): Promise<Commit> {
|
|
41
|
+
const commit = await context.backend.readCommit(repo, sha);
|
|
42
|
+
if (commit === null) {
|
|
43
|
+
throw gatewayError('storage_unavailable', `Storage backend failed: commit ${sha} is missing`, {
|
|
44
|
+
retryable: true,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return commit;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The commit a revision names: a 40-hex commit id is read as a commit (never a branch), anything
|
|
52
|
+
* else as a branch name. Null when there is no such commit or branch.
|
|
53
|
+
*/
|
|
54
|
+
export async function resolveRevision(
|
|
55
|
+
context: GatewayContext,
|
|
56
|
+
repo: string,
|
|
57
|
+
revision: string,
|
|
58
|
+
): Promise<Commit | null> {
|
|
59
|
+
if (Sha.safeParse(revision).success) return context.backend.readCommit(repo, revision);
|
|
60
|
+
const head = await branchHead(context, repo, revision);
|
|
61
|
+
return head === null ? null : requireCommit(context, repo, head);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The commit a revision names, or ref_not_found. */
|
|
65
|
+
export async function requireRevision(
|
|
66
|
+
context: GatewayContext,
|
|
67
|
+
repo: string,
|
|
68
|
+
revision: string,
|
|
69
|
+
): Promise<Commit> {
|
|
70
|
+
const commit = await resolveRevision(context, repo, revision);
|
|
71
|
+
if (commit === null) throw gatewayError('ref_not_found', `Ref not found: ${revision}`, { ref: revision });
|
|
72
|
+
return commit;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A {@link TreeReader} over the repository's trees. */
|
|
76
|
+
export function treeReader(context: GatewayContext, repo: string): TreeReader {
|
|
77
|
+
return { readTree: (sha) => context.backend.readTree(repo, sha) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The entry a path names beneath a root tree, reading one tree per segment, or null when some
|
|
82
|
+
* segment is missing or a parent is not a directory.
|
|
83
|
+
*/
|
|
84
|
+
export async function entryAt(
|
|
85
|
+
context: GatewayContext,
|
|
86
|
+
repo: string,
|
|
87
|
+
rootTree: string,
|
|
88
|
+
path: string,
|
|
89
|
+
): Promise<StorageTreeEntry | null> {
|
|
90
|
+
let tree = rootTree;
|
|
91
|
+
let found: StorageTreeEntry | null = null;
|
|
92
|
+
for (const segment of path.split('/')) {
|
|
93
|
+
if (found !== null && found.type !== 'tree') return null;
|
|
94
|
+
const entries = await context.backend.readTree(repo, tree);
|
|
95
|
+
found = entries?.find((entry) => entry.name === segment) ?? null;
|
|
96
|
+
if (found === null) return null;
|
|
97
|
+
tree = found.sha;
|
|
98
|
+
}
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Whether the repository has any branch at all, read from the ref advertisement of its git
|
|
104
|
+
* remote (the storage contract has no "list refs" call). Only asked when a commit names a branch
|
|
105
|
+
* that does not exist, to decide between a root commit and ref_not_found.
|
|
106
|
+
*/
|
|
107
|
+
export async function hasBranches(context: GatewayContext, repo: string): Promise<boolean> {
|
|
108
|
+
const remote = await context.backend.gitRemote(repo, 'read');
|
|
109
|
+
const client = new GitHttpClient(remote, context.fetch === undefined ? {} : { fetch: context.fetch });
|
|
110
|
+
const advertisement = await client.advertisement('git-upload-pack');
|
|
111
|
+
return advertisement.refs.some((ref) => ref.name.startsWith('refs/heads/'));
|
|
112
|
+
}
|