Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/105-repo-members.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Written-by: HugoXK

A repository can be shared with its members: the dashboard, repository page,
work items and jobs are visible to every active `repo_members` row, a `viewer`
reads without writing, a `developer` works without changing the merge policy,
and only a `maintainer` writes repository settings, changes the role, deletes
the repository, publishes a release or stops and restarts its workspace.
30 changes: 28 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -2357,8 +2357,34 @@ grants and the legacy `repos.user_id` owner. `maintainer`, `developer` and
`admin` gets `grants.manage` and repository capabilities only through a
membership or grant. `GET /api/auth/me` is the first read surface: it requires an
approved session and returns the user summary, tenant/project roles,
capabilities and platform capabilities without a token or key column. Enforcement
on read and write routes remains a later slice.
capabilities and platform capabilities without a token or key column.

## Shared repository read path (#105, slice 1)

Repository membership reaches the product surfaces here. `Store.listRepos`,
`listReposPage` and `countReposForViewer` include every repository with an active
`repo_members` row for the viewer, so the dashboard and its total describe what
the person can see rather than what they connected. The owner-only
`countReposForUser` stays the connection-limit count, because a shared repository
is the owner's connection and must not consume a member's own repository limit.

Every `/repos/:id` route resolves the viewer through `ownedRepo`: the connection
owner is the maintainer of last resort, an active member row supplies its own
role, and a missing repository and a non-member answer the same 404 so an id does
not leak. A `viewer` reads but any mutating route answers 403; repository
settings (merge policy, target branch, role gate, auto-merge) require
`maintainer`, and so do the routes that are settings in effect or can end the
connection: `POST /repos/:id/role` (it writes the same `repo_role` column as the
settings form and clears `auto_merge`), `/delete`, `/release`, `/enable`,
`/disable`, `/instance`, `/instance/stop` and `/models/apply`. A `developer`
keeps the work routes — `/work`, `/run`, `/plan`, `/triage`, `/review` and the
job actions — and `/run` is resolved through `ownedRepo` like the other starts,
so it answers for a member instead of the 404 a stranger gets. The member write path — `addRepoMember`, `setRepoMemberRole`,
`removeRepoMember` — validates the capability vocabulary and refuses to remove
the connection owner, which is what keeps a repository with a maintainer.
Invitations, accept/leave/transfer, the audit rows for each membership change and
member-aware controls in the views are the following slices; no route shown to a
viewer writes yet.

## Notification webhook egress

Expand Down
61 changes: 45 additions & 16 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -830,11 +830,33 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
return true
}

