Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
repo-access.ts7.0 KB · 221 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
 * Repo access middleware — resolves a viewer's effective access level to a
 * repository and enforces a minimum-level gate on routes.
 *
 * Access hierarchy (ordered): none < read < write < admin < owner.
 *
 * The repo owner (repositories.ownerId === userId) always resolves to
 * "owner", regardless of any collaborator row. Beyond that, we look up an
 * ACCEPTED row in repo_collaborators (acceptedAt IS NOT NULL) and return the
 * stored role. If no row exists, public repos fall back to "read" for any
 * viewer (including anonymous); private repos return "none".
 *
 * The middleware factory reads `:owner` + `:repo` from the URL, looks up
 * the repository, computes the access level, stashes both on the context
 * (so downstream handlers don't re-query), and renders a 403 HTML page via
 * Layout if the caller's level is below the required minimum.
 *
 * Implementation notes:
 *  - Hono and JSX dependencies are loaded via *dynamic* `import()` inside
 *    `requireRepoAccess` so that `resolveRepoAccess` — the pure, unit-
 *    testable half — has no static hono/hono-jsx imports at module load.
 *    This lets `bun test` run the logic tests without needing the full
 *    hono runtime (notably `hono/jsx/jsx-dev-runtime`, which a given
 *    install may not have yet when the schema/parallel agent ships).
 *  - The middleware signature `(c, next) => Promise<Response | void>`
 *    matches Hono's `MiddlewareHandler` structurally without importing
 *    the type; routes can pass this directly to `.use()` / handler chains.
 */

import { and, eq, isNotNull } from "drizzle-orm";
import { db } from "../db";
import { repositories, users, repoCollaborators } from "../db/schema";
import type { Repository, User } from "../db/schema";

export type RepoAccessLevel = "none" | "read" | "write" | "admin" | "owner";

/**
 * Ordered access hierarchy. Higher index = more access. Use `ACCESS_RANK`
 * to compare two levels; callers should prefer {@link satisfiesAccess}.
 */
export const ACCESS_RANK: Record<RepoAccessLevel, number> = {
  none: 0,
  read: 1,
  write: 2,
  admin: 3,
  owner: 4,
};

/** True if `actual` meets or exceeds `required`. */
export function satisfiesAccess(
  actual: RepoAccessLevel,
  required: RepoAccessLevel
): boolean {
  return ACCESS_RANK[actual] >= ACCESS_RANK[required];
}

/**
 * Env type for Hono routes that sit behind `requireRepoAccess`. Extends the
 * existing auth variables — `user` is populated by softAuth/requireAuth,
 * `repository` and `repoAccess` are populated here.
 */
export type RepoAccessEnv = {
  Variables: {
    user: User | null;
    repository: Repository;
    repoAccess: RepoAccessLevel;
  };
};

/**
 * Pure access resolution — no HTTP, no context. Exposed so callers (e.g.
 * API responses, view-layer conditionals, tests) can ask "what can this
 * user do with this repo?" without running the middleware.
 */
export async function resolveRepoAccess(args: {
  repoId: string;
  userId: string | null;
  isPublic: boolean;
}): Promise<RepoAccessLevel> {
  const { repoId, userId, isPublic } = args;

  // Anonymous viewer: only public repos grant anything, and only "read".
  if (!userId) {
    return isPublic ? "read" : "none";
  }

  // Owner check — look up the repo row once. If the caller IS the owner,
  // short-circuit before hitting repo_collaborators.
  try {
    const [repo] = await db
      .select({ ownerId: repositories.ownerId })
      .from(repositories)
      .where(eq(repositories.id, repoId))
      .limit(1);

    if (repo && repo.ownerId === userId) {
      return "owner";
    }
  } catch {
    // Fall through — if the owner lookup fails we still try the
    // collaborator path below (which may also fail, in which case we'll
    // end up at the public/private fallback).
  }

  // Accepted collaborator row wins over the public fallback.
  try {
    const [collab] = await db
      .select({ role: repoCollaborators.role })
      .from(repoCollaborators)
      .where(
        and(
          eq(repoCollaborators.repositoryId, repoId),
          eq(repoCollaborators.userId, userId),
          isNotNull(repoCollaborators.acceptedAt)
        )
      )
      .limit(1);

    if (collab) {
      return collab.role as RepoAccessLevel;
    }
  } catch {
    // Ignore — fall through to public/private fallback.
  }

  return isPublic ? "read" : "none";
}

/**
 * Middleware factory: gate a route on a minimum access level.
 *
 * Assumes the URL has `:owner` and `:repo` params. Looks up the repository,
 * 404s if it doesn't exist, resolves the viewer's access, and 403s if the
 * viewer is below `level`. On success, sets `c.var.repository` and
 * `c.var.repoAccess` for downstream handlers.
 *
 * Returns a bare `(c, next)` async function — structurally compatible with
 * Hono's `MiddlewareHandler`. Hono is loaded lazily inside the handler so
 * the unit-testable exports above don't force-import the jsx runtime.
 */
export function requireRepoAccess(
  level: "read" | "write" | "admin"
): (c: any, next: () => Promise<void>) => Promise<Response | void> {
  return async (c: any, next: () => Promise<void>) => {
    const { owner: ownerName, repo: repoName } = c.req.param() as {
      owner?: string;
      repo?: string;
    };
    const user: User | null = c.get("user") ?? null;

    if (!ownerName || !repoName) {
      return c.notFound();
    }

    // Resolve owner -> user row, then repo by (owner, name).
    const [ownerRow] = await db
      .select()
      .from(users)
      .where(eq(users.username, ownerName))
      .limit(1);

    if (!ownerRow) {
      return c.notFound();
    }

    const [repo] = await db
      .select()
      .from(repositories)
      .where(
        and(
          eq(repositories.ownerId, ownerRow.id),
          eq(repositories.name, repoName)
        )
      )
      .limit(1);

    if (!repo) {
      return c.notFound();
    }

    const access = await resolveRepoAccess({
      repoId: repo.id,
      userId: user?.id ?? null,
      isPublic: !repo.isPrivate,
    });

    if (!satisfiesAccess(access, level)) {
      const reason =
        access === "none"
          ? "You don't have permission to view this repository."
          : `This action requires ${level} access. You have ${access} access.`;
      // Lazy-load hono/jsx + Layout so the top of this module is safe to
      // import from unit tests that can't resolve the jsx runtime.
      const [{ jsx }, { Layout }] = await Promise.all([
        import("hono/jsx"),
        import("../views/layout"),
      ]);
      const body = jsx(
        "div",
        {
          style:
            "max-width: 600px; margin: 80px auto; padding: 24px; text-align: center;",
        },
        [
          jsx("h1", { style: "margin-bottom: 12px" }, ["403 — Access denied"]),
          jsx("p", { style: "color: var(--muted, #8b949e)" }, [reason]),
        ]
      );
      const page = jsx(
        Layout as any,
        { title: "Access denied", user },
        [body]
      );
      return c.html(page, 403);
    }

    c.set("repoAccess", access);
    c.set("repository", repo);
    return next();
  };
}