Phase 3C — Commit Summary
feat: workspaces — collaborative repo namespaces Backend - internal/models/workspace.go — Workspace (handle, displayName, description, createdBy) + WorkspaceMember (workspaceId, userId, username, role: owner/admin/member) - internal/models/repo.go — added nullable workspace_id column; existing user repos unaffected - internal/models/migrations/011_workspaces.go — syncs both tables + adds column to repository - internal/api/handlers/workspace.go — ListWorkspaces, CreateWorkspace, GetWorkspace, UpdateWorkspace, DeleteWorkspace (blocks if repos remain), ListRepos, ListMembers, AddMember, UpdateMember, RemoveMember - internal/api/handlers/repos.go — lookupRepo resolves workspace handles; Create accepts workspace field; List includes workspace member repos; withOwnerName uses workspace handle for workspace-owned repos - internal/api/handlers/dashboard.go — recentRuns + repo list include workspace repos the user is a member of - internal/api/router.go — /workspaces, /workspaces/:handle/* routes Workspace rules enforced: - Handle globally unique across usernames + workspace handles (409 on collision) - Creator auto-assigned owner role - Delete blocked if repos exist - Last owner cannot be demoted/removed --- feat: secret management hierarchy (Global → Workspace → Repo → Env) Backend - internal/models/secret.go — Secret struct + EncryptSecret/DecryptSecret with AES-256-GCM (key = SHA-256 of SESSION_SECRET); values never serialised to JSON - internal/models/migrations/012_secrets.go — syncs secret table - internal/api/handlers/secret.go — List/Upsert/Delete for all four scopes; ResolveSecretsForRun builds merged env map for CI - internal/domain/ci/executor.go — JobContext.Secrets field; secrets injected as --env KEY=VALUE into docker run; buildJobContext calls resolveSecrets(Global < Workspace < Repo < Env) - internal/domain/ci/runner_manager.go — passes cfg.SessionSecret to buildJobContext - internal/api/router.go — /repos/:owner/:repo/secrets, /environments/:envName/secrets, /workspaces/:handle/secrets, /admin/secrets --- feat: workspace + secret management UI Frontend - types/api.ts — Workspace, WorkspaceWithMeta, WorkspaceMember, SecretListItem types - api/queries/workspaces.ts — full CRUD hooks + WorkspaceRepo type - api/queries/secrets.ts — repo/env/workspace secret hooks - pages/WorkspacesPage.tsx — list + create modal - pages/WorkspacePage.tsx — workspace dashboard with repo list - pages/WorkspaceSettingsPage.tsx — general settings, members CRUD, workspace secrets, danger zone - pages/RepoSecretsPage.tsx — repo secrets + per-environment secret sections with priority hierarchy callout - pages/CreateRepoPage.tsx — ?workspace= query param pre-fills owner selector; only admin/owner workspaces shown - components/layout/Sidebar.tsx — "Workspaces" global nav item + workspace quick-links; "Secrets" in RepoSubNav; new SecretsIcon, WorkspaceIcon - App.tsx — routes for /workspaces, /workspaces/:handle, /workspaces/:handle/settings, /repos/:owner/:repo/secrets
This commit is contained in:
@@ -60,8 +60,8 @@ Understand the phases before adding code — don't build Phase 3 infrastructure
|
|||||||
| 2B | CI orchestrator, runner manager, Docker executor, artifact registry | **Complete** |
|
| 2B | CI orchestrator, runner manager, Docker executor, artifact registry | **Complete** |
|
||||||
| 2C | Pipeline DAG visualization, dashboard CI upgrade, command palette wiring | **Complete** |
|
| 2C | Pipeline DAG visualization, dashboard CI upgrade, command palette wiring | **Complete** |
|
||||||
| 3A | Environment model + deployment tracking | **Complete** |
|
| 3A | Environment model + deployment tracking | **Complete** |
|
||||||
| 3B | Unified operational timeline | **Active** |
|
| 3B | Unified operational timeline | **Complete** |
|
||||||
| 3C | Secret management hierarchy | Planned |
|
| 3C | Workspaces + secret management hierarchy | **Active** |
|
||||||
| 3D | GitOps controller + drift detection | Planned |
|
| 3D | GitOps controller + drift detection | Planned |
|
||||||
| 3E | Observability (Prometheus, health sparklines) | Planned |
|
| 3E | Observability (Prometheus, health sparklines) | Planned |
|
||||||
| 3F | Federation handlers (ActivityPub inbox/outbox) | Planned |
|
| 3F | Federation handlers (ActivityPub inbox/outbox) | Planned |
|
||||||
|
|||||||
+14
-1
@@ -9,7 +9,20 @@ Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### In Progress — Phase 3B (Unified Operational Timeline)
|
### In Progress — Phase 3C (Workspaces + Secret management hierarchy)
|
||||||
|
- `Workspace` model — named collaborative namespace (handle, displayName, description, avatarUrl)
|
||||||
|
- `WorkspaceMember` model — user membership with owner/admin/member roles
|
||||||
|
- Repos can be owned by a workspace; URL format stays `/{owner}/{repo}` where owner is a workspace handle or username
|
||||||
|
- `Secret` model — AES-256-GCM encrypted, scoped to global / workspace / repo / env
|
||||||
|
- Secret hierarchy resolution in CI executor: Env → Repo → Workspace → Global
|
||||||
|
- Full CRUD APIs for workspaces, workspace members, secrets at all scope levels
|
||||||
|
- WorkspacesPage, WorkspacePage, WorkspaceSettingsPage (settings + members)
|
||||||
|
- Workspace switcher in sidebar header
|
||||||
|
- Create repo: workspace owner selector
|
||||||
|
- RepoSecretsPage — write-only secret management per repo and per environment
|
||||||
|
- Sidebar "Secrets" nav item in repo context
|
||||||
|
|
||||||
|
### Completed — Phase 3B (Unified Operational Timeline)
|
||||||
- `GET /api/v1/repos/:owner/:repo/timeline` — merges commits, pipeline runs, and deployments into a single chronological feed
|
- `GET /api/v1/repos/:owner/:repo/timeline` — merges commits, pipeline runs, and deployments into a single chronological feed
|
||||||
- `RepoTimelinePage` at `/repos/:owner/:repo/timeline` — vertical event feed with type filter tabs
|
- `RepoTimelinePage` at `/repos/:owner/:repo/timeline` — vertical event feed with type filter tabs
|
||||||
- Sidebar "Timeline" nav item between Environments and Settings
|
- Sidebar "Timeline" nav item between Environments and Settings
|
||||||
|
|||||||
@@ -223,8 +223,9 @@ ForgeBucket has its own design language — intentionally distinct from GitHub a
|
|||||||
| Phase 2B | CI orchestrator, runner manager, Docker backend, artifact registry | Done |
|
| Phase 2B | CI orchestrator, runner manager, Docker backend, artifact registry | Done |
|
||||||
| Phase 2C | Pipeline DAG visualization, dashboard CI upgrade, command palette | Done |
|
| Phase 2C | Pipeline DAG visualization, dashboard CI upgrade, command palette | Done |
|
||||||
| Phase 3A | Environment model + deployment tracking | Done |
|
| Phase 3A | Environment model + deployment tracking | Done |
|
||||||
| Phase 3B | Unified operational timeline | **In progress** |
|
| Phase 3B | Unified operational timeline | Done |
|
||||||
| Phase 3C–F | Secrets, drift detection, federation, observability | Planned |
|
| Phase 3C | Workspaces + secret management hierarchy | **In progress** |
|
||||||
|
| Phase 3D–F | GitOps/drift, federation, observability | Planned |
|
||||||
| Phase 4 | AI diagnostics, signed artifacts, OCI registry, dep scanning | Planned |
|
| Phase 4 | AI diagnostics, signed artifacts, OCI registry, dep scanning | Planned |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+10
-2
@@ -37,8 +37,12 @@ const PRsPage = lazy(() => import('./pages/PRsPage'))
|
|||||||
const PipelinesPage = lazy(() => import('./pages/PipelinesPage'))
|
const PipelinesPage = lazy(() => import('./pages/PipelinesPage'))
|
||||||
const PipelineRunPage = lazy(() => import('./pages/PipelineRunPage'))
|
const PipelineRunPage = lazy(() => import('./pages/PipelineRunPage'))
|
||||||
const RepoPipelinesPage = lazy(() => import('./pages/RepoPipelinesPage'))
|
const RepoPipelinesPage = lazy(() => import('./pages/RepoPipelinesPage'))
|
||||||
const EnvironmentsPage = lazy(() => import('./pages/EnvironmentsPage'))
|
const EnvironmentsPage = lazy(() => import('./pages/EnvironmentsPage'))
|
||||||
const RepoTimelinePage = lazy(() => import('./pages/RepoTimelinePage'))
|
const RepoTimelinePage = lazy(() => import('./pages/RepoTimelinePage'))
|
||||||
|
const RepoSecretsPage = lazy(() => import('./pages/RepoSecretsPage'))
|
||||||
|
const WorkspacesPage = lazy(() => import('./pages/WorkspacesPage'))
|
||||||
|
const WorkspacePage = lazy(() => import('./pages/WorkspacePage'))
|
||||||
|
const WorkspaceSettingsPage = lazy(() => import('./pages/WorkspaceSettingsPage'))
|
||||||
const ProfilePage = lazy(() => import('./pages/ProfilePage'))
|
const ProfilePage = lazy(() => import('./pages/ProfilePage'))
|
||||||
const ExplorePage = lazy(() => import('./pages/ExplorePage'))
|
const ExplorePage = lazy(() => import('./pages/ExplorePage'))
|
||||||
const SettingsPage = lazy(() => import('./pages/SettingsPage'))
|
const SettingsPage = lazy(() => import('./pages/SettingsPage'))
|
||||||
@@ -89,11 +93,15 @@ export default function App() {
|
|||||||
<Route path="repos/:owner/:repo/pipelines" element={<S><RepoPipelinesPage /></S>} />
|
<Route path="repos/:owner/:repo/pipelines" element={<S><RepoPipelinesPage /></S>} />
|
||||||
<Route path="repos/:owner/:repo/environments" element={<S><EnvironmentsPage /></S>} />
|
<Route path="repos/:owner/:repo/environments" element={<S><EnvironmentsPage /></S>} />
|
||||||
<Route path="repos/:owner/:repo/timeline" element={<S><RepoTimelinePage /></S>} />
|
<Route path="repos/:owner/:repo/timeline" element={<S><RepoTimelinePage /></S>} />
|
||||||
|
<Route path="repos/:owner/:repo/secrets" element={<S><RepoSecretsPage /></S>} />
|
||||||
<Route path="repos/:owner/:repo/runs/:runId" element={<S><PipelineRunPage /></S>} />
|
<Route path="repos/:owner/:repo/runs/:runId" element={<S><PipelineRunPage /></S>} />
|
||||||
|
|
||||||
<Route path="starred" element={<S><StarredPage /></S>} />
|
<Route path="starred" element={<S><StarredPage /></S>} />
|
||||||
<Route path="pulls" element={<S><PRsPage /></S>} />
|
<Route path="pulls" element={<S><PRsPage /></S>} />
|
||||||
<Route path="pipelines" element={<S><PipelinesPage /></S>} />
|
<Route path="pipelines" element={<S><PipelinesPage /></S>} />
|
||||||
|
<Route path="workspaces" element={<S><WorkspacesPage /></S>} />
|
||||||
|
<Route path="workspaces/:handle" element={<S><WorkspacePage /></S>} />
|
||||||
|
<Route path="workspaces/:handle/settings" element={<S><WorkspaceSettingsPage /></S>} />
|
||||||
<Route path="explore" element={<S><ExplorePage /></S>} />
|
<Route path="explore" element={<S><ExplorePage /></S>} />
|
||||||
<Route path="profile" element={<S><ProfilePage /></S>} />
|
<Route path="profile" element={<S><ProfilePage /></S>} />
|
||||||
<Route path="settings" element={<S><SettingsPage /></S>} />
|
<Route path="settings" element={<S><SettingsPage /></S>} />
|
||||||
|
|||||||
@@ -186,6 +186,7 @@ export function useCreateRepo() {
|
|||||||
defaultBranch?: string
|
defaultBranch?: string
|
||||||
initReadme?: 'none' | 'blank' | 'tutorial'
|
initReadme?: 'none' | 'blank' | 'tutorial'
|
||||||
initGitignore?: boolean
|
initGitignore?: boolean
|
||||||
|
workspace?: string
|
||||||
}) => api.post<Repository>('/api/v1/repos', repositorySchema, data),
|
}) => api.post<Repository>('/api/v1/repos', repositorySchema, data),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { api } from '../client'
|
||||||
|
import type { SecretListItem } from '../../types/api'
|
||||||
|
|
||||||
|
const secretSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const secretsSchema = z.array(secretSchema)
|
||||||
|
|
||||||
|
// ── Repo secrets ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useRepoSecrets(owner: string, repo: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repos', owner, repo, 'secrets'],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<SecretListItem[]>(`/api/v1/repos/${owner}/${repo}/secrets`, secretsSchema),
|
||||||
|
enabled: Boolean(owner && repo),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpsertRepoSecret(owner: string, repo: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { name: string; value: string }) =>
|
||||||
|
api.post<SecretListItem>(`/api/v1/repos/${owner}/${repo}/secrets`, secretSchema, body),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteRepoSecret(owner: string, repo: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (name: string) =>
|
||||||
|
api.delete<void>(
|
||||||
|
`/api/v1/repos/${owner}/${repo}/secrets/${encodeURIComponent(name)}`,
|
||||||
|
z.unknown() as z.ZodType<void>,
|
||||||
|
),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Environment secrets ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useEnvSecrets(owner: string, repo: string, envName: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<SecretListItem[]>(
|
||||||
|
`/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets`,
|
||||||
|
secretsSchema,
|
||||||
|
),
|
||||||
|
enabled: Boolean(owner && repo && envName),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpsertEnvSecret(owner: string, repo: string, envName: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { name: string; value: string }) =>
|
||||||
|
api.post<SecretListItem>(
|
||||||
|
`/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets`,
|
||||||
|
secretSchema,
|
||||||
|
body,
|
||||||
|
),
|
||||||
|
onSuccess: () =>
|
||||||
|
qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteEnvSecret(owner: string, repo: string, envName: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (name: string) =>
|
||||||
|
api.delete<void>(
|
||||||
|
`/api/v1/repos/${owner}/${repo}/environments/${envName}/secrets/${encodeURIComponent(name)}`,
|
||||||
|
z.unknown() as z.ZodType<void>,
|
||||||
|
),
|
||||||
|
onSuccess: () =>
|
||||||
|
qc.invalidateQueries({ queryKey: ['repos', owner, repo, 'environments', envName, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Workspace secrets ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useWorkspaceSecrets(handle: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['workspaces', handle, 'secrets'],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<SecretListItem[]>(`/api/v1/workspaces/${handle}/secrets`, secretsSchema),
|
||||||
|
enabled: Boolean(handle),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpsertWorkspaceSecret(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { name: string; value: string }) =>
|
||||||
|
api.post<SecretListItem>(`/api/v1/workspaces/${handle}/secrets`, secretSchema, body),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteWorkspaceSecret(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (name: string) =>
|
||||||
|
api.delete<void>(
|
||||||
|
`/api/v1/workspaces/${handle}/secrets/${encodeURIComponent(name)}`,
|
||||||
|
z.unknown() as z.ZodType<void>,
|
||||||
|
),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'secrets'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { z } from 'zod'
|
||||||
|
import { api } from '../client'
|
||||||
|
import type { WorkspaceWithMeta, WorkspaceMember } from '../../types/api'
|
||||||
|
|
||||||
|
// ── Schemas ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const wsSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
handle: z.string(),
|
||||||
|
displayName: z.string(),
|
||||||
|
description: z.string(),
|
||||||
|
avatarUrl: z.string(),
|
||||||
|
createdBy: z.number(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
memberCount: z.number(),
|
||||||
|
repoCount: z.number(),
|
||||||
|
myRole: z.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const memberSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
workspaceId: z.number(),
|
||||||
|
userId: z.number(),
|
||||||
|
username: z.string(),
|
||||||
|
role: z.enum(['owner', 'admin', 'member']),
|
||||||
|
addedAt: z.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// WorkspaceRepo — raw repo as returned by the workspace list endpoint
|
||||||
|
export interface WorkspaceRepo {
|
||||||
|
id: number
|
||||||
|
ownerId: number
|
||||||
|
workspaceId?: number | null
|
||||||
|
ownerName: string
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
isPrivate: boolean
|
||||||
|
defaultBranch: string
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const repoSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
ownerId: z.number(),
|
||||||
|
workspaceId: z.number().nullable().optional(),
|
||||||
|
ownerName: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
description: z.string(),
|
||||||
|
isPrivate: z.boolean(),
|
||||||
|
defaultBranch: z.string(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useWorkspaces() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['workspaces'],
|
||||||
|
queryFn: () => api.get<WorkspaceWithMeta[]>('/api/v1/workspaces', z.array(wsSchema)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWorkspace(handle: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['workspaces', handle],
|
||||||
|
queryFn: () => api.get<WorkspaceWithMeta>(`/api/v1/workspaces/${handle}`, wsSchema),
|
||||||
|
enabled: Boolean(handle),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWorkspaceMembers(handle: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['workspaces', handle, 'members'],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<WorkspaceMember[]>(`/api/v1/workspaces/${handle}/members`, z.array(memberSchema)),
|
||||||
|
enabled: Boolean(handle),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useWorkspaceRepos(handle: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['workspaces', handle, 'repos'],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<WorkspaceRepo[]>(`/api/v1/workspaces/${handle}/repos`, z.array(repoSchema)),
|
||||||
|
enabled: Boolean(handle),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mutations ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function useCreateWorkspace() {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { handle: string; displayName?: string; description?: string }) =>
|
||||||
|
api.post<WorkspaceWithMeta>('/api/v1/workspaces', wsSchema, body),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateWorkspace(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { displayName?: string; description?: string }) =>
|
||||||
|
api.patch<WorkspaceWithMeta>(`/api/v1/workspaces/${handle}`, wsSchema, body),
|
||||||
|
onSuccess: () => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['workspaces'] })
|
||||||
|
qc.invalidateQueries({ queryKey: ['workspaces', handle] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteWorkspace(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
api.delete<void>(`/api/v1/workspaces/${handle}`, z.unknown() as z.ZodType<void>),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAddWorkspaceMember(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (body: { username: string; role: string }) =>
|
||||||
|
api.post<WorkspaceMember>(`/api/v1/workspaces/${handle}/members`, memberSchema, body),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateWorkspaceMember(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ username, role }: { username: string; role: string }) =>
|
||||||
|
api.patch<WorkspaceMember>(
|
||||||
|
`/api/v1/workspaces/${handle}/members/${username}`,
|
||||||
|
memberSchema,
|
||||||
|
{ role },
|
||||||
|
),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRemoveWorkspaceMember(handle: string) {
|
||||||
|
const qc = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (username: string) =>
|
||||||
|
api.delete<void>(
|
||||||
|
`/api/v1/workspaces/${handle}/members/${username}`,
|
||||||
|
z.unknown() as z.ZodType<void>,
|
||||||
|
),
|
||||||
|
onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { useAuth } from '../../contexts/AuthContext'
|
|||||||
import { useRecentRepos } from '../../hooks/useRecentRepos'
|
import { useRecentRepos } from '../../hooks/useRecentRepos'
|
||||||
import { useStarredRepos } from '../../hooks/useStarredRepos'
|
import { useStarredRepos } from '../../hooks/useStarredRepos'
|
||||||
import { useRepos } from '../../api/queries/repos'
|
import { useRepos } from '../../api/queries/repos'
|
||||||
|
import { useWorkspaces } from '../../api/queries/workspaces'
|
||||||
import { RepoAvatar } from '../../ui/RepoAvatar'
|
import { RepoAvatar } from '../../ui/RepoAvatar'
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
@@ -16,6 +17,7 @@ export function Sidebar({ className }: SidebarProps) {
|
|||||||
const { repos: recentRepos, remove } = useRecentRepos()
|
const { repos: recentRepos, remove } = useRecentRepos()
|
||||||
const { toggle, isStarred } = useStarredRepos()
|
const { toggle, isStarred } = useStarredRepos()
|
||||||
const { data: apiRepos } = useRepos()
|
const { data: apiRepos } = useRepos()
|
||||||
|
const { data: workspaces } = useWorkspaces()
|
||||||
const [openRecent, setOpenRecent] = useState(true)
|
const [openRecent, setOpenRecent] = useState(true)
|
||||||
|
|
||||||
// Drop localStorage entries for repos that no longer exist in the API.
|
// Drop localStorage entries for repos that no longer exist in the API.
|
||||||
@@ -53,6 +55,25 @@ export function Sidebar({ className }: SidebarProps) {
|
|||||||
<SidebarItem to="/repos" icon={<RepoIcon />} label="Repositories" />
|
<SidebarItem to="/repos" icon={<RepoIcon />} label="Repositories" />
|
||||||
<SidebarItem to="/explore" icon={<ExploreIcon />} label="Explore" />
|
<SidebarItem to="/explore" icon={<ExploreIcon />} label="Explore" />
|
||||||
<SidebarItem to="/starred" icon={<StarIcon />} label="Starred" />
|
<SidebarItem to="/starred" icon={<StarIcon />} label="Starred" />
|
||||||
|
<SidebarItem to="/workspaces" icon={<WorkspaceIcon />} label="Workspaces" />
|
||||||
|
{/* Workspace quick-links */}
|
||||||
|
{workspaces && workspaces.length > 0 && workspaces.map(ws => (
|
||||||
|
<NavLink
|
||||||
|
key={ws.id}
|
||||||
|
to={`/workspaces/${ws.handle}`}
|
||||||
|
className={({ isActive }) => cn(
|
||||||
|
'flex items-center gap-2.5 px-3 py-1.5 mx-1 rounded text-xs transition-colors min-h-[32px]',
|
||||||
|
isActive
|
||||||
|
? 'bg-[var(--c-surface)]/12 text-white font-medium'
|
||||||
|
: 'text-white/55 hover:bg-white/8 hover:text-white',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="w-4 h-4 rounded bg-[var(--c-brand)]/70 flex items-center justify-center text-white text-[9px] font-bold shrink-0">
|
||||||
|
{(ws.displayName || ws.handle)[0].toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<span className="truncate">{ws.displayName || ws.handle}</span>
|
||||||
|
</NavLink>
|
||||||
|
))}
|
||||||
|
|
||||||
{/* ── Recent repos ───────────────────────────────────────────── */}
|
{/* ── Recent repos ───────────────────────────────────────────── */}
|
||||||
{recentRepos.length > 0 && (
|
{recentRepos.length > 0 && (
|
||||||
@@ -164,6 +185,7 @@ function RepoSubNav({ owner, repo }: { owner: string; repo: string }) {
|
|||||||
{ label: 'Pipelines', to: `${base}/pipelines`, icon: <PipelineIcon /> },
|
{ label: 'Pipelines', to: `${base}/pipelines`, icon: <PipelineIcon /> },
|
||||||
{ label: 'Environments', to: `${base}/environments`, icon: <EnvIcon /> },
|
{ label: 'Environments', to: `${base}/environments`, icon: <EnvIcon /> },
|
||||||
{ label: 'Timeline', to: `${base}/timeline`, icon: <TimelineIcon /> },
|
{ label: 'Timeline', to: `${base}/timeline`, icon: <TimelineIcon /> },
|
||||||
|
{ label: 'Secrets', to: `${base}/secrets`, icon: <SecretsIcon /> },
|
||||||
{ label: 'Settings', to: `${base}/settings`, icon: <SettingsSmIcon /> },
|
{ label: 'Settings', to: `${base}/settings`, icon: <SettingsSmIcon /> },
|
||||||
]
|
]
|
||||||
return (
|
return (
|
||||||
@@ -207,4 +229,6 @@ const IssueIcon = () => <I d={['M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.94
|
|||||||
const PipelineIcon = () => <I d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" />
|
const PipelineIcon = () => <I d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" />
|
||||||
const EnvIcon = () => <I d="M5.25 14.25h13.5m-13.5 0a3 3 0 0 1-3-3m3 3a3 3 0 1 0 6 0m-6 0H3m16.5 0a3 3 0 0 0-3-3m3 3a3 3 0 1 1-6 0m6 0h1.5m-7.5 0h-3" />
|
const EnvIcon = () => <I d="M5.25 14.25h13.5m-13.5 0a3 3 0 0 1-3-3m3 3a3 3 0 1 0 6 0m-6 0H3m16.5 0a3 3 0 0 0-3-3m3 3a3 3 0 1 1-6 0m6 0h1.5m-7.5 0h-3" />
|
||||||
const TimelineIcon = () => <I d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
|
const TimelineIcon = () => <I d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
|
||||||
|
const SecretsIcon = () => <I d="M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.169.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 0 1 21.75 8.25Z" />
|
||||||
|
const WorkspaceIcon = () => <I d="M18 18.72a9.094 9.094 0 0 0 3.741-.479 3 3 0 0 0-4.682-2.72m.94 3.198.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0 1 12 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 0 1 6 18.719m12 0a5.971 5.971 0 0 0-.941-3.197m0 0A5.995 5.995 0 0 0 12 12.75a5.995 5.995 0 0 0-5.058 2.772m0 0a3 3 0 0 0-4.681 2.72 8.986 8.986 0 0 0 3.74.477m.94-3.197a5.971 5.971 0 0 0-.94 3.197M15 6.75a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm6 3a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Zm-13.5 0a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z" />
|
||||||
const SettingsSmIcon = () => <I d={['M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z', 'M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z']} />
|
const SettingsSmIcon = () => <I d={['M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z', 'M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z']} />
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Link, useNavigate } from 'react-router-dom'
|
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
import { useCreateRepo } from '../api/queries/repos'
|
import { useCreateRepo } from '../api/queries/repos'
|
||||||
|
import { useWorkspaces } from '../api/queries/workspaces'
|
||||||
|
|
||||||
export default function CreateRepoPage() {
|
export default function CreateRepoPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const [searchParams] = useSearchParams()
|
||||||
const createRepo = useCreateRepo()
|
const createRepo = useCreateRepo()
|
||||||
|
const { data: workspaces } = useWorkspaces()
|
||||||
|
|
||||||
const [name, setName] = useState('')
|
const [name, setName] = useState('')
|
||||||
|
const [workspace, setWorkspace] = useState(searchParams.get('workspace') ?? '')
|
||||||
const [isPrivate, setIsPrivate] = useState(true)
|
const [isPrivate, setIsPrivate] = useState(true)
|
||||||
const [initReadme, setInitReadme] = useState<'none' | 'blank' | 'tutorial'>('none')
|
const [initReadme, setInitReadme] = useState<'none' | 'blank' | 'tutorial'>('none')
|
||||||
const [defaultBranch, setDefaultBranch] = useState('')
|
const [defaultBranch, setDefaultBranch] = useState('')
|
||||||
@@ -24,6 +28,7 @@ export default function CreateRepoPage() {
|
|||||||
defaultBranch: defaultBranch.trim() || 'main',
|
defaultBranch: defaultBranch.trim() || 'main',
|
||||||
initReadme,
|
initReadme,
|
||||||
initGitignore,
|
initGitignore,
|
||||||
|
workspace: workspace || undefined,
|
||||||
})
|
})
|
||||||
navigate(`/repos/${repo.ownerName}/${repo.name}`)
|
navigate(`/repos/${repo.ownerName}/${repo.name}`)
|
||||||
}
|
}
|
||||||
@@ -41,6 +46,24 @@ export default function CreateRepoPage() {
|
|||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-5">
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
|
|
||||||
|
{/* Owner */}
|
||||||
|
{workspaces && workspaces.length > 0 && (
|
||||||
|
<Field label="Owner">
|
||||||
|
<select
|
||||||
|
value={workspace}
|
||||||
|
onChange={e => setWorkspace(e.target.value)}
|
||||||
|
className="w-full border border-[var(--c-border)] rounded px-3 py-2 text-sm focus:outline-none focus:border-[var(--c-brand-focus)] bg-[var(--c-surface)]"
|
||||||
|
>
|
||||||
|
<option value="">My account (personal)</option>
|
||||||
|
{workspaces.filter(ws => ws.myRole === 'owner' || ws.myRole === 'admin').map(ws => (
|
||||||
|
<option key={ws.id} value={ws.handle}>
|
||||||
|
{ws.displayName || ws.handle} (workspace)
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Repository name */}
|
{/* Repository name */}
|
||||||
<Field label="Repository name" required>
|
<Field label="Repository name" required>
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useParams } from 'react-router-dom'
|
||||||
|
import {
|
||||||
|
useRepoSecrets, useUpsertRepoSecret, useDeleteRepoSecret,
|
||||||
|
} from '../api/queries/secrets'
|
||||||
|
import { useEnvironments } from '../api/queries/environments'
|
||||||
|
import {
|
||||||
|
useEnvSecrets, useUpsertEnvSecret, useDeleteEnvSecret,
|
||||||
|
} from '../api/queries/secrets'
|
||||||
|
import { Skeleton } from '../ui/Skeleton'
|
||||||
|
import type { SecretListItem } from '../types/api'
|
||||||
|
|
||||||
|
// ── Shared secret table ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function SecretTable({
|
||||||
|
secrets,
|
||||||
|
onDelete,
|
||||||
|
isLoading,
|
||||||
|
}: {
|
||||||
|
secrets: SecretListItem[] | undefined
|
||||||
|
onDelete: (name: string) => void
|
||||||
|
isLoading: boolean
|
||||||
|
}) {
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[1, 2].map(i => <Skeleton key={i} className="h-10 rounded" />)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (!secrets?.length) {
|
||||||
|
return <p className="text-xs text-[var(--c-muted)] py-2">No secrets defined.</p>
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
|
||||||
|
{secrets.map(s => (
|
||||||
|
<div key={s.id} className="flex items-center gap-3 px-4 py-2.5">
|
||||||
|
<code className="flex-1 text-xs font-mono text-[var(--c-text)]">{s.name}</code>
|
||||||
|
<span className="text-[10px] text-[var(--c-muted)] font-mono">••••••••</span>
|
||||||
|
<button
|
||||||
|
onClick={() => onDelete(s.name)}
|
||||||
|
className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
|
||||||
|
title="Delete secret"
|
||||||
|
>
|
||||||
|
<svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AddSecretForm({
|
||||||
|
onSubmit,
|
||||||
|
isPending,
|
||||||
|
error,
|
||||||
|
}: {
|
||||||
|
onSubmit: (name: string, value: string) => void
|
||||||
|
isPending: boolean
|
||||||
|
error?: string
|
||||||
|
}) {
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [value, setValue] = useState('')
|
||||||
|
|
||||||
|
function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!name.trim() || !value.trim()) return
|
||||||
|
onSubmit(name.trim(), value.trim())
|
||||||
|
setName('')
|
||||||
|
setValue('')
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit} className="flex items-center gap-2 mt-3">
|
||||||
|
<input
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_'))}
|
||||||
|
placeholder="SECRET_NAME"
|
||||||
|
className="w-44 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)] font-mono"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={value}
|
||||||
|
onChange={e => setValue(e.target.value)}
|
||||||
|
placeholder="Secret value"
|
||||||
|
className="flex-1 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!name.trim() || !value.trim() || isPending}
|
||||||
|
className="px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isPending ? 'Saving…' : 'Save'}
|
||||||
|
</button>
|
||||||
|
{error && <p className="text-xs text-[var(--c-danger)]">{error}</p>}
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Env secrets sub-section ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function EnvSecretsSection({ owner, repo, envName }: { owner: string; repo: string; envName: string }) {
|
||||||
|
const { data: secrets, isLoading } = useEnvSecrets(owner, repo, envName)
|
||||||
|
const upsert = useUpsertEnvSecret(owner, repo, envName)
|
||||||
|
const del = useDeleteEnvSecret(owner, repo, envName)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden">
|
||||||
|
<div className="px-4 py-3 border-b border-[var(--c-border)] bg-[var(--c-surface-raised)] flex items-center gap-2">
|
||||||
|
<svg width="13" height="13" fill="none" stroke="var(--c-muted)" strokeWidth="1.5" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M5.25 14.25h13.5m-13.5 0a3 3 0 0 1-3-3m3 3a3 3 0 1 0 6 0m-6 0H3m16.5 0a3 3 0 0 0-3-3m3 3a3 3 0 1 1-6 0m6 0h1.5m-7.5 0h-3" />
|
||||||
|
</svg>
|
||||||
|
<span className="text-sm font-medium text-[var(--c-text)]">{envName}</span>
|
||||||
|
<span className="text-[10px] text-[var(--c-muted)] ml-auto">env-level override</span>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<SecretTable secrets={secrets} onDelete={name => del.mutate(name)} isLoading={isLoading} />
|
||||||
|
<AddSecretForm
|
||||||
|
onSubmit={(name, value) => upsert.mutate({ name, value })}
|
||||||
|
isPending={upsert.isPending}
|
||||||
|
error={(upsert.error as Error)?.message}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Page ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export default function RepoSecretsPage() {
|
||||||
|
const { owner = '', repo = '' } = useParams()
|
||||||
|
const { data: repoSecrets, isLoading: loadingRepo } = useRepoSecrets(owner, repo)
|
||||||
|
const upsertRepo = useUpsertRepoSecret(owner, repo)
|
||||||
|
const deleteRepo = useDeleteRepoSecret(owner, repo)
|
||||||
|
const { data: environments } = useEnvironments(owner, repo)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-6">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-[var(--c-text)]">Secrets</h1>
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5">
|
||||||
|
Secrets are injected as environment variables into CI pipeline jobs. Values are write-only.
|
||||||
|
</p>
|
||||||
|
<div className="mt-2 p-3 border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[10px] text-[var(--c-muted)]">
|
||||||
|
<strong className="text-[var(--c-text)]">Priority order:</strong>{' '}
|
||||||
|
Environment secrets → Repository secrets → Workspace secrets → Global secrets.
|
||||||
|
Higher-priority secrets with the same name override lower ones.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Repository-level secrets */}
|
||||||
|
<section>
|
||||||
|
<h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)] mb-3">
|
||||||
|
Repository secrets
|
||||||
|
</h2>
|
||||||
|
<div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden">
|
||||||
|
<div className="p-4">
|
||||||
|
<SecretTable
|
||||||
|
secrets={repoSecrets}
|
||||||
|
onDelete={name => deleteRepo.mutate(name)}
|
||||||
|
isLoading={loadingRepo}
|
||||||
|
/>
|
||||||
|
<AddSecretForm
|
||||||
|
onSubmit={(name, value) => upsertRepo.mutate({ name, value })}
|
||||||
|
isPending={upsertRepo.isPending}
|
||||||
|
error={(upsertRepo.error as Error)?.message}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Environment-level secrets */}
|
||||||
|
{environments && environments.length > 0 && (
|
||||||
|
<section>
|
||||||
|
<h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)] mb-3">
|
||||||
|
Environment secrets
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{environments.map(env => (
|
||||||
|
<EnvSecretsSection
|
||||||
|
key={env.id}
|
||||||
|
owner={owner}
|
||||||
|
repo={repo}
|
||||||
|
envName={env.name}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { useParams, Link } from 'react-router-dom'
|
||||||
|
import { useWorkspace, useWorkspaceRepos, type WorkspaceRepo } from '../api/queries/workspaces'
|
||||||
|
import { Skeleton } from '../ui/Skeleton'
|
||||||
|
|
||||||
|
function timeAgo(iso: string): string {
|
||||||
|
const diff = Date.now() - new Date(iso).getTime()
|
||||||
|
const min = Math.floor(diff / 60_000)
|
||||||
|
if (min < 60) return `${Math.max(1, min)}m ago`
|
||||||
|
const hr = Math.floor(min / 60)
|
||||||
|
if (hr < 24) return `${hr}h ago`
|
||||||
|
return `${Math.floor(hr / 24)}d ago`
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WorkspacePage() {
|
||||||
|
const { handle = '' } = useParams()
|
||||||
|
const { data: ws, isLoading } = useWorkspace(handle)
|
||||||
|
const { data: repos } = useWorkspaceRepos(handle)
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="max-w-4xl mx-auto px-4 md:px-6 py-5 space-y-4">
|
||||||
|
<Skeleton className="h-6 w-48 rounded" />
|
||||||
|
<Skeleton className="h-4 w-72 rounded" />
|
||||||
|
<div className="space-y-3 mt-6">
|
||||||
|
{[1, 2, 3].map(i => <Skeleton key={i} className="h-16 rounded-lg" />)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ws) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center py-24 gap-2">
|
||||||
|
<p className="text-sm text-[var(--c-muted)]">Workspace not found.</p>
|
||||||
|
<Link to="/workspaces" className="text-xs text-[var(--c-brand)] hover:underline">← All workspaces</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const canAdmin = ws.myRole === 'owner' || ws.myRole === 'admin'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-4xl mx-auto px-4 md:px-6 py-5 space-y-5">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-12 h-12 rounded-xl bg-[var(--c-brand)] flex items-center justify-center text-white text-lg font-bold shrink-0">
|
||||||
|
{ws.displayName?.[0]?.toUpperCase() || ws.handle[0].toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-[var(--c-text)]">{ws.displayName || ws.handle}</h1>
|
||||||
|
<div className="flex items-center gap-2 text-xs text-[var(--c-muted)]">
|
||||||
|
<span className="font-mono">@{ws.handle}</span>
|
||||||
|
<span>·</span>
|
||||||
|
<span>{ws.memberCount} member{ws.memberCount !== 1 ? 's' : ''}</span>
|
||||||
|
<span>·</span>
|
||||||
|
<span>{ws.repoCount} repo{ws.repoCount !== 1 ? 's' : ''}</span>
|
||||||
|
</div>
|
||||||
|
{ws.description && <p className="text-xs text-[var(--c-muted)] mt-0.5">{ws.description}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{canAdmin && (
|
||||||
|
<Link
|
||||||
|
to={`/workspaces/${handle}/settings`}
|
||||||
|
className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium border border-[var(--c-border)] rounded-lg text-[var(--c-text)] hover:border-[var(--c-brand-focus)] hover:text-[var(--c-brand)] transition-colors"
|
||||||
|
>
|
||||||
|
<svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z" /><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
|
||||||
|
</svg>
|
||||||
|
Settings
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Repositories */}
|
||||||
|
<section>
|
||||||
|
<div className="flex items-center justify-between mb-2.5">
|
||||||
|
<h2 className="text-xs font-semibold uppercase tracking-wider text-[var(--c-muted)]">Repositories</h2>
|
||||||
|
{canAdmin && (
|
||||||
|
<Link
|
||||||
|
to={`/repos/new?workspace=${handle}`}
|
||||||
|
className="text-[10px] text-[var(--c-brand)] hover:underline"
|
||||||
|
>
|
||||||
|
+ New repo
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] divide-y divide-[var(--c-border)] overflow-hidden">
|
||||||
|
{!repos?.length ? (
|
||||||
|
<div className="px-4 py-8 text-center text-xs text-[var(--c-muted)]">
|
||||||
|
No repositories yet.{' '}
|
||||||
|
{canAdmin && (
|
||||||
|
<Link to={`/repos/new?workspace=${handle}`} className="text-[var(--c-brand)] hover:underline">
|
||||||
|
Create the first one
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
(repos as WorkspaceRepo[]).map(repo => (
|
||||||
|
<Link
|
||||||
|
key={repo.id}
|
||||||
|
to={`/repos/${handle}/${repo.name}`}
|
||||||
|
className="flex items-center gap-3 px-4 py-3 hover:bg-[var(--c-surface-muted)] transition-colors group"
|
||||||
|
>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium text-[var(--c-text)] group-hover:text-[var(--c-brand)] transition-colors">
|
||||||
|
{repo.name}
|
||||||
|
</span>
|
||||||
|
{repo.isPrivate && (
|
||||||
|
<span className="text-[9px] font-semibold uppercase tracking-wider border border-[var(--c-border)] text-[var(--c-muted)] px-1 py-px rounded">private</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{repo.description && (
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5 truncate">{repo.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] text-[var(--c-subtle)] shrink-0">{timeAgo(repo.updatedAt)}</span>
|
||||||
|
</Link>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useParams, useNavigate } from 'react-router-dom'
|
||||||
|
import {
|
||||||
|
useWorkspace, useWorkspaceMembers, useUpdateWorkspace,
|
||||||
|
useDeleteWorkspace, useAddWorkspaceMember, useUpdateWorkspaceMember,
|
||||||
|
useRemoveWorkspaceMember,
|
||||||
|
} from '../api/queries/workspaces'
|
||||||
|
import {
|
||||||
|
useWorkspaceSecrets, useUpsertWorkspaceSecret, useDeleteWorkspaceSecret,
|
||||||
|
} from '../api/queries/secrets'
|
||||||
|
import { Skeleton } from '../ui/Skeleton'
|
||||||
|
import type { WorkspaceMember } from '../types/api'
|
||||||
|
|
||||||
|
// ── Shared section wrapper ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<section className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden">
|
||||||
|
<div className="px-4 py-3 border-b border-[var(--c-border)] bg-[var(--c-surface-raised)]">
|
||||||
|
<h2 className="text-sm font-semibold text-[var(--c-text)]">{title}</h2>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">{children}</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── General settings ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function GeneralSection({ handle }: { handle: string }) {
|
||||||
|
const { data: ws } = useWorkspace(handle)
|
||||||
|
const update = useUpdateWorkspace(handle)
|
||||||
|
const [displayName, setDisplayName] = useState(ws?.displayName ?? '')
|
||||||
|
const [description, setDescription] = useState(ws?.description ?? '')
|
||||||
|
|
||||||
|
function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
update.mutate({ displayName, description })
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="General">
|
||||||
|
<form onSubmit={submit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Display name</label>
|
||||||
|
<input
|
||||||
|
value={displayName}
|
||||||
|
onChange={e => setDisplayName(e.target.value)}
|
||||||
|
placeholder={handle}
|
||||||
|
className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Description</label>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={e => setDescription(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)] resize-y"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={update.isPending}
|
||||||
|
className="px-4 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{update.isPending ? 'Saving…' : 'Save changes'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Members ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function MembersSection({ handle, myRole }: { handle: string; myRole: string }) {
|
||||||
|
const { data: members } = useWorkspaceMembers(handle)
|
||||||
|
const addMember = useAddWorkspaceMember(handle)
|
||||||
|
const updateMember = useUpdateWorkspaceMember(handle)
|
||||||
|
const removeMember = useRemoveWorkspaceMember(handle)
|
||||||
|
const [username, setUsername] = useState('')
|
||||||
|
const [role, setRole] = useState('member')
|
||||||
|
const canEdit = myRole === 'owner' || myRole === 'admin'
|
||||||
|
|
||||||
|
function add(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!username.trim()) return
|
||||||
|
addMember.mutate({ username: username.trim(), role }, { onSuccess: () => setUsername('') })
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROLES = ['owner', 'admin', 'member']
|
||||||
|
const roleBadge: Record<string, string> = {
|
||||||
|
owner: 'bg-[var(--c-brand-tint)] text-[var(--c-brand)] border-[var(--c-brand-focus)]',
|
||||||
|
admin: 'bg-[#FFFAE6] text-[#B45309] border-[#F59E0B]/40',
|
||||||
|
member: 'bg-[var(--c-surface-muted)] text-[var(--c-muted)] border-[var(--c-border)]',
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Members">
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* Member list */}
|
||||||
|
<div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
|
||||||
|
{!members?.length ? (
|
||||||
|
<p className="px-4 py-3 text-xs text-[var(--c-muted)]">No members.</p>
|
||||||
|
) : (
|
||||||
|
members.map((m: WorkspaceMember) => (
|
||||||
|
<div key={m.id} className="flex items-center gap-3 px-4 py-2.5">
|
||||||
|
<div className="w-7 h-7 rounded-full bg-[var(--c-brand)] flex items-center justify-center text-white text-[11px] font-bold shrink-0">
|
||||||
|
{m.username[0].toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<span className="flex-1 text-sm text-[var(--c-text)]">{m.username}</span>
|
||||||
|
{canEdit ? (
|
||||||
|
<select
|
||||||
|
value={m.role}
|
||||||
|
onChange={e => updateMember.mutate({ username: m.username, role: e.target.value })}
|
||||||
|
className="text-xs border border-[var(--c-border)] rounded px-2 py-1 bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
>
|
||||||
|
{ROLES.map(r => <option key={r} value={r}>{r}</option>)}
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className={`text-[10px] font-semibold px-2 py-0.5 rounded border capitalize ${roleBadge[m.role] || roleBadge.member}`}>
|
||||||
|
{m.role}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{canEdit && (
|
||||||
|
<button
|
||||||
|
onClick={() => removeMember.mutate(m.username)}
|
||||||
|
className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
|
||||||
|
title="Remove member"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add member form */}
|
||||||
|
{canEdit && (
|
||||||
|
<form onSubmit={add} className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
value={username}
|
||||||
|
onChange={e => setUsername(e.target.value)}
|
||||||
|
placeholder="Username to add"
|
||||||
|
className="flex-1 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={role}
|
||||||
|
onChange={e => setRole(e.target.value)}
|
||||||
|
className="px-2 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] text-[var(--c-text)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
>
|
||||||
|
<option value="member">Member</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!username.trim() || addMember.isPending}
|
||||||
|
className="px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Add
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
{addMember.isError && (
|
||||||
|
<p className="text-xs text-[var(--c-danger)]">{(addMember.error as Error)?.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Secrets ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function SecretsSection({ handle }: { handle: string }) {
|
||||||
|
const { data: secrets } = useWorkspaceSecrets(handle)
|
||||||
|
const upsert = useUpsertWorkspaceSecret(handle)
|
||||||
|
const del = useDeleteWorkspaceSecret(handle)
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [value, setValue] = useState('')
|
||||||
|
|
||||||
|
function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!name.trim() || !value.trim()) return
|
||||||
|
upsert.mutate({ name: name.trim(), value: value.trim() }, {
|
||||||
|
onSuccess: () => { setName(''); setValue('') },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Secrets">
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mb-3">
|
||||||
|
Secrets are available to all CI pipelines in this workspace's repositories. Values are write-only and never displayed after creation.
|
||||||
|
</p>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="divide-y divide-[var(--c-border)] border border-[var(--c-border)] rounded-lg overflow-hidden">
|
||||||
|
{!secrets?.length ? (
|
||||||
|
<p className="px-4 py-3 text-xs text-[var(--c-muted)]">No workspace secrets.</p>
|
||||||
|
) : (
|
||||||
|
secrets.map(s => (
|
||||||
|
<div key={s.id} className="flex items-center gap-3 px-4 py-2.5">
|
||||||
|
<code className="flex-1 text-xs font-mono text-[var(--c-text)]">{s.name}</code>
|
||||||
|
<span className="text-[10px] text-[var(--c-muted)]">••••••••</span>
|
||||||
|
<button
|
||||||
|
onClick={() => del.mutate(s.name)}
|
||||||
|
className="text-[var(--c-muted)] hover:text-[var(--c-danger)] transition-colors p-1"
|
||||||
|
>
|
||||||
|
<svg width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<form onSubmit={submit} className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_'))}
|
||||||
|
placeholder="SECRET_NAME"
|
||||||
|
className="w-40 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)] font-mono"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={value}
|
||||||
|
onChange={e => setValue(e.target.value)}
|
||||||
|
placeholder="Secret value"
|
||||||
|
className="flex-1 px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!name.trim() || !value.trim() || upsert.isPending}
|
||||||
|
className="px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Danger zone ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function DangerSection({ handle, myRole }: { handle: string; myRole: string }) {
|
||||||
|
const del = useDeleteWorkspace(handle)
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
if (myRole !== 'owner') return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title="Danger zone">
|
||||||
|
<div className="flex items-center justify-between gap-4 p-3 border border-[var(--c-danger)]/30 rounded-lg bg-[var(--c-danger-tint)]">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-[var(--c-text)]">Delete workspace</p>
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5">
|
||||||
|
Permanently deletes the workspace and all membership. Repos must be deleted first.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (confirm(`Delete workspace "${handle}"? This cannot be undone.`)) {
|
||||||
|
del.mutate(undefined, { onSuccess: () => navigate('/workspaces') })
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={del.isPending}
|
||||||
|
className="px-3 py-2 text-sm font-medium border border-[var(--c-danger)] text-[var(--c-danger)] rounded-lg hover:bg-[var(--c-danger)] hover:text-white transition-colors disabled:opacity-50 shrink-0"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Page ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export default function WorkspaceSettingsPage() {
|
||||||
|
const { handle = '' } = useParams()
|
||||||
|
const { data: ws, isLoading } = useWorkspace(handle)
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-4">
|
||||||
|
{[1, 2, 3].map(i => <Skeleton key={i} className="h-40 rounded-lg" />)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ws) {
|
||||||
|
return <div className="p-6 text-sm text-[var(--c-muted)]">Workspace not found.</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
const canAdmin = ws.myRole === 'owner' || ws.myRole === 'admin'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-5">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-[var(--c-text)]">
|
||||||
|
{ws.displayName || ws.handle} — Settings
|
||||||
|
</h1>
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5 font-mono">@{ws.handle}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canAdmin && <GeneralSection handle={handle} />}
|
||||||
|
<MembersSection handle={handle} myRole={ws.myRole} />
|
||||||
|
{canAdmin && <SecretsSection handle={handle} />}
|
||||||
|
<DangerSection handle={handle} myRole={ws.myRole} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import { useWorkspaces, useCreateWorkspace } from '../api/queries/workspaces'
|
||||||
|
import { Skeleton } from '../ui/Skeleton'
|
||||||
|
import type { WorkspaceWithMeta } from '../types/api'
|
||||||
|
|
||||||
|
function WorkspaceCard({ ws }: { ws: WorkspaceWithMeta }) {
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
to={`/workspaces/${ws.handle}`}
|
||||||
|
className="flex items-center gap-4 p-4 border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] hover:border-[var(--c-brand-focus)] hover:bg-[var(--c-surface-muted)] transition-colors group"
|
||||||
|
>
|
||||||
|
<div className="w-10 h-10 rounded-lg bg-[var(--c-brand)] flex items-center justify-center text-white text-sm font-bold shrink-0">
|
||||||
|
{ws.displayName?.[0]?.toUpperCase() || ws.handle[0].toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-semibold text-[var(--c-text)] group-hover:text-[var(--c-brand)] transition-colors">
|
||||||
|
{ws.displayName || ws.handle}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs font-mono text-[var(--c-muted)]">@{ws.handle}</span>
|
||||||
|
{ws.myRole && (
|
||||||
|
<span className="text-[10px] font-semibold px-1.5 py-px rounded border border-[var(--c-border)] text-[var(--c-muted)] capitalize">
|
||||||
|
{ws.myRole}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{ws.description && (
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5 truncate">{ws.description}</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-3 mt-1 text-[10px] text-[var(--c-subtle)]">
|
||||||
|
<span>{ws.repoCount} repo{ws.repoCount !== 1 ? 's' : ''}</span>
|
||||||
|
<span>{ws.memberCount} member{ws.memberCount !== 1 ? 's' : ''}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<svg className="shrink-0 text-[var(--c-border)] group-hover:text-[var(--c-brand)] transition-colors" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
|
||||||
|
</svg>
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreateModal({ onClose }: { onClose: () => void }) {
|
||||||
|
const [handle, setHandle] = useState('')
|
||||||
|
const [displayName, setDisplayName] = useState('')
|
||||||
|
const [description, setDescription] = useState('')
|
||||||
|
const create = useCreateWorkspace()
|
||||||
|
|
||||||
|
function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!handle.trim()) return
|
||||||
|
create.mutate(
|
||||||
|
{ handle: handle.trim(), displayName: displayName.trim(), description: description.trim() },
|
||||||
|
{ onSuccess: onClose },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4" onClick={onClose}>
|
||||||
|
<div className="w-full max-w-md bg-[var(--c-surface)] border border-[var(--c-border)] rounded-xl shadow-2xl" onClick={e => e.stopPropagation()}>
|
||||||
|
<div className="flex items-center justify-between px-5 py-4 border-b border-[var(--c-border)]">
|
||||||
|
<h2 className="text-sm font-semibold text-[var(--c-text)]">Create a workspace</h2>
|
||||||
|
<button onClick={onClose} className="text-[var(--c-muted)] hover:text-[var(--c-text)] transition-colors">
|
||||||
|
<svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form onSubmit={submit} className="p-5 space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">
|
||||||
|
Handle <span className="text-[var(--c-danger)]">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
value={handle}
|
||||||
|
onChange={e => setHandle(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '-'))}
|
||||||
|
placeholder="acme-corp"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)] font-mono"
|
||||||
|
/>
|
||||||
|
<p className="text-[10px] text-[var(--c-muted)] mt-1">
|
||||||
|
Used in URLs. Letters, numbers, hyphens, underscores only.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Display name</label>
|
||||||
|
<input
|
||||||
|
value={displayName}
|
||||||
|
onChange={e => setDisplayName(e.target.value)}
|
||||||
|
placeholder="Acme Corp"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-[var(--c-text)] mb-1.5">Description</label>
|
||||||
|
<input
|
||||||
|
value={description}
|
||||||
|
onChange={e => setDescription(e.target.value)}
|
||||||
|
placeholder="Our engineering workspace"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-[var(--c-border)] rounded-lg bg-[var(--c-surface-muted)] text-[var(--c-text)] placeholder:text-[var(--c-muted)] focus:outline-none focus:border-[var(--c-brand-focus)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{create.isError && (
|
||||||
|
<p className="text-xs text-[var(--c-danger)]">
|
||||||
|
{(create.error as Error)?.message ?? 'Failed to create workspace'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-2 pt-1">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!handle.trim() || create.isPending}
|
||||||
|
className="flex-1 py-2 bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{create.isPending ? 'Creating…' : 'Create workspace'}
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={onClose} className="px-4 py-2 border border-[var(--c-border)] text-sm text-[var(--c-text)] rounded-lg hover:bg-[var(--c-surface-muted)] transition-colors">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WorkspacesPage() {
|
||||||
|
const { data: workspaces, isLoading } = useWorkspaces()
|
||||||
|
const [showCreate, setShowCreate] = useState(false)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-3xl mx-auto px-4 md:px-6 py-5 space-y-5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-[var(--c-text)]">Workspaces</h1>
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-0.5">Shared namespaces for team repositories</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
|
||||||
|
</svg>
|
||||||
|
New workspace
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{[1, 2, 3].map(i => <Skeleton key={i} className="h-20 rounded-lg" />)}
|
||||||
|
</div>
|
||||||
|
) : !workspaces?.length ? (
|
||||||
|
<div className="flex flex-col items-center justify-center py-20 border border-dashed border-[var(--c-border)] rounded-lg gap-3 text-center">
|
||||||
|
<div className="w-10 h-10 rounded-full bg-[var(--c-surface-muted)] flex items-center justify-center">
|
||||||
|
<svg width="20" height="20" fill="none" stroke="var(--c-muted)" strokeWidth="1.5" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 0 0 3.741-.479 3 3 0 0 0-4.682-2.72m.94 3.198.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0 1 12 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 0 1 6 18.719m12 0a5.971 5.971 0 0 0-.941-3.197m0 0A5.995 5.995 0 0 0 12 12.75a5.995 5.995 0 0 0-5.058 2.772m0 0a3 3 0 0 0-4.681 2.72 8.986 8.986 0 0 0 3.74.477m.94-3.197a5.971 5.971 0 0 0-.94 3.197M15 6.75a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm6 3a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Zm-13.5 0a2.25 2.25 0 1 1-4.5 0 2.25 2.25 0 0 1 4.5 0Z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-[var(--c-text)]">No workspaces yet</p>
|
||||||
|
<p className="text-xs text-[var(--c-muted)] mt-1 max-w-xs">
|
||||||
|
Create a workspace to share repositories with your team.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreate(true)}
|
||||||
|
className="px-4 py-2 text-sm font-medium bg-[var(--c-brand)] hover:bg-[var(--c-brand-hover)] text-white rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
Create your first workspace
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{workspaces.map(ws => <WorkspaceCard key={ws.id} ws={ws} />)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showCreate && <CreateModal onClose={() => setShowCreate(false)} />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -260,6 +260,43 @@ export interface EnvironmentWithLatest extends Environment {
|
|||||||
latestDeployment: Deployment | null
|
latestDeployment: Deployment | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Workspaces + Secrets (Phase 3C) ──────────────────────────────────────────
|
||||||
|
|
||||||
|
export type WorkspaceRole = 'owner' | 'admin' | 'member'
|
||||||
|
|
||||||
|
export interface Workspace {
|
||||||
|
id: number
|
||||||
|
handle: string
|
||||||
|
displayName: string
|
||||||
|
description: string
|
||||||
|
avatarUrl: string
|
||||||
|
createdBy: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WorkspaceWithMeta extends Workspace {
|
||||||
|
memberCount: number
|
||||||
|
repoCount: number
|
||||||
|
myRole: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WorkspaceMember {
|
||||||
|
id: number
|
||||||
|
workspaceId: number
|
||||||
|
userId: number
|
||||||
|
username: string
|
||||||
|
role: WorkspaceRole
|
||||||
|
addedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SecretListItem {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
// ── Unified Operational Timeline (Phase 3B) ──────────────────────────────────
|
// ── Unified Operational Timeline (Phase 3B) ──────────────────────────────────
|
||||||
|
|
||||||
export interface CommitEvent {
|
export interface CommitEvent {
|
||||||
|
|||||||
@@ -89,9 +89,21 @@ type dashboardResponse struct {
|
|||||||
func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
|
||||||
// 1. Repos owned by this user.
|
// 1. Repos owned by this user (user-level) + workspace repos where user is a member.
|
||||||
var repos []models.Repository
|
var repos []models.Repository
|
||||||
h.db.Where("owner_id = ?", userID).Desc("updated_at").Find(&repos)
|
h.db.Where("owner_id = ? AND workspace_id IS NULL", userID).Desc("updated_at").Find(&repos)
|
||||||
|
|
||||||
|
var memberships []models.WorkspaceMember
|
||||||
|
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||||
|
if len(memberships) > 0 {
|
||||||
|
wsIDs := make([]int64, len(memberships))
|
||||||
|
for i, m := range memberships {
|
||||||
|
wsIDs[i] = m.WorkspaceID
|
||||||
|
}
|
||||||
|
var wsRepos []models.Repository
|
||||||
|
h.db.In("workspace_id", wsIDs).Desc("updated_at").Find(&wsRepos)
|
||||||
|
repos = append(repos, wsRepos...)
|
||||||
|
}
|
||||||
|
|
||||||
repoIDs := make([]int64, len(repos))
|
repoIDs := make([]int64, len(repos))
|
||||||
repoByID := make(map[int64]models.Repository, len(repos))
|
repoByID := make(map[int64]models.Repository, len(repos))
|
||||||
@@ -184,8 +196,22 @@ func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|||||||
return dp
|
return dp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cache workspace handles to avoid N+1.
|
||||||
|
wsHandleByID := map[int64]string{}
|
||||||
|
|
||||||
dashRepos := make([]dashRepo, 0, len(repos))
|
dashRepos := make([]dashRepo, 0, len(repos))
|
||||||
for _, rp := range repos {
|
for _, rp := range repos {
|
||||||
|
ownerName := owner.Username
|
||||||
|
if rp.WorkspaceID != nil && *rp.WorkspaceID != 0 {
|
||||||
|
if wsHandle, ok := wsHandleByID[*rp.WorkspaceID]; ok {
|
||||||
|
ownerName = wsHandle
|
||||||
|
} else {
|
||||||
|
var ws models.Workspace
|
||||||
|
h.db.ID(*rp.WorkspaceID).Cols("handle").Get(&ws)
|
||||||
|
wsHandleByID[*rp.WorkspaceID] = ws.Handle
|
||||||
|
ownerName = ws.Handle
|
||||||
|
}
|
||||||
|
}
|
||||||
dashRepos = append(dashRepos, dashRepo{
|
dashRepos = append(dashRepos, dashRepo{
|
||||||
ID: rp.ID,
|
ID: rp.ID,
|
||||||
Name: rp.Name,
|
Name: rp.Name,
|
||||||
@@ -193,8 +219,8 @@ func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|||||||
IsPrivate: rp.IsPrivate,
|
IsPrivate: rp.IsPrivate,
|
||||||
DefaultBranch: rp.DefaultBranch,
|
DefaultBranch: rp.DefaultBranch,
|
||||||
UpdatedAt: rp.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
UpdatedAt: rp.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
||||||
OwnerName: owner.Username,
|
OwnerName: ownerName,
|
||||||
AvatarURL: "/api/v1/repos/" + owner.Username + "/" + rp.Name + "/avatar",
|
AvatarURL: "/api/v1/repos/" + ownerName + "/" + rp.Name + "/avatar",
|
||||||
OpenPRCount: prCountByRepo[rp.ID],
|
OpenPRCount: prCountByRepo[rp.ID],
|
||||||
OpenIssueCount: issueCountByRepo[rp.ID],
|
OpenIssueCount: issueCountByRepo[rp.ID],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -46,19 +46,28 @@ func isValidRepoName(name string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *RepoHandler) withOwnerName(repo *models.Repository) repoResponse {
|
func (h *RepoHandler) withOwnerName(repo *models.Repository) repoResponse {
|
||||||
var owner models.User
|
|
||||||
h.db.ID(repo.OwnerID).Get(&owner)
|
|
||||||
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
||||||
|
|
||||||
|
ownerName := ""
|
||||||
|
if repo.WorkspaceID != nil && *repo.WorkspaceID != 0 {
|
||||||
|
var ws models.Workspace
|
||||||
|
h.db.ID(*repo.WorkspaceID).Cols("handle").Get(&ws)
|
||||||
|
ownerName = ws.Handle
|
||||||
|
} else {
|
||||||
|
var owner models.User
|
||||||
|
h.db.ID(repo.OwnerID).Cols("username").Get(&owner)
|
||||||
|
ownerName = owner.Username
|
||||||
|
}
|
||||||
|
|
||||||
avURL := ""
|
avURL := ""
|
||||||
if _, err := os.Stat(avatarPath(h.cfg.RepoRoot, repo.ID)); err == nil {
|
if _, err := os.Stat(avatarPath(h.cfg.RepoRoot, repo.ID)); err == nil {
|
||||||
avURL = "/api/v1/repos/" + owner.Username + "/" + repo.Name + "/avatar"
|
avURL = "/api/v1/repos/" + ownerName + "/" + repo.Name + "/avatar"
|
||||||
}
|
}
|
||||||
|
|
||||||
return repoResponse{
|
return repoResponse{
|
||||||
Repository: *repo,
|
Repository: *repo,
|
||||||
AvatarURL: avURL,
|
AvatarURL: avURL,
|
||||||
OwnerName: owner.Username,
|
OwnerName: ownerName,
|
||||||
IsEmpty: gitdomain.IsEmpty(repo.DiskPath),
|
IsEmpty: gitdomain.IsEmpty(repo.DiskPath),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,10 +84,21 @@ func NewRepoHandler(db *xorm.Engine, cfg *config.Config) *RepoHandler {
|
|||||||
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
|
||||||
|
// User-owned repos.
|
||||||
var repos []models.Repository
|
var repos []models.Repository
|
||||||
if err := h.db.Where("owner_id = ?", userID).Find(&repos); err != nil {
|
h.db.Where("owner_id = ? AND workspace_id IS NULL", userID).Find(&repos)
|
||||||
jsonError(w, "could not list repositories", http.StatusInternalServerError)
|
|
||||||
return
|
// Workspace repos where user is a member.
|
||||||
|
var memberships []models.WorkspaceMember
|
||||||
|
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||||
|
if len(memberships) > 0 {
|
||||||
|
wsIDs := make([]int64, len(memberships))
|
||||||
|
for i, m := range memberships {
|
||||||
|
wsIDs[i] = m.WorkspaceID
|
||||||
|
}
|
||||||
|
var wsRepos []models.Repository
|
||||||
|
h.db.In("workspace_id", wsIDs).Find(&wsRepos)
|
||||||
|
repos = append(repos, wsRepos...)
|
||||||
}
|
}
|
||||||
|
|
||||||
result := make([]repoResponse, len(repos))
|
result := make([]repoResponse, len(repos))
|
||||||
@@ -98,6 +118,7 @@ func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|||||||
DefaultBranch string `json:"defaultBranch"`
|
DefaultBranch string `json:"defaultBranch"`
|
||||||
InitReadme string `json:"initReadme"` // "none" | "blank" | "tutorial"
|
InitReadme string `json:"initReadme"` // "none" | "blank" | "tutorial"
|
||||||
InitGitignore bool `json:"initGitignore"` // true → add .gitignore
|
InitGitignore bool `json:"initGitignore"` // true → add .gitignore
|
||||||
|
Workspace string `json:"workspace"` // optional workspace handle
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
@@ -112,10 +133,35 @@ func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
|||||||
branch = "main"
|
branch = "main"
|
||||||
}
|
}
|
||||||
|
|
||||||
diskPath := filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
// Determine owner: workspace or user.
|
||||||
|
var workspaceID *int64
|
||||||
|
var diskPath string
|
||||||
|
if body.Workspace != "" {
|
||||||
|
var ws models.Workspace
|
||||||
|
if found, _ := h.db.Where("handle = ?", body.Workspace).Get(&ws); !found {
|
||||||
|
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Caller must be a member with write access.
|
||||||
|
var member models.WorkspaceMember
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); !found {
|
||||||
|
jsonError(w, "not a member of this workspace", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if member.Role == models.WorkspaceRoleMember {
|
||||||
|
jsonError(w, "admin or owner required to create repos in a workspace", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wsID := ws.ID
|
||||||
|
workspaceID = &wsID
|
||||||
|
diskPath = diskPathForWorkspaceRepo(h.cfg.RepoRoot, ws.ID, body.Name)
|
||||||
|
} else {
|
||||||
|
diskPath = filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
||||||
|
}
|
||||||
|
|
||||||
repo := &models.Repository{
|
repo := &models.Repository{
|
||||||
OwnerID: userID,
|
OwnerID: userID,
|
||||||
|
WorkspaceID: workspaceID,
|
||||||
Name: body.Name,
|
Name: body.Name,
|
||||||
Description: body.Description,
|
Description: body.Description,
|
||||||
IsPrivate: body.IsPrivate,
|
IsPrivate: body.IsPrivate,
|
||||||
@@ -559,33 +605,48 @@ func (h *RepoHandler) Diff(w http.ResponseWriter, r *http.Request) {
|
|||||||
jsonOK(w, diffs)
|
jsonOK(w, diffs)
|
||||||
}
|
}
|
||||||
|
|
||||||
// lookupRepo resolves {owner}/{repo} URL params to a DB row, enforcing access.
|
// lookupRepo resolves {owner}/{repo} URL params to a DB row.
|
||||||
|
// The owner segment can be either a username (user-owned repo) or a
|
||||||
|
// workspace handle (workspace-owned repo).
|
||||||
func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) {
|
func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) {
|
||||||
ownerName := chi.URLParam(r, "owner")
|
ownerName := chi.URLParam(r, "owner")
|
||||||
repoName := chi.URLParam(r, "repo")
|
repoName := chi.URLParam(r, "repo")
|
||||||
|
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
|
||||||
var owner models.User
|
// 1. Try user namespace first.
|
||||||
found, err := h.db.Where("username = ?", ownerName).Get(&owner)
|
var user models.User
|
||||||
if err != nil || !found {
|
if found, _ := h.db.Where("username = ?", ownerName).Get(&user); found {
|
||||||
jsonError(w, "repository not found", http.StatusNotFound)
|
var repo models.Repository
|
||||||
return nil, false
|
if found2, _ := h.db.Where("owner_id = ? AND name = ? AND workspace_id IS NULL", user.ID, repoName).Get(&repo); found2 {
|
||||||
}
|
if repo.IsPrivate && callerID != repo.OwnerID {
|
||||||
|
// Check repo membership for private user repos.
|
||||||
var repo models.Repository
|
var m models.RepoMember
|
||||||
found, err = h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo)
|
if mfound, _ := h.db.Where("repo_id = ? AND user_id = ?", repo.ID, callerID).Get(&m); !mfound {
|
||||||
if err != nil || !found {
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
jsonError(w, "repository not found", http.StatusNotFound)
|
return nil, false
|
||||||
return nil, false
|
}
|
||||||
}
|
}
|
||||||
|
return &repo, true
|
||||||
// Private repo: only the owner may access (RBAC will be expanded in Phase 3)
|
|
||||||
if repo.IsPrivate {
|
|
||||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
|
||||||
if callerID != repo.OwnerID {
|
|
||||||
jsonError(w, "repository not found", http.StatusNotFound)
|
|
||||||
return nil, false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &repo, true
|
// 2. Try workspace namespace.
|
||||||
|
var ws models.Workspace
|
||||||
|
if found, _ := h.db.Where("handle = ?", ownerName).Get(&ws); found {
|
||||||
|
var repo models.Repository
|
||||||
|
if found2, _ := h.db.Where("workspace_id = ? AND name = ?", ws.ID, repoName).Get(&repo); found2 {
|
||||||
|
if repo.IsPrivate {
|
||||||
|
// Private workspace repo: caller must be a workspace member.
|
||||||
|
var m models.WorkspaceMember
|
||||||
|
if mfound, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, callerID).Get(&m); !mfound {
|
||||||
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &repo, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"xorm.io/xorm"
|
||||||
|
|
||||||
|
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||||
|
"github.com/forgeo/forgebucket/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SecretHandler struct {
|
||||||
|
db *xorm.Engine
|
||||||
|
sessionSecret string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSecretHandler(db *xorm.Engine, sessionSecret string) *SecretHandler {
|
||||||
|
return &SecretHandler{db: db, sessionSecret: sessionSecret}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Secret list response (names only — never values) ─────────────────────────
|
||||||
|
|
||||||
|
type secretListItem struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
CreatedAt string `json:"createdAt"`
|
||||||
|
UpdatedAt string `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func toListItem(s models.Secret) secretListItem {
|
||||||
|
return secretListItem{
|
||||||
|
ID: s.ID,
|
||||||
|
Name: s.Name,
|
||||||
|
CreatedAt: s.CreatedAt.Format("2006-01-02T15:04:05Z"),
|
||||||
|
UpdatedAt: s.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Repo secrets ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) ListRepoSecrets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
repoID, ok := h.resolveRepoID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.listSecrets(w, models.SecretScopeRepo, repoID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) UpsertRepoSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
repoID, ok := h.resolveRepoID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.upsertSecret(w, r, models.SecretScopeRepo, repoID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) DeleteRepoSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
repoID, ok := h.resolveRepoID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.deleteSecret(w, r, models.SecretScopeRepo, repoID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Env secrets ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) ListEnvSecrets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
envID, ok := h.resolveEnvID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.listSecrets(w, models.SecretScopeEnv, envID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) UpsertEnvSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
envID, ok := h.resolveEnvID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.upsertSecret(w, r, models.SecretScopeEnv, envID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) DeleteEnvSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
envID, ok := h.resolveEnvID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.deleteSecret(w, r, models.SecretScopeEnv, envID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Workspace secrets ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) ListWorkspaceSecrets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.listSecrets(w, models.SecretScopeWorkspace, wsID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) UpsertWorkspaceSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.upsertSecret(w, r, models.SecretScopeWorkspace, wsID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) DeleteWorkspaceSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.deleteSecret(w, r, models.SecretScopeWorkspace, wsID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Global secrets (admin only) ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) ListGlobalSecrets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !h.requireAdmin(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.listSecrets(w, models.SecretScopeGlobal, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) UpsertGlobalSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !h.requireAdmin(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.upsertSecret(w, r, models.SecretScopeGlobal, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) DeleteGlobalSecret(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !h.requireAdmin(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.deleteSecret(w, r, models.SecretScopeGlobal, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Shared CRUD primitives ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) listSecrets(w http.ResponseWriter, scope models.SecretScope, scopeID int64) {
|
||||||
|
var secrets []models.Secret
|
||||||
|
h.db.Where("scope = ? AND scope_id = ?", scope, scopeID).Asc("name").Find(&secrets)
|
||||||
|
items := make([]secretListItem, len(secrets))
|
||||||
|
for i, s := range secrets {
|
||||||
|
items[i] = toListItem(s)
|
||||||
|
}
|
||||||
|
jsonOK(w, items)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) upsertSecret(w http.ResponseWriter, r *http.Request, scope models.SecretScope, scopeID int64) {
|
||||||
|
var body struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.Name == "" || body.Value == "" {
|
||||||
|
jsonError(w, "name and value are required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
encrypted, err := models.EncryptSecret(body.Value, h.sessionSecret)
|
||||||
|
if err != nil {
|
||||||
|
jsonError(w, "encryption failed", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert: update if the name already exists for this scope.
|
||||||
|
var existing models.Secret
|
||||||
|
found, _ := h.db.Where("scope = ? AND scope_id = ? AND name = ?", scope, scopeID, body.Name).Get(&existing)
|
||||||
|
if found {
|
||||||
|
existing.EncryptedValue = encrypted
|
||||||
|
h.db.ID(existing.ID).Cols("encrypted_value", "updated_at").Update(&existing) //nolint:errcheck
|
||||||
|
jsonOK(w, toListItem(existing))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
secret := &models.Secret{
|
||||||
|
Scope: scope,
|
||||||
|
ScopeID: scopeID,
|
||||||
|
Name: body.Name,
|
||||||
|
EncryptedValue: encrypted,
|
||||||
|
}
|
||||||
|
if _, err := h.db.Insert(secret); err != nil {
|
||||||
|
jsonError(w, "could not save secret", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
json.NewEncoder(w).Encode(toListItem(*secret)) //nolint:errcheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) deleteSecret(w http.ResponseWriter, r *http.Request, scope models.SecretScope, scopeID int64) {
|
||||||
|
name := chi.URLParam(r, "name")
|
||||||
|
res, err := h.db.Where("scope = ? AND scope_id = ? AND name = ?", scope, scopeID, name).
|
||||||
|
Delete(&models.Secret{})
|
||||||
|
if err != nil || res == 0 {
|
||||||
|
jsonError(w, "secret not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── ResolveSecretsForRun ──────────────────────────────────────────────────────
|
||||||
|
// Used by the CI executor to build the env var map for a pipeline job.
|
||||||
|
// Priority order (highest wins): Env > Repo > Workspace > Global.
|
||||||
|
|
||||||
|
func ResolveSecretsForRun(db *xorm.Engine, repoID, workspaceID, envID int64, sessionSecret string) map[string]string {
|
||||||
|
out := map[string]string{}
|
||||||
|
|
||||||
|
loadScope := func(scope models.SecretScope, scopeID int64) {
|
||||||
|
var secrets []models.Secret
|
||||||
|
db.Where("scope = ? AND scope_id = ?", scope, scopeID).Find(&secrets)
|
||||||
|
for _, s := range secrets {
|
||||||
|
if _, already := out[s.Name]; !already {
|
||||||
|
pt, err := models.DecryptSecret(s.EncryptedValue, sessionSecret)
|
||||||
|
if err == nil {
|
||||||
|
out[s.Name] = pt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load in reverse priority so higher-priority scopes overwrite.
|
||||||
|
loadScope(models.SecretScopeGlobal, 0)
|
||||||
|
if workspaceID != 0 {
|
||||||
|
loadScope(models.SecretScopeWorkspace, workspaceID)
|
||||||
|
}
|
||||||
|
loadScope(models.SecretScopeRepo, repoID)
|
||||||
|
if envID != 0 {
|
||||||
|
loadScope(models.SecretScopeEnv, envID)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *SecretHandler) resolveRepoID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||||
|
owner := chi.URLParam(r, "owner")
|
||||||
|
repoName := chi.URLParam(r, "repo")
|
||||||
|
var u models.User
|
||||||
|
if found, _ := h.db.Where("username = ?", owner).Get(&u); !found {
|
||||||
|
// Try workspace
|
||||||
|
var ws models.Workspace
|
||||||
|
if found2, _ := h.db.Where("handle = ?", owner).Get(&ws); !found2 {
|
||||||
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
var repo models.Repository
|
||||||
|
if found3, _ := h.db.Where("workspace_id = ? AND name = ?", ws.ID, repoName).Get(&repo); !found3 {
|
||||||
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return repo.ID, true
|
||||||
|
}
|
||||||
|
var repo models.Repository
|
||||||
|
if found, _ := h.db.Where("owner_id = ? AND name = ?", u.ID, repoName).Get(&repo); !found {
|
||||||
|
jsonError(w, "repository not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return repo.ID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) resolveEnvID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||||
|
repoID, ok := h.resolveRepoID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
envName := chi.URLParam(r, "envName")
|
||||||
|
var env models.Environment
|
||||||
|
if found, _ := h.db.Where("repo_id = ? AND name = ?", repoID, envName).Get(&env); !found {
|
||||||
|
jsonError(w, "environment not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return env.ID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) resolveWorkspaceID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||||
|
handle := chi.URLParam(r, "handle")
|
||||||
|
var ws models.Workspace
|
||||||
|
if found, _ := h.db.Where("handle = ?", handle).Get(&ws); !found {
|
||||||
|
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
// Require membership.
|
||||||
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
var member models.WorkspaceMember
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); !found {
|
||||||
|
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return ws.ID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SecretHandler) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
|
||||||
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
var u models.User
|
||||||
|
if found, _ := h.db.ID(userID).Get(&u); !found || !u.IsAdmin {
|
||||||
|
jsonError(w, "admin required", http.StatusForbidden)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"xorm.io/xorm"
|
||||||
|
|
||||||
|
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||||
|
"github.com/forgeo/forgebucket/internal/config"
|
||||||
|
"github.com/forgeo/forgebucket/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WorkspaceHandler struct {
|
||||||
|
db *xorm.Engine
|
||||||
|
cfg *config.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWorkspaceHandler(db *xorm.Engine, cfg *config.Config) *WorkspaceHandler {
|
||||||
|
return &WorkspaceHandler{db: db, cfg: cfg}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Response shapes ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type workspaceResponse struct {
|
||||||
|
models.Workspace
|
||||||
|
MemberCount int `json:"memberCount"`
|
||||||
|
RepoCount int `json:"repoCount"`
|
||||||
|
MyRole string `json:"myRole"` // caller's role, empty if not a member
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── List ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// ListWorkspaces returns all workspaces the current user belongs to.
|
||||||
|
func (h *WorkspaceHandler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
|
||||||
|
var memberships []models.WorkspaceMember
|
||||||
|
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||||
|
|
||||||
|
if len(memberships) == 0 {
|
||||||
|
jsonOK(w, []workspaceResponse{})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
wsIDs := make([]int64, len(memberships))
|
||||||
|
roleByWS := map[int64]string{}
|
||||||
|
for i, m := range memberships {
|
||||||
|
wsIDs[i] = m.WorkspaceID
|
||||||
|
roleByWS[m.WorkspaceID] = string(m.Role)
|
||||||
|
}
|
||||||
|
|
||||||
|
var workspaces []models.Workspace
|
||||||
|
h.db.In("id", wsIDs).Find(&workspaces)
|
||||||
|
|
||||||
|
result := make([]workspaceResponse, len(workspaces))
|
||||||
|
for i, ws := range workspaces {
|
||||||
|
memberCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.WorkspaceMember{})
|
||||||
|
repoCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||||
|
result[i] = workspaceResponse{
|
||||||
|
Workspace: ws,
|
||||||
|
MemberCount: int(memberCount),
|
||||||
|
RepoCount: int(repoCount),
|
||||||
|
MyRole: roleByWS[ws.ID],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
jsonOK(w, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Create ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Handle string `json:"handle"`
|
||||||
|
DisplayName string `json:"displayName"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.Handle == "" {
|
||||||
|
jsonError(w, "handle is required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !isValidHandle(body.Handle) {
|
||||||
|
jsonError(w, "handle may only contain letters, numbers, hyphens, and underscores", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle must not collide with any username or existing workspace handle.
|
||||||
|
var existingUser models.User
|
||||||
|
if found, _ := h.db.Where("username = ?", body.Handle).Get(&existingUser); found {
|
||||||
|
jsonError(w, "handle is already taken by a user", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var existingWS models.Workspace
|
||||||
|
if found, _ := h.db.Where("handle = ?", body.Handle).Get(&existingWS); found {
|
||||||
|
jsonError(w, "handle is already taken by a workspace", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ws := &models.Workspace{
|
||||||
|
Handle: body.Handle,
|
||||||
|
DisplayName: body.DisplayName,
|
||||||
|
Description: body.Description,
|
||||||
|
CreatedBy: userID,
|
||||||
|
}
|
||||||
|
if _, err := h.db.Insert(ws); err != nil {
|
||||||
|
jsonError(w, "could not create workspace", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creator becomes owner automatically.
|
||||||
|
var creator models.User
|
||||||
|
h.db.ID(userID).Cols("username").Get(&creator)
|
||||||
|
member := &models.WorkspaceMember{
|
||||||
|
WorkspaceID: ws.ID,
|
||||||
|
UserID: userID,
|
||||||
|
Username: creator.Username,
|
||||||
|
Role: models.WorkspaceRoleOwner,
|
||||||
|
}
|
||||||
|
h.db.Insert(member) //nolint:errcheck
|
||||||
|
|
||||||
|
resp := workspaceResponse{Workspace: *ws, MemberCount: 1, MyRole: string(models.WorkspaceRoleOwner)}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
json.NewEncoder(w).Encode(resp) //nolint:errcheck
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Get ───────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) GetWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
memberCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.WorkspaceMember{})
|
||||||
|
repoCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||||
|
jsonOK(w, workspaceResponse{Workspace: *ws, MemberCount: int(memberCount), RepoCount: int(repoCount), MyRole: myRole})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Update ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||||
|
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
DisplayName *string `json:"displayName"`
|
||||||
|
Description *string `json:"description"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cols := []string{}
|
||||||
|
if body.DisplayName != nil {
|
||||||
|
ws.DisplayName = *body.DisplayName
|
||||||
|
cols = append(cols, "display_name")
|
||||||
|
}
|
||||||
|
if body.Description != nil {
|
||||||
|
ws.Description = *body.Description
|
||||||
|
cols = append(cols, "description")
|
||||||
|
}
|
||||||
|
if len(cols) > 0 {
|
||||||
|
h.db.ID(ws.ID).Cols(cols...).Update(ws) //nolint:errcheck
|
||||||
|
}
|
||||||
|
jsonOK(w, ws)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Delete ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if myRole != string(models.WorkspaceRoleOwner) {
|
||||||
|
jsonError(w, "only the workspace owner can delete it", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Refuse if the workspace still has repos.
|
||||||
|
count, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||||
|
if count > 0 {
|
||||||
|
jsonError(w, "delete or transfer all repositories before deleting the workspace", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.db.Where("workspace_id = ?", ws.ID).Delete(&models.WorkspaceMember{}) //nolint:errcheck
|
||||||
|
h.db.ID(ws.ID).Delete(&models.Workspace{}) //nolint:errcheck
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Repos in workspace ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) ListRepos(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, _, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var repos []models.Repository
|
||||||
|
h.db.Where("workspace_id = ?", ws.ID).Find(&repos)
|
||||||
|
if repos == nil {
|
||||||
|
repos = []models.Repository{}
|
||||||
|
}
|
||||||
|
// Return the same enriched shape that the repo list uses.
|
||||||
|
type wsRepoResponse struct {
|
||||||
|
models.Repository
|
||||||
|
OwnerName string `json:"ownerName"`
|
||||||
|
}
|
||||||
|
result := make([]wsRepoResponse, len(repos))
|
||||||
|
for i, r := range repos {
|
||||||
|
result[i] = wsRepoResponse{Repository: r, OwnerName: ws.Handle}
|
||||||
|
}
|
||||||
|
jsonOK(w, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Members ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) ListMembers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, _, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var members []models.WorkspaceMember
|
||||||
|
h.db.Where("workspace_id = ?", ws.ID).Find(&members)
|
||||||
|
if members == nil {
|
||||||
|
members = []models.WorkspaceMember{}
|
||||||
|
}
|
||||||
|
jsonOK(w, members)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) AddMember(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||||
|
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Role string `json:"role"` // "admin" | "member"
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
role := models.WorkspaceRole(body.Role)
|
||||||
|
if role != models.WorkspaceRoleAdmin && role != models.WorkspaceRoleMember {
|
||||||
|
role = models.WorkspaceRoleMember
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if found, _ := h.db.Where("username = ?", body.Username).Get(&user); !found {
|
||||||
|
jsonError(w, "user not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idempotent: update role if already a member.
|
||||||
|
var existing models.WorkspaceMember
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, user.ID).Get(&existing); found {
|
||||||
|
existing.Role = role
|
||||||
|
h.db.ID(existing.ID).Cols("role").Update(&existing) //nolint:errcheck
|
||||||
|
jsonOK(w, existing)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
member := &models.WorkspaceMember{
|
||||||
|
WorkspaceID: ws.ID,
|
||||||
|
UserID: user.ID,
|
||||||
|
Username: user.Username,
|
||||||
|
Role: role,
|
||||||
|
}
|
||||||
|
if _, err := h.db.Insert(member); err != nil {
|
||||||
|
jsonError(w, "could not add member", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
json.NewEncoder(w).Encode(member) //nolint:errcheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) UpdateMember(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||||
|
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
targetUsername := chi.URLParam(r, "username")
|
||||||
|
var body struct{ Role string `json:"role"` }
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var target models.User
|
||||||
|
if found, _ := h.db.Where("username = ?", targetUsername).Get(&target); !found {
|
||||||
|
jsonError(w, "user not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var member models.WorkspaceMember
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, target.ID).Get(&member); !found {
|
||||||
|
jsonError(w, "member not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Cannot demote the last owner.
|
||||||
|
if member.Role == models.WorkspaceRoleOwner && models.WorkspaceRole(body.Role) != models.WorkspaceRoleOwner {
|
||||||
|
count, _ := h.db.Where("workspace_id = ? AND role = 'owner'", ws.ID).Count(&models.WorkspaceMember{})
|
||||||
|
if count <= 1 {
|
||||||
|
jsonError(w, "workspace must have at least one owner", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
member.Role = models.WorkspaceRole(body.Role)
|
||||||
|
h.db.ID(member.ID).Cols("role").Update(&member) //nolint:errcheck
|
||||||
|
jsonOK(w, member)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) RemoveMember(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
targetUsername := chi.URLParam(r, "username")
|
||||||
|
|
||||||
|
var target models.User
|
||||||
|
if found, _ := h.db.Where("username = ?", targetUsername).Get(&target); !found {
|
||||||
|
jsonError(w, "user not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Members can remove themselves; admins/owners can remove others.
|
||||||
|
if target.ID != callerID {
|
||||||
|
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||||
|
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var member models.WorkspaceMember
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, target.ID).Get(&member); !found {
|
||||||
|
jsonError(w, "member not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if member.Role == models.WorkspaceRoleOwner {
|
||||||
|
count, _ := h.db.Where("workspace_id = ? AND role = 'owner'", ws.ID).Count(&models.WorkspaceMember{})
|
||||||
|
if count <= 1 {
|
||||||
|
jsonError(w, "cannot remove the last owner", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.db.ID(member.ID).Delete(&models.WorkspaceMember{}) //nolint:errcheck
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func (h *WorkspaceHandler) resolveWorkspace(w http.ResponseWriter, r *http.Request) (*models.Workspace, string, bool) {
|
||||||
|
handle := chi.URLParam(r, "handle")
|
||||||
|
var ws models.Workspace
|
||||||
|
if found, _ := h.db.Where("handle = ?", handle).Get(&ws); !found {
|
||||||
|
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||||
|
return nil, "", false
|
||||||
|
}
|
||||||
|
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||||
|
var member models.WorkspaceMember
|
||||||
|
myRole := ""
|
||||||
|
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); found {
|
||||||
|
myRole = string(member.Role)
|
||||||
|
}
|
||||||
|
return &ws, myRole, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// diskPathForWorkspaceRepo returns the on-disk bare repo path for workspace-owned repos.
|
||||||
|
func diskPathForWorkspaceRepo(repoRoot string, workspaceID int64, repoName string) string {
|
||||||
|
return filepath.Join(repoRoot, "ws_"+strconv.FormatInt(workspaceID, 10), repoName+".git")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidHandle(h string) bool {
|
||||||
|
if len(h) == 0 || len(h) > 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range h {
|
||||||
|
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||||
|
(c >= '0' && c <= '9') || c == '-' || c == '_') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -60,6 +60,8 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus even
|
|||||||
runnerH := handlers.NewRunnerHandler(engine)
|
runnerH := handlers.NewRunnerHandler(engine)
|
||||||
envH := handlers.NewEnvironmentHandler(engine, bus)
|
envH := handlers.NewEnvironmentHandler(engine, bus)
|
||||||
timelineH := handlers.NewTimelineHandler(engine, cfg.RepoRoot)
|
timelineH := handlers.NewTimelineHandler(engine, cfg.RepoRoot)
|
||||||
|
workspaceH := handlers.NewWorkspaceHandler(engine, cfg)
|
||||||
|
secretH := handlers.NewSecretHandler(engine, cfg.SessionSecret)
|
||||||
|
|
||||||
// ── Git smart-HTTP transport ───────────────────────────────────────────────
|
// ── Git smart-HTTP transport ───────────────────────────────────────────────
|
||||||
// Regex constraint ensures only *.git paths match, so asset/SPA URLs
|
// Regex constraint ensures only *.git paths match, so asset/SPA URLs
|
||||||
@@ -108,6 +110,30 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus even
|
|||||||
r.Get("/audit", auditH.List)
|
r.Get("/audit", auditH.List)
|
||||||
r.Get("/pipelines/runs", pipeH.ListRecentRuns)
|
r.Get("/pipelines/runs", pipeH.ListRecentRuns)
|
||||||
|
|
||||||
|
// Workspace routes
|
||||||
|
r.Get("/workspaces", workspaceH.ListWorkspaces)
|
||||||
|
r.With(csrf).Post("/workspaces", workspaceH.CreateWorkspace)
|
||||||
|
r.Route("/workspaces/{handle}", func(r chi.Router) {
|
||||||
|
r.Get("/", workspaceH.GetWorkspace)
|
||||||
|
r.With(csrf).Patch("/", workspaceH.UpdateWorkspace)
|
||||||
|
r.With(csrf).Delete("/", workspaceH.DeleteWorkspace)
|
||||||
|
r.Get("/repos", workspaceH.ListRepos)
|
||||||
|
r.Route("/members", func(r chi.Router) {
|
||||||
|
r.Get("/", workspaceH.ListMembers)
|
||||||
|
r.With(csrf).Post("/", workspaceH.AddMember)
|
||||||
|
r.With(csrf).Patch("/{username}", workspaceH.UpdateMember)
|
||||||
|
r.With(csrf).Delete("/{username}", workspaceH.RemoveMember)
|
||||||
|
})
|
||||||
|
r.Get("/secrets", secretH.ListWorkspaceSecrets)
|
||||||
|
r.With(csrf).Post("/secrets", secretH.UpsertWorkspaceSecret)
|
||||||
|
r.With(csrf).Delete("/secrets/{name}", secretH.DeleteWorkspaceSecret)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Global secrets (admin)
|
||||||
|
r.Get("/admin/secrets", secretH.ListGlobalSecrets)
|
||||||
|
r.With(csrf).Post("/admin/secrets", secretH.UpsertGlobalSecret)
|
||||||
|
r.With(csrf).Delete("/admin/secrets/{name}", secretH.DeleteGlobalSecret)
|
||||||
|
|
||||||
r.Route("/admin", func(r chi.Router) {
|
r.Route("/admin", func(r chi.Router) {
|
||||||
r.Get("/runners", runnerH.List)
|
r.Get("/runners", runnerH.List)
|
||||||
r.With(csrf).Post("/runners/register", runnerH.Register)
|
r.With(csrf).Post("/runners/register", runnerH.Register)
|
||||||
@@ -208,6 +234,9 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus even
|
|||||||
r.Get("/excluded-files", prSettingsH.GetExcludedFiles)
|
r.Get("/excluded-files", prSettingsH.GetExcludedFiles)
|
||||||
r.With(csrf).Put("/excluded-files", prSettingsH.UpdateExcludedFiles)
|
r.With(csrf).Put("/excluded-files", prSettingsH.UpdateExcludedFiles)
|
||||||
r.Get("/timeline", timelineH.GetTimeline)
|
r.Get("/timeline", timelineH.GetTimeline)
|
||||||
|
r.Get("/secrets", secretH.ListRepoSecrets)
|
||||||
|
r.With(csrf).Post("/secrets", secretH.UpsertRepoSecret)
|
||||||
|
r.With(csrf).Delete("/secrets/{name}", secretH.DeleteRepoSecret)
|
||||||
r.Get("/lfs-settings", lfsH.Get)
|
r.Get("/lfs-settings", lfsH.Get)
|
||||||
r.With(csrf).Put("/lfs-settings", lfsH.Update)
|
r.With(csrf).Put("/lfs-settings", lfsH.Update)
|
||||||
r.Route("/environments", func(r chi.Router) {
|
r.Route("/environments", func(r chi.Router) {
|
||||||
@@ -222,6 +251,9 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus even
|
|||||||
r.With(csrf).Post("/", envH.CreateDeployment)
|
r.With(csrf).Post("/", envH.CreateDeployment)
|
||||||
r.With(csrf).Patch("/{deployID}/status", envH.UpdateDeploymentStatus)
|
r.With(csrf).Patch("/{deployID}/status", envH.UpdateDeploymentStatus)
|
||||||
})
|
})
|
||||||
|
r.Get("/secrets", secretH.ListEnvSecrets)
|
||||||
|
r.With(csrf).Post("/secrets", secretH.UpsertEnvSecret)
|
||||||
|
r.With(csrf).Delete("/secrets/{name}", secretH.DeleteEnvSecret)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -18,10 +18,11 @@ import (
|
|||||||
|
|
||||||
// JobContext holds everything needed to execute a single pipeline job.
|
// JobContext holds everything needed to execute a single pipeline job.
|
||||||
type JobContext struct {
|
type JobContext struct {
|
||||||
Run models.PipelineRun
|
Run models.PipelineRun
|
||||||
Job models.PipelineJob
|
Job models.PipelineJob
|
||||||
Steps []models.PipelineStep
|
Steps []models.PipelineStep
|
||||||
Repo models.Repository
|
Repo models.Repository
|
||||||
|
Secrets map[string]string // resolved secret key→value map (Env > Repo > Workspace > Global)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExecuteJob runs all steps of a job inside isolated Docker containers,
|
// ExecuteJob runs all steps of a job inside isolated Docker containers,
|
||||||
@@ -60,7 +61,7 @@ func ExecuteJob(ctx context.Context, db *xorm.Engine, bus events.EventBus, jc Jo
|
|||||||
markStep(db, step, "skipped", 0)
|
markStep(db, step, "skipped", 0)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
exitCode, err := runStep(ctx, db, bus, jc.Run.ID, jc.Job.ID, step, image, workDir)
|
exitCode, err := runStep(ctx, db, bus, jc.Run.ID, jc.Job.ID, step, image, workDir, jc.Secrets)
|
||||||
if err != nil || exitCode != 0 {
|
if err != nil || exitCode != 0 {
|
||||||
if exitCode == 0 {
|
if exitCode == 0 {
|
||||||
exitCode = 1
|
exitCode = 1
|
||||||
@@ -83,20 +84,26 @@ func ExecuteJob(ctx context.Context, db *xorm.Engine, bus events.EventBus, jc Jo
|
|||||||
|
|
||||||
// runStep runs a single shell-command step inside a Docker container.
|
// runStep runs a single shell-command step inside a Docker container.
|
||||||
func runStep(ctx context.Context, db *xorm.Engine, bus events.EventBus,
|
func runStep(ctx context.Context, db *xorm.Engine, bus events.EventBus,
|
||||||
runID, jobID int64, step *models.PipelineStep, image, workDir string) (int, error) {
|
runID, jobID int64, step *models.PipelineStep, image, workDir string,
|
||||||
|
secrets map[string]string) (int, error) {
|
||||||
|
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
step.Status = "running"
|
step.Status = "running"
|
||||||
step.StartedAt = &now
|
step.StartedAt = &now
|
||||||
db.ID(step.ID).Cols("status", "started_at").Update(step) //nolint:errcheck
|
db.ID(step.ID).Cols("status", "started_at").Update(step) //nolint:errcheck
|
||||||
|
|
||||||
cmd := exec.CommandContext(ctx, "docker", "run", "--rm",
|
// Build docker args: base flags + one --env per secret.
|
||||||
"-v", workDir+":/workspace",
|
args := []string{"run", "--rm",
|
||||||
|
"-v", workDir + ":/workspace",
|
||||||
"-w", "/workspace",
|
"-w", "/workspace",
|
||||||
"--network=none", // no network by default; Phase 2C will add network scopes
|
"--network=none",
|
||||||
image,
|
}
|
||||||
"/bin/sh", "-ec", step.RunCmd,
|
for k, v := range secrets {
|
||||||
)
|
args = append(args, "--env", k+"="+v)
|
||||||
|
}
|
||||||
|
args = append(args, image, "/bin/sh", "-ec", step.RunCmd)
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, "docker", args...)
|
||||||
|
|
||||||
stdout, err := cmd.StdoutPipe()
|
stdout, err := cmd.StdoutPipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -235,8 +242,9 @@ func repoForRun(db *xorm.Engine, runID int64) (models.Repository, models.Pipelin
|
|||||||
return repo, run, true
|
return repo, run, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildJobContext assembles a JobContext from DB rows.
|
// buildJobContext assembles a JobContext from DB rows and resolves the secret
|
||||||
func buildJobContext(db *xorm.Engine, jobID int64) (JobContext, bool) {
|
// hierarchy (Env > Repo > Workspace > Global) for injection into docker run.
|
||||||
|
func buildJobContext(db *xorm.Engine, jobID int64, sessionSecret string) (JobContext, bool) {
|
||||||
var job models.PipelineJob
|
var job models.PipelineJob
|
||||||
if found, _ := db.ID(jobID).Get(&job); !found {
|
if found, _ := db.ID(jobID).Get(&job); !found {
|
||||||
return JobContext{}, false
|
return JobContext{}, false
|
||||||
@@ -249,7 +257,42 @@ func buildJobContext(db *xorm.Engine, jobID int64) (JobContext, bool) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return JobContext{}, false
|
return JobContext{}, false
|
||||||
}
|
}
|
||||||
return JobContext{Run: run, Job: job, Steps: steps, Repo: repo}, true
|
|
||||||
|
// Determine workspace ID (0 if user-owned repo).
|
||||||
|
var wsID int64
|
||||||
|
if repo.WorkspaceID != nil {
|
||||||
|
wsID = *repo.WorkspaceID
|
||||||
|
}
|
||||||
|
|
||||||
|
secrets := resolveSecrets(db, repo.ID, wsID, 0, sessionSecret)
|
||||||
|
return JobContext{Run: run, Job: job, Steps: steps, Repo: repo, Secrets: secrets}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveSecrets builds a merged key→plaintext map respecting hierarchy:
|
||||||
|
// Global < Workspace < Repo < Env (last writer wins per key).
|
||||||
|
func resolveSecrets(db *xorm.Engine, repoID, workspaceID, envID int64, sessionSecret string) map[string]string {
|
||||||
|
out := map[string]string{}
|
||||||
|
|
||||||
|
load := func(scope models.SecretScope, scopeID int64) {
|
||||||
|
var secrets []models.Secret
|
||||||
|
db.Where("scope = ? AND scope_id = ?", scope, scopeID).Find(&secrets)
|
||||||
|
for _, s := range secrets {
|
||||||
|
// Higher-priority scopes loaded later — simply overwrite.
|
||||||
|
if pt, err := models.DecryptSecret(s.EncryptedValue, sessionSecret); err == nil {
|
||||||
|
out[s.Name] = pt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
load(models.SecretScopeGlobal, 0)
|
||||||
|
if workspaceID != 0 {
|
||||||
|
load(models.SecretScopeWorkspace, workspaceID)
|
||||||
|
}
|
||||||
|
load(models.SecretScopeRepo, repoID)
|
||||||
|
if envID != 0 {
|
||||||
|
load(models.SecretScopeEnv, envID)
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// pipeForRun returns the longest-matching step label for an image.
|
// pipeForRun returns the longest-matching step label for an image.
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ func (m *RunnerManager) Start(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
jc, ok := buildJobContext(m.db, evt.JobID)
|
jc, ok := buildJobContext(m.db, evt.JobID, m.cfg.SessionSecret)
|
||||||
if !ok {
|
if !ok {
|
||||||
log.Printf("runner: could not build job context for job %d", evt.JobID)
|
log.Printf("runner: could not build job context for job %d", evt.JobID)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -40,5 +40,11 @@ func Run(engine *xorm.Engine) error {
|
|||||||
if err := Run009(engine); err != nil {
|
if err := Run009(engine); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return Run010(engine)
|
if err := Run010(engine); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := Run011(engine); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return Run012(engine)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/forgeo/forgebucket/internal/models"
|
||||||
|
"xorm.io/xorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Run011 adds the workspace and workspace_member tables and adds the nullable
|
||||||
|
// workspace_id column to the repository table to support workspace-owned repos.
|
||||||
|
func Run011(engine *xorm.Engine) error {
|
||||||
|
if err := engine.Sync2(
|
||||||
|
&models.Workspace{},
|
||||||
|
&models.WorkspaceMember{},
|
||||||
|
); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Sync2 on Repository will add the new workspace_id column to existing rows
|
||||||
|
// (default NULL, meaning existing repos remain user-owned).
|
||||||
|
return engine.Sync2(&models.Repository{})
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/forgeo/forgebucket/internal/models"
|
||||||
|
"xorm.io/xorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Run012(engine *xorm.Engine) error {
|
||||||
|
return engine.Sync2(&models.Secret{})
|
||||||
|
}
|
||||||
@@ -3,13 +3,14 @@ package models
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Repository struct {
|
type Repository struct {
|
||||||
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||||
OwnerID int64 `xorm:"'owner_id' notnull index" json:"ownerId"`
|
OwnerID int64 `xorm:"'owner_id' index" json:"ownerId"` // user ID; 0 when workspace-owned
|
||||||
Name string `xorm:"'name' notnull varchar(100)" json:"name"`
|
WorkspaceID *int64 `xorm:"'workspace_id' index" json:"workspaceId"` // set when workspace-owned
|
||||||
Description string `xorm:"'description' varchar(500)" json:"description"`
|
Name string `xorm:"'name' notnull varchar(100)" json:"name"`
|
||||||
IsPrivate bool `xorm:"'is_private' default false" json:"isPrivate"`
|
Description string `xorm:"'description' varchar(500)" json:"description"`
|
||||||
|
IsPrivate bool `xorm:"'is_private' default false" json:"isPrivate"`
|
||||||
DefaultBranch string `xorm:"'default_branch' default 'main' varchar(255)" json:"defaultBranch"`
|
DefaultBranch string `xorm:"'default_branch' default 'main' varchar(255)" json:"defaultBranch"`
|
||||||
DiskPath string `xorm:"'disk_path' notnull" json:"-"`
|
DiskPath string `xorm:"'disk_path' notnull" json:"-"`
|
||||||
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
||||||
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
|
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SecretScope controls which resources a secret is visible to.
|
||||||
|
type SecretScope string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SecretScopeGlobal SecretScope = "global" // admin-only; available to all repos
|
||||||
|
SecretScopeWorkspace SecretScope = "workspace" // available to all repos in a workspace
|
||||||
|
SecretScopeRepo SecretScope = "repo" // specific repository
|
||||||
|
SecretScopeEnv SecretScope = "env" // specific environment (highest priority)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Secret stores an AES-256-GCM encrypted key/value pair.
|
||||||
|
// Values are write-only: the API never returns the plaintext after creation.
|
||||||
|
// Uniqueness: (scope, scope_id, name) must be unique.
|
||||||
|
type Secret struct {
|
||||||
|
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||||
|
Scope SecretScope `xorm:"'scope' varchar(20) notnull" json:"scope"`
|
||||||
|
ScopeID int64 `xorm:"'scope_id'" json:"scopeId"` // 0 for global
|
||||||
|
Name string `xorm:"'name' varchar(255) notnull" json:"name"`
|
||||||
|
EncryptedValue string `xorm:"'encrypted_value' text notnull" json:"-"` // never serialised
|
||||||
|
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Encryption helpers ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// deriveKey produces a 32-byte AES key from the session secret via SHA-256.
|
||||||
|
func deriveKey(sessionSecret string) []byte {
|
||||||
|
h := sha256.Sum256([]byte(sessionSecret))
|
||||||
|
return h[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncryptSecret encrypts plaintext with AES-256-GCM and returns a base64 string
|
||||||
|
// of the form: base64(nonce || ciphertext).
|
||||||
|
func EncryptSecret(plaintext, sessionSecret string) (string, error) {
|
||||||
|
key := deriveKey(sessionSecret)
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("aes cipher: %w", err)
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("gcm: %w", err)
|
||||||
|
}
|
||||||
|
nonce := make([]byte, gcm.NonceSize())
|
||||||
|
if _, err := rand.Read(nonce); err != nil {
|
||||||
|
return "", fmt.Errorf("nonce: %w", err)
|
||||||
|
}
|
||||||
|
sealed := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||||
|
return base64.StdEncoding.EncodeToString(sealed), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecryptSecret reverses EncryptSecret.
|
||||||
|
func DecryptSecret(encrypted, sessionSecret string) (string, error) {
|
||||||
|
data, err := base64.StdEncoding.DecodeString(encrypted)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("base64: %w", err)
|
||||||
|
}
|
||||||
|
key := deriveKey(sessionSecret)
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("aes cipher: %w", err)
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("gcm: %w", err)
|
||||||
|
}
|
||||||
|
if len(data) < gcm.NonceSize() {
|
||||||
|
return "", fmt.Errorf("ciphertext too short")
|
||||||
|
}
|
||||||
|
nonce, ct := data[:gcm.NonceSize()], data[gcm.NonceSize():]
|
||||||
|
pt, err := gcm.Open(nil, nonce, ct, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("decrypt: %w", err)
|
||||||
|
}
|
||||||
|
return string(pt), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// WorkspaceRole controls what a member can do inside a workspace.
|
||||||
|
type WorkspaceRole string
|
||||||
|
|
||||||
|
const (
|
||||||
|
WorkspaceRoleOwner WorkspaceRole = "owner"
|
||||||
|
WorkspaceRoleAdmin WorkspaceRole = "admin"
|
||||||
|
WorkspaceRoleMember WorkspaceRole = "member"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Workspace is a named collaborative namespace that can own repositories.
|
||||||
|
// Its handle must be globally unique across all usernames and workspace handles
|
||||||
|
// so that /{owner}/{repo} URLs remain unambiguous.
|
||||||
|
type Workspace struct {
|
||||||
|
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||||
|
Handle string `xorm:"'handle' unique notnull varchar(64)" json:"handle"`
|
||||||
|
DisplayName string `xorm:"'display_name' varchar(255)" json:"displayName"`
|
||||||
|
Description string `xorm:"'description' text" json:"description"`
|
||||||
|
AvatarURL string `xorm:"'avatar_url' varchar(500)" json:"avatarUrl"`
|
||||||
|
CreatedBy int64 `xorm:"'created_by' notnull" json:"createdBy"`
|
||||||
|
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkspaceMember links a User to a Workspace with a role.
|
||||||
|
type WorkspaceMember struct {
|
||||||
|
ID int64 `xorm:"'id' pk autoincr" json:"id"`
|
||||||
|
WorkspaceID int64 `xorm:"'workspace_id' notnull index" json:"workspaceId"`
|
||||||
|
UserID int64 `xorm:"'user_id' notnull index" json:"userId"`
|
||||||
|
Username string `xorm:"'username' varchar(64)" json:"username"`
|
||||||
|
Role WorkspaceRole `xorm:"'role' varchar(20)" json:"role"`
|
||||||
|
AddedAt time.Time `xorm:"'added_at' created" json:"addedAt"`
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user