const ownedRepo = (request: FastifyRequest, id: string, mutating = false) => {
// #105: a repository is shared with its active members. The connection owner
// stays the maintainer of last resort; a member row carries `maintainer`,
// `developer` or `viewer`. Reads are open to every active member, writes need
// developer or better, and repository settings need maintainer. A non-member
// and a missing repository answer the same 404 so an id does not leak.
// `maintainOnly` also covers the destructive and lifecycle routes: the role
// and settings forms write the same `repo_role`/`auto_merge` columns, and
// delete, release, enable/disable, the workspace controls and the model apply
// are settings in effect. A developer keeps the work routes (`/work`,
// `/run`, `/plan`, `/triage`, `/review` and job actions), never the ones that
// can destroy the connection or change who may use it.
const ownedRepo = (request: FastifyRequest, id: string, mutating = false, maintainOnly = false) => {
const viewer = mutating ? approvedCsrfGuard(request) : requireApproved(request)
const repo = store.getRepo(id)
if (repo === undefined || repo.user_id !== viewer.user.id) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND')
return { viewer, repo }
const role = repo === undefined
? null
: repo.user_id === viewer.user.id
? 'maintainer'
: store.memberRoleFor(repo.id, viewer.user.id)
if (repo === undefined || role === null) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND')
if (mutating && role === 'viewer') {
throw httpError(403, '只读成员不能修改这个仓库。', 'A viewer cannot change this repository.')
}
if (maintainOnly && role !== 'maintainer') {
throw httpError(403, '只有维护者可以修改仓库设置。', 'Only a maintainer can change repository settings.')
}
return { viewer, repo, role }
}

// #543: a plan carries the SHA it was analysed at. Resolving the default
Expand Down Expand Up @@ -1395,7 +1417,9 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
{ repo: queryText(request, 'repo'), status: queryText(request, 'status'), kind: queryText(request, 'kind'), priority: queryText(request, 'priority') },
allRepos.map((repo) => repo.id),
)
const reposTotal = store.countReposForUser(viewer.user.id)
// #105: the dashboard lists shared repositories too, so its total counts
// what this viewer can see rather than what they own.
const reposTotal = store.countReposForViewer(viewer.user.id)
const jobsTotal = store.countJobsForUser(viewer.user.id, jobFilter)
const pageNumber = (name: string, total: number): number => {
const pages = Math.max(1, Math.ceil(total / perPage))
Expand Down Expand Up @@ -2458,7 +2482,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
// is read-only; only a plan that passes every check reaches the tag write, and
// the tag is annotated and created through the repository's installation token.
app.post('/repos/:id/release', async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
const body = form(request)
const version = String(body.version ?? '').trim()
const targetSha = String(body.sha ?? '').trim().toLowerCase()
Expand Down Expand Up @@ -3907,9 +3931,10 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
// #708: starting a job spends a model budget and a FlyBot slot, so it takes
// the expensive window before the repository is read.
if (!limits.take('expensive', `job-start:${rateLimitKey(request)}`)) return refuseTooMany(request, reply)
const viewer = approvedCsrfGuard(request)
const repo = store.getRepo(String((request.params as Record<string, string>).id))
if (repo === undefined || repo.user_id !== viewer.user.id) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND')
// #105 review: this start reads the repository through `ownedRepo` like the
// other four member-facing starts, so a developer member starts work instead
// of getting the 404 a stranger gets.
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const t = translator(request.locale ?? 'zh')
const outcome = await runCreate(request, viewer, repo, { kind: repo.plan_required === 1 ? 'plan' : 'iterate' })
if (!outcome.ok) {
Expand Down Expand Up @@ -4033,7 +4058,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/instance', async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
if (config.flybot.instanceImage === '') throw httpError(400, 'FlyBot 实例未配置', 'INSTANCE_DISABLED')
// #457 review: the guard used to run before this route knew the repository
// already had a row, so a stopped instance counted against its own restart
Expand All @@ -4049,7 +4074,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/instance/stop', { config: { rateLimit: destructiveLimit } }, async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
if (requireRecentAuth(request, reply, viewer, 'flybot.instance.stop')) return reply
await instances.stop(repo.id)
await jobs.cancelRepoJobs(repo.id, 'FlyBot 实例已停止', 'BRIDGE_ERROR')
Expand All @@ -4068,7 +4093,9 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/role', { config: { rateLimit: destructiveClassLimit } }, async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
// #105 review: this route writes the same `repo_role` column as the settings
// form, so it carries the settings rule.
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
const body = form(request)
const t = translator(request.locale ?? 'zh')
const role = parseRepoRole(body.role)
Expand All @@ -4089,7 +4116,9 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/settings', { config: { rateLimit: destructiveLimit } }, async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
// #105: settings decide the merge policy and the role gate, so a developer
// member reads them but cannot write them.
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
const body = form(request)
const interval = normalizeInterval(body.interval, repo.interval_minutes)
const reviewInterval = normalizeInterval(body.reviewInterval, repo.review_interval_minutes)
Expand Down Expand Up @@ -4237,7 +4266,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/models/apply', async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
try {
const result = await instances.applyModels(repo.id)
if (!result.ok) return reply.redirect(`/repos/${repo.id}?error=${encodeURIComponent(result.error ?? '模型应用失败。')}#repo-settings`)
Expand All @@ -4249,22 +4278,22 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
})

app.post('/repos/:id/enable', async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
store.updateRepo(repo.id, { enabled: 1 })
store.audit(viewer.user.id, 'repo.enabled', `${repo.owner}/${repo.name}`)
return reply.redirect(`/repos/${repo.id}?notice=${encodeURIComponent('仓库已启用;自动迭代不会自动打开,需要时在设置里开启。')}`)
})

app.post('/repos/:id/disable', async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
store.updateRepo(repo.id, { enabled: 0, auto_iterate: 0 })
await jobs.cancelRepoJobs(repo.id, '仓库已停用', 'REPO_DISABLED')
store.audit(viewer.user.id, 'repo.disabled', `${repo.owner}/${repo.name}`)
return reply.redirect(`/repos/${repo.id}?notice=${encodeURIComponent('仓库已停用,任务不会再运行。')}`)
})

app.post('/repos/:id/delete', { config: { rateLimit: destructiveLimit } }, async (request, reply) => {
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true)
const { viewer, repo } = ownedRepo(request, String((request.params as Record<string, string>).id), true, true)
if (requireRecentAuth(request, reply, viewer, 'repo.delete', `/repos/${repo.id}#danger`)) return reply
const confirmName = (form(request).confirmName ?? '').trim()
if (confirmName !== repo.name && confirmName !== `${repo.owner}/${repo.name}`) {
Expand Down
78 changes: 76 additions & 2 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5102,18 +5102,92 @@ export class Store {
return repo
}

// #105: a repository is visible to its connection owner and to every active
// member. The owner keeps the credential, the instance and the quota; sharing
// starts with the read path (dashboard, repository page, work items, jobs).
listRepos(userId: string): RepoRow[] {
return this.all<RepoRow>('SELECT * FROM repos WHERE user_id = ? ORDER BY created_at DESC', userId)
return this.all<RepoRow>(
`SELECT * FROM repos
WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL)
ORDER BY created_at DESC`,
userId,
userId,
)
}

listReposPage(userId: string, limit: number, offset: number): RepoRow[] {
return this.all<RepoRow>('SELECT * FROM repos WHERE user_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?', userId, limit, offset)
return this.all<RepoRow>(
`SELECT * FROM repos
WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL)
ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?`,
userId,
userId,
limit,
offset,
)
}

// The connection-limit count stays owner-only: a shared repository is the
// owner's connection and must not consume a member's own repository limit.
countReposForUser(userId: string): number {
return Number(this.get<{ n: number }>('SELECT COUNT(*) AS n FROM repos WHERE user_id = ?', userId)?.n ?? 0)
}

countReposForViewer(userId: string): number {
return Number(this.get<{ n: number }>(
'SELECT COUNT(*) AS n FROM repos WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL)',
userId,
userId,
)?.n ?? 0)
}

// #105: the member rows already exist (the #541 identity backfill wrote the
// owner's). These methods are the write path a later invite slice exposes; the
// role vocabulary is the capability model's, so a member never gets a role the
// resolver cannot read.
listRepoMembers(repoId: string): RepoMemberRow[] {
return this.all<RepoMemberRow>('SELECT * FROM repo_members WHERE repo_id = ? AND revoked_at IS NULL ORDER BY created_at ASC', repoId)
}

memberRoleFor(repoId: string, userId: string): string | null {
const row = this.get<RepoMemberRow>('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId)
return row?.role ?? null
}

addRepoMember(input: { repoId: string; userId: string; role: string; grantedBy: string | null }): RepoMemberRow | undefined {
if (input.role !== 'maintainer' && input.role !== 'developer' && input.role !== 'viewer') return undefined
if (this.getRepo(input.repoId) === undefined || this.userById(input.userId) === undefined) return undefined
this.run(
`INSERT INTO repo_members (repo_id, user_id, role, granted_by, created_at, revoked_at) VALUES (?, ?, ?, ?, ?, NULL)
ON CONFLICT(repo_id, user_id) DO UPDATE SET role = excluded.role, granted_by = excluded.granted_by, revoked_at = NULL`,
input.repoId,
input.userId,
input.role,
input.grantedBy,
nowIso(),
)
return this.get<RepoMemberRow>('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ?', input.repoId, input.userId)
}

setRepoMemberRole(repoId: string, userId: string, role: string): boolean {
if (role !== 'maintainer' && role !== 'developer' && role !== 'viewer') return false
const row = this.get<RepoMemberRow>('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId)
if (row === undefined) return false
this.run('UPDATE repo_members SET role = ? WHERE repo_id = ? AND user_id = ?', role, repoId, userId)
return true
}

removeRepoMember(repoId: string, userId: string): boolean {
const row = this.get<RepoMemberRow>('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId)
if (row === undefined) return false
// #105: the connection owner is the maintainer of last resort and cannot be
// removed here; that is what keeps a repository with at least one maintainer.
const repo = this.getRepo(repoId)
if (repo !== undefined && repo.user_id === userId) return false
this.run('UPDATE repo_members SET revoked_at = ? WHERE repo_id = ? AND user_id = ?', nowIso(), repoId, userId)
return true
}

getRepo(id: string): RepoRow | undefined {
return this.get<RepoRow>('SELECT * FROM repos WHERE id = ?', id)
}
Expand Down
Loading
Loading