Public: anyone can read this; the crew can change it.

A work repo as a read-only origin: fetch only, private, granted to his own apps #10443

Parked opened this in answer to
Closed without merging

scout/forge:scout/10414-a-work-repo-as-a-read-only-origin-fetch → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
34 files changed +583 −5
docs/features/work-origin.md added +30
@@ -0,0 +1,30 @@
1 # A work repository, read-only (#10414)
2
3 Your employer's git host, counted in your forge's view of your work, and never
4 written to.
5
6 **Adding one.** Settings → Origins → token: tick *Work repository (read-only)*,
7 or `POST /api/v1/user/origins` with `"readOnly": true`. The token is validated,
8 sealed at rest and never shown back. The forge fetches on the origin sync
9 schedule (every ten minutes): commits, branches, issues, merged and open
10 pulls, and reviews where the host's API has them.
11
12 **No way back.** `writesPaused` answers the read-only sentence for a work
13 origin, and every write path asks it: write-through (`origin_read_only`),
14 pushes through a mirror, carried branches, forks, contributions, the
15 migration mirror-out, webhooks on the origin. The provider adapter refuses any
16 request that is not a read. `test/work-origin.test.ts` walks them all.
17
18 **Private.** The copy is always private, and no setting makes it public, so it
19 is in no public page, changelog, Talk, search for others or crew brief. Only its
20 owner sees the origin at all. The owner grants an app a scoped read with
21 `POST /api/v1/user/origins/:id/grants` `{"repo": "owner/app"}` (`GET` lists,
22 `DELETE .../grants/:owner/:name` withdraws); `appMayReadWork` is the question
23 an app's reader asks.
24
25 **Its place.** Your profile shows *work (read-only)* to you alone, with the
26 last fetch time and a failed fetch in one line.
27
28 **Not done.** Handing the granted read to a running app (a token an app can
29 present) is not built: the grant is recorded and checkable. A crew member is
30 granted by the existing repository crew grant on the private copy.
src/actions/branches.ts +1
@@ -178,6 +178,7 @@ export async function originPush(
178178 > {
179179 const link = originForRepo(app.db, repo.id);
180180 if (!link) return ok(undefined);
181 if (link.origin.readOnly) return err("origin_read_only");
181182 if (link.origin.userId !== actor.id) return err("origin_owner_only");
182183 if (link.cloneUrl === "") return err("origin_unreachable");
183184 if (writesPaused(app, link.origin.id) !== undefined)
src/actions/contribute.ts +4
@@ -75,6 +75,8 @@ export type ForkOriginError =
7575 | "origin_refused"
7676 /** The connection is not verified against the operator's rules yet. */
7777 | "origin_paused"
78 /** A work repository (#10414): nothing is forked into it or out of it. */
79 | "origin_read_only"
7880 /** The origin took the request and the fork never appeared in time. */
7981 | "fork_timeout";
8082
@@ -123,6 +125,7 @@ export async function forkOrigin(
123125 // Somebody else's connected account does not exist for you (invariant 9).
124126 const origin = getOriginFor(app.db, user.value.id, originId);
125127 if (!origin) return err("not_found");
128 if (origin.readOnly) return err("origin_read_only");
126129 if (writesPaused(app, origin.id) !== undefined) return err("origin_paused");
127130 const provider = providerForOrigin(app, origin);
128131 if (!provider.ok) return err("origin_unreachable");
@@ -271,6 +274,7 @@ export async function contribute(
271274 if (!proven.ok) return proven;
272275 const origin = getOriginFor(app.db, user.value.id, input.originId);
273276 if (!origin) return err("not_found");
277 if (origin.readOnly) return err("origin_read_only");
274278 if (writesPaused(app, origin.id) !== undefined) return err("origin_paused");
275279 const branch = input.branch.trim();
276280 if (!isSafeRef(branch) || branch.startsWith("refs/"))
src/actions/origins.ts +5
@@ -167,6 +167,8 @@ export interface ConnectInput {
167167 /** Set when the user picked a forge explicitly (GitHub Enterprise). */
168168 kind?: OriginKind;
169169 token: string;
170 /** A work repository (#10414): fetched from, never written to. */
171 readOnly?: boolean;
170172 }
171173
172174 /**
@@ -232,6 +234,7 @@ export async function connectOrigin(
232234 token: input.token.trim(),
233235 authKind: "pat",
234236 software: softwareOf(found.value.software),
237 ...(input.readOnly === true ? { readOnly: true } : {}),
235238 });
236239 if (!stored.ok) return stored;
237240 if (guard.value.checked) noteGuardPassed(app, stored.value.id);
@@ -362,6 +365,7 @@ function storeOrigin(
362365 refreshToken?: string;
363366 expiresAt?: string | null;
364367 software?: string;
368 readOnly?: boolean;
365369 },
366370 ): Result<Origin, "already_connected"> {
367371 // Connecting an account whose credential died is re-authorizing it: the
@@ -406,6 +410,7 @@ function storeOrigin(
406410 : { refreshToken: input.refreshToken }),
407411 ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),
408412 ...(input.software === undefined ? {} : { software: input.software }),
413 ...(input.readOnly === true ? { readOnly: true } : {}),
409414 });
410415 if (!created.ok) return created;
411416 // The payload names the host and the login and nothing else: an audit
src/actions/repos.ts +8
@@ -74,6 +74,7 @@ import {
7474 requireWriter,
7575 type AccessError,
7676 } from "./access.ts";
77 import { originForRepo } from "../core/origins.ts";
7778 import { validPolishShare } from "../crew/small_share.ts";
7879 import { removeInstallCache } from "../crew/workdir.ts";
7980 import type { SettingsChanged } from "../core/settings_changed.ts";
@@ -421,6 +422,13 @@ export async function updateRepoSettings(
421422 // base, whoever owns it (`core/sealed.ts`).
422423 if (repo.sealedFor !== null && settings.visibility === "public")
423424 return err("not_found");
425 // A work repository is private to its owner and the apps they grant
426 // (#10414): no setting makes the copy of it public.
427 if (
428 settings.visibility === "public" &&
429 originForRepo(app.db, repo.id)?.origin.readOnly === true
430 )
431 return err("not_found");
424432 if (settings.polishShare !== undefined && !validPolishShare(settings.polishShare))
425433 return err("polish_share");
426434 const branch = settings.defaultBranch;
src/actions/work_origins.ts added +96
@@ -0,0 +1,96 @@
1 /**
2 * Work origins (#10414): a remote on the owner's employer's host, connected
3 * read-only. Adding one is `connectOrigin` with `readOnly`; this file holds
4 * what is particular to them — who sees one, and which apps it is granted to.
5 *
6 * Only the owner sees a work origin (anyone else gets `not_found`, invariant
7 * 9), and only the owner grants it, and only to an app they administer.
8 */
9
10 import type { App } from "../app.ts";
11 import {
12 getOriginFor,
13 listOrigins,
14 type Origin,
15 } from "../core/origins.ts";
16 import {
17 grantRead,
18 grantedRepoIds,
19 revokeRead,
20 } from "../core/origin_grants.ts";
21 import { canAdmin, getRepoById, type Repo } from "../core/repos.ts";
22 import type { User } from "../core/users.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24
25 export type WorkGrantError = "not_found";
26
27 /** The one line every surface shows about who can see a work origin. */
28 export const WORK_VISIBILITY =
29 "Private: only you, and the apps you grant, can read this. It never appears in public pages, the changelog, Talk, search for others or crew briefs.";
30
31 /** The owner's work origins (read-only), oldest first. */
32 export function listWorkOrigins(app: App, actor: User): Origin[] {
33 return listOrigins(app.db, actor.id).filter((o) => o.readOnly);
34 }
35
36 /** One line for a failed fetch: no more than a sentence, never the credential. */
37 export function fetchFailureLine(origin: Origin): string {
38 if (origin.needsReauth)
39 return "The credential no longer works: replace the token to fetch again.";
40 if (origin.lastError === "") return "";
41 const first = (origin.lastError.split("\n")[0] ?? "").trim();
42 return first.length > 160 ? `${first.slice(0, 157)}...` : first;
43 }
44
45 function ownRepo(app: App, actor: User, repoId: string): Repo | undefined {
46 const repo = getRepoById(app.db, repoId);
47 return repo !== undefined && canAdmin(app.db, repo, actor) ? repo : undefined;
48 }
49
50 /** Grant an app a read of a work origin. */
51 export function grantWorkRead(
52 app: App,
53 actor: User,
54 originId: string,
55 repoId: string,
56 ): Result<Repo, WorkGrantError> {
57 const origin = getOriginFor(app.db, actor.id, originId);
58 if (origin === undefined || !origin.readOnly) return err("not_found");
59 const repo = ownRepo(app, actor, repoId);
60 if (repo === undefined) return err("not_found");
61 grantRead(app.db, origin.id, repo.id);
62 app.bus.append({
63 kind: "origin.work_granted",
64 actorId: actor.id,
65 payload: { originId: origin.id, repoId: repo.id },
66 });
67 return ok(repo);
68 }
69
70 export function revokeWorkRead(
71 app: App,
72 actor: User,
73 originId: string,
74 repoId: string,
75 ): Result<true, WorkGrantError> {
76 const origin = getOriginFor(app.db, actor.id, originId);
77 if (origin === undefined || !origin.readOnly) return err("not_found");
78 if (!revokeRead(app.db, origin.id, repoId)) return err("not_found");
79 app.bus.append({
80 kind: "origin.work_revoked",
81 actorId: actor.id,
82 payload: { originId: origin.id, repoId },
83 });
84 return ok(true);
85 }
86
87 export function workGrants(app: App, actor: User, originId: string): Result<Repo[], WorkGrantError> {
88 const origin = getOriginFor(app.db, actor.id, originId);
89 if (origin === undefined || !origin.readOnly) return err("not_found");
90 return ok(
91 grantedRepoIds(app.db, origin.id).flatMap((id) => {
92 const repo = getRepoById(app.db, id);
93 return repo === undefined ? [] : [repo];
94 }),
95 );
96 }
src/contract/openapi/routes/deleteApiV1UserOriginsIdGrantsOwnerName.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 const U = "no valid credentials were sent";
4 const F = "the credential is not the account: a session from another origin, or a token without admin scope";
5 const NF = "no such work origin among the caller's, or no such repository";
6
7 export const route: Route = {
8 method: "delete",
9 path: "/api/v1/user/origins/{id}/grants/{owner}/{name}",
10 summary: "Revoke an app's read access to a work origin of the caller's; the account only",
11 auth: true,
12 refusals: { unauthorized: U, forbidden: F, not_found: NF },
13 };
src/contract/openapi/routes/getApiV1UserOriginsIdGrants.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 const U = "no valid credentials were sent";
4 const F = "the credential is not the account: a session from another origin, or a token without admin scope";
5 const NF = "no such work origin among the caller's, or no such repository";
6
7 export const route: Route = {
8 method: "get",
9 path: "/api/v1/user/origins/{id}/grants",
10 summary: "List the repositories (owner/name) that may read a work origin of the caller's; the account only",
11 auth: true,
12 refusals: { unauthorized: U, forbidden: F, not_found: NF },
13 };
src/contract/openapi/routes/index.ts +3
@@ -31,6 +31,7 @@ export { route as deleteApiV1TokensId } from "./deleteApiV1TokensId.ts";
3131 export { route as deleteApiV1UserKeysId } from "./deleteApiV1UserKeysId.ts";
3232 export { route as deleteApiV1UserOriginAppsId } from "./deleteApiV1UserOriginAppsId.ts";
3333 export { route as deleteApiV1UserOriginsId } from "./deleteApiV1UserOriginsId.ts";
34 export { route as deleteApiV1UserOriginsIdGrantsOwnerName } from "./deleteApiV1UserOriginsIdGrantsOwnerName.ts";
3435 export { route as deleteApiV1UserPinsOwnerName } from "./deleteApiV1UserPinsOwnerName.ts";
3536 export { route as deleteApiV1UsersUsernameSessionsId } from "./deleteApiV1UsersUsernameSessionsId.ts";
3637 export { route as getApiV1 } from "./getApiV1.ts";
@@ -197,6 +198,7 @@ export { route as getApiV1UserOriginsIdBrowseOwnerNamePullsNumber } from "./getA
197198 export { route as getApiV1UserOriginsIdBrowseOwnerNameTags } from "./getApiV1UserOriginsIdBrowseOwnerNameTags.ts";
198199 export { route as getApiV1UserOriginsIdBrowseOwnerNameTreeRef } from "./getApiV1UserOriginsIdBrowseOwnerNameTreeRef.ts";
199200 export { route as getApiV1UserOriginsIdBrowseOwnerNameTreeRefPath } from "./getApiV1UserOriginsIdBrowseOwnerNameTreeRefPath.ts";
201 export { route as getApiV1UserOriginsIdGrants } from "./getApiV1UserOriginsIdGrants.ts";
200202 export { route as getApiV1UserOriginsIdMirrorJob } from "./getApiV1UserOriginsIdMirrorJob.ts";
201203 export { route as getApiV1UserOriginsIdMirrorJobStream } from "./getApiV1UserOriginsIdMirrorJobStream.ts";
202204 export { route as getApiV1UserOriginsIdRepos } from "./getApiV1UserOriginsIdRepos.ts";
@@ -346,6 +348,7 @@ export { route as postApiV1UserOriginApps } from "./postApiV1UserOriginApps.ts";
346348 export { route as postApiV1UserOrigins } from "./postApiV1UserOrigins.ts";
347349 export { route as postApiV1UserOriginsIdBrowseOwnerNameContribute } from "./postApiV1UserOriginsIdBrowseOwnerNameContribute.ts";
348350 export { route as postApiV1UserOriginsIdFork } from "./postApiV1UserOriginsIdFork.ts";
351 export { route as postApiV1UserOriginsIdGrants } from "./postApiV1UserOriginsIdGrants.ts";
349352 export { route as postApiV1UserOriginsIdMirror } from "./postApiV1UserOriginsIdMirror.ts";
350353 export { route as postApiV1UserOriginsIdSync } from "./postApiV1UserOriginsIdSync.ts";
351354 export { route as postApiV1UserOriginsOauth } from "./postApiV1UserOriginsOauth.ts";
src/contract/openapi/routes/postApiV1UserOriginsIdGrants.ts added +15
@@ -0,0 +1,15 @@
1 import type { Route } from "../shared.ts";
2
3 const U = "no valid credentials were sent";
4 const F = "the credential is not the account: a session from another origin, or a token without admin scope";
5 const NF = "no such work origin among the caller's, or no such repository";
6
7 export const route: Route = {
8 method: "post",
9 path: "/api/v1/user/origins/{id}/grants",
10 summary: "Grant an app read access to a work origin of the caller's; answers 201 with { repo, access: \"read\" }; the account only",
11 auth: true,
12 status: 201,
13 body: { repo: "string" },
14 refusals: { unauthorized: U, forbidden: F, not_found: NF },
15 };
src/core/migration-pins/20261109200000-work-origin.pin added +1
@@ -0,0 +1,1 @@
1 ea575566a6c737e23482249368350fb0bdeb74abef742d35136fe5cafc15936b
src/core/migrations/20261109200000-work-origin.ts added +15
@@ -0,0 +1,15 @@
1 // A work repository as a read-only origin (#10414). `read_only` marks an
2 // origin that may only be fetched from: every write path refuses it. It is
3 // private to its owner and to the apps the owner grants (`origin_grant`, a
4 // scoped read grant naming one app repository). Additive.
5 export default `
6 ALTER TABLE origin ADD COLUMN read_only INTEGER NOT NULL DEFAULT 0;
7
8 CREATE TABLE origin_grant (
9 origin_id TEXT NOT NULL REFERENCES origin(id) ON DELETE CASCADE,
10 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
11 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
12 PRIMARY KEY (origin_id, repo_id)
13 );
14 CREATE INDEX origin_grant_repo ON origin_grant(repo_id);
15 `;
src/core/origin_grants.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * Which apps may read a work origin (#10414). A work origin is private to its
3 * owner; the owner hands a scoped read to one app repository at a time. The
4 * grant names an origin and an app, carries no write, and goes with either.
5 * Pure data access, like the rest of `core/`: who may grant is decided in
6 * `actions/work_origins.ts`.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 export function grantRead(db: Database, originId: string, repoId: string): void {
12 db.query(
13 "INSERT OR IGNORE INTO origin_grant (origin_id, repo_id) VALUES (?1, ?2)",
14 ).run(originId, repoId);
15 }
16
17 export function revokeRead(db: Database, originId: string, repoId: string): boolean {
18 return (
19 db
20 .query("DELETE FROM origin_grant WHERE origin_id = ?1 AND repo_id = ?2")
21 .run(originId, repoId).changes > 0
22 );
23 }
24
25 /** The app repositories granted a read of this origin. */
26 export function grantedRepoIds(db: Database, originId: string): string[] {
27 return db
28 .query<{ repo_id: string }, [string]>(
29 "SELECT repo_id FROM origin_grant WHERE origin_id = ?1 ORDER BY created_at, repo_id",
30 )
31 .all(originId)
32 .map((r) => r.repo_id);
33 }
34
35 export function mayRead(db: Database, originId: string, repoId: string): boolean {
36 return (
37 db
38 .query("SELECT 1 FROM origin_grant WHERE origin_id = ?1 AND repo_id = ?2")
39 .get(originId, repoId) !== null
40 );
41 }
src/core/origins.ts +7 −2
@@ -36,6 +36,7 @@ interface OriginRow {
3636 expires_at: string | null;
3737 needs_reauth: number;
3838 software: string;
39 read_only: number;
3940 }
4041
4142 function toOrigin(row: OriginRow): Origin {
@@ -53,6 +54,7 @@ function toOrigin(row: OriginRow): Origin {
5354 expiresAt: row.expires_at,
5455 needsReauth: row.needs_reauth === 1,
5556 software: row.software,
57 readOnly: row.read_only === 1,
5658 };
5759 }
5860
@@ -72,6 +74,8 @@ export interface CreateOriginInput {
7274 expiresAt?: string | null;
7375 /** `forge` for another forge; see `Origin.software`. */
7476 software?: string;
77 /** A work repository: fetched from, never written to. */
78 readOnly?: boolean;
7579 }
7680
7781 export type CreateOriginError = "already_connected";
@@ -97,8 +101,8 @@ export function createOrigin(
97101 const originId = id();
98102 db.query(
99103 `INSERT INTO origin (id, user_id, kind, api_url, web_url, login, token_enc,
100 auth_kind, refresh_token_enc, expires_at, software)
101 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`,
104 auth_kind, refresh_token_enc, expires_at, software, read_only)
105 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)`,
102106 ).run(
103107 originId,
104108 input.userId,
@@ -113,6 +117,7 @@ export function createOrigin(
113117 : seal(dataDir, input.refreshToken, originId),
114118 input.expiresAt ?? null,
115119 input.software ?? "",
120 input.readOnly === true ? 1 : 0,
116121 );
117122 return ok(getOriginById(db, originId)!);
118123 }
src/design/activity.ts +2
@@ -194,6 +194,8 @@ const WORDS: Record<string, string> = {
194194 "webhook.failing": "had a webhook fail three deliveries in a row",
195195 "origin.connected": "connected an origin",
196196 "origin.disconnected": "disconnected an origin",
197 "origin.work_granted": "granted an app a read of a work repository",
198 "origin.work_revoked": "withdrew an app's read of a work repository",
197199 "origin.needs_reauth": "needs to reconnect an origin",
198200 "origin.mirror_reattached": "reconnected a frozen mirror to its origin",
199201 "build.pinned": "pinned a build",
src/http/api.ts +8
@@ -574,6 +574,8 @@ export function originJson(origin: Origin) {
574574 needsReauth: origin.needsReauth,
575575 expiresAt: origin.expiresAt,
576576 software: origin.software,
577 // A work repository: fetched from, never written to (#10414).
578 readOnly: origin.readOnly,
577579 // What a forge origin does not bring, said where a client reads the origin.
578580 carries: origin.software === "forge" ? FORGE_NOT_CARRIED : null,
579581 };
@@ -679,6 +681,12 @@ export function originAware(error: string, status = 422): Response {
679681 409,
680682 "the operator protects this repository at its origin: nothing is pushed to it from here; propose the change from your fork",
681683 );
684 if (error === "origin_read_only")
685 return apiError(
686 "origin_read_only",
687 409,
688 "this is a work repository, connected read-only: nothing is written to it; nothing was changed",
689 );
682690 if (error === "origin_paused")
683691 return apiError(
684692 "origin_paused",
src/http/api/user.ts +35 −1
@@ -9,6 +9,7 @@ import { contribute, forkOrigin } from "../../actions/contribute.ts";
99 import { CAPPED_WORDS } from "../../actions/mail.ts";
1010 import { ORIGIN_UNREACHABLE } from "../../actions/origin_app_words.ts";
1111 import { connectOrigin, connectRefusal, listOriginRepoGroup, deleteOriginApp, disconnectOrigin, listOriginApps, listPinned, listRemoteRepos, listUserOrigins, mirrorJobFor, pinRepo, pollOAuthConnect, registerOriginApp, startMirrorJob, startOAuthConnect, syncOriginNow, unpinRepo } from "../../actions/origins.ts";
12 import { grantWorkRead, revokeWorkRead, workGrants } from "../../actions/work_origins.ts";
1213 import { addSshKey, changePassword, deleteSshKey, updateProfile } from "../../actions/users.ts";
1314 import { VERIFY_WORDS } from "../../actions/verify_words.ts";
1415 import { resendVerification } from "../../actions/verify.ts";
@@ -17,7 +18,7 @@ import { listAssignedTo } from "../../core/issues.ts";
1718 import { nextStepsFor } from "../../core/next-steps.ts";
1819 import { listKeys, publicKey } from "../../core/keys.ts";
1920 import { listOrgsForUser } from "../../core/orgs.ts";
20 import { canRead, getReposByIds } from "../../core/repos.ts";
21 import { canRead, getRepo, getReposByIds } from "../../core/repos.ts";
2122 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
2223 import { mayView } from "../../core/sealed.ts";
2324 import { emailVerified } from "../../core/verify.ts";
@@ -269,6 +270,7 @@ export function userRoutes(router: Router<Handler>): void {
269270 ? { kind }
270271 : {}),
271272 token: str(input.token),
273 ...(input.readOnly === true ? { readOnly: true } : {}),
272274 });
273275 if (!connected.ok) {
274276 // A refusal that names its own reason (a missing scope) keeps it;
@@ -291,6 +293,38 @@ export function userRoutes(router: Router<Handler>): void {
291293 );
292294 });
293295
296 // A work origin's grants: which apps may read it (#10414). Account-gated
297 // like every origin route; an origin that is not yours or not a work one is
298 // not found.
299 const grantee = (ctx: Ctx, repoRef: string) => {
300 const [owner, name] = repoRef.split("/");
301 return owner === undefined || name === undefined ? undefined : getRepo(ctx.app.db, owner, name);
302 };
303 router.add("GET", "/api/v1/user/origins/:id/grants", (ctx) => {
304 const denied = requireAccount(ctx, { adminToken: true });
305 if (denied) return denied;
306 const granted = workGrants(ctx.app, ctx.auth.user!, ctx.params.id ?? "");
307 if (!granted.ok) return notFound();
308 return json(granted.value.map((r) => `${r.ownerName}/${r.name}`));
309 });
310 router.add("POST", "/api/v1/user/origins/:id/grants", async (ctx) => {
311 const denied = requireAccount(ctx, { adminToken: true });
312 if (denied) return denied;
313 const input = await body(ctx.request);
314 const repo = grantee(ctx, str(input.repo));
315 const granted = repo === undefined ? undefined : grantWorkRead(ctx.app, ctx.auth.user!, ctx.params.id ?? "", repo.id);
316 if (granted === undefined || !granted.ok) return notFound();
317 return json({ repo: `${repo!.ownerName}/${repo!.name}`, access: "read" }, 201);
318 });
319 router.add("DELETE", "/api/v1/user/origins/:id/grants/:owner/:name", (ctx) => {
320 const denied = requireAccount(ctx, { adminToken: true });
321 if (denied) return denied;
322 const repo = grantee(ctx, `${ctx.params.owner ?? ""}/${ctx.params.name ?? ""}`);
323 const revoked = repo === undefined ? undefined : revokeWorkRead(ctx.app, ctx.auth.user!, ctx.params.id ?? "", repo.id);
324 if (revoked === undefined || !revoked.ok) return notFound();
325 return json({ ok: true });
326 });
327
294328 // OAuth: one start route for both flows, because which flow you get is a
295329 // property of the forge (device on GitHub, code+PKCE on Forgejo) and not
296330 // something a client should have to know.
src/origins/credential.ts +5
@@ -247,6 +247,10 @@ const GUARD_GIVE_UP_MS = 24 * 60 * 60_000;
247247 /** The sweep's pause between requests: one origin at a time, gently. */
248248 const SWEEP_PAUSE_MS = 500;
249249
250 /** What a write through a work (read-only) origin is told, everywhere (#10414). */
251 export const READ_ONLY =
252 "This is a work repository, connected read-only: the forge fetches from it and never writes to it.";
253
250254 /** What a write through a paused origin is told, everywhere. */
251255 export const WRITES_PAUSED =
252256 "This forge could not verify this connection against the operator's rules, so writes through it are paused. Reads and sync go on. Check it again under Settings → Origins.";
@@ -262,6 +266,7 @@ export const WRITES_PAUSED =
262266 */
263267 export function writesPaused(app: App, originId: string): string | undefined {
264268 const origin = getOriginById(app.db, originId);
269 if (origin?.readOnly === true) return READ_ONLY;
265270 if (origin === undefined || origin.needsReauth || !guarded(origin))
266271 return undefined;
267272 const checked = getCursor(app.db, originId, CHECKED);
src/origins/hook.ts +2
@@ -80,6 +80,8 @@ export async function watchPulls(app: App, repo: Repo): Promise<void> {
8080 const link = originForRepo(app.db, repo.id);
8181 const url = hookUrl(app, repo);
8282 if (!link || url === undefined || link.origin.software !== "forge") return;
83 // A work repository is only read: no hook is planted on it (#10414).
84 if (link.origin.readOnly) return;
8385 const provider = providerForOrigin(app, link.origin);
8486 if (!provider.ok || provider.value.watch === undefined) return;
8587 await provider.value.watch(link.fullName, { url, secret: hookSecret(app, repo) });
src/origins/mirror.ts +1 −1
@@ -147,7 +147,7 @@ export async function mirrorRepo(
147147 const created = await createRepo(app.db, app.reposRoot, {
148148 ownerId: actor.id,
149149 name: chosen,
150 visibility: remote.private ? "private" : "public",
150 visibility: remote.private || origin.readOnly ? "private" : "public",
151151 description: remote.description,
152152 defaultBranch,
153153 });
src/origins/push-through.ts +2 −1
@@ -37,7 +37,7 @@ import { FORWARDED_GIT_ENV, type RefUpdate } from "../git/hook-protocol.ts";
3737 import { fetchInto, resolveOid, writeRef } from "../git/merge.ts";
3838 import { repoDir } from "../git/repos.ts";
3939 import { err, ok, type Result } from "../kernel/result.ts";
40 import { providerForOrigin, writesPaused } from "./credential.ts";
40 import { READ_ONLY, providerForOrigin, writesPaused } from "./credential.ts";
4141 import { redact, secretsIn } from "./credentials.ts";
4242 import { pushToOrigin, snapshotRefs } from "./git-mirror.ts";
4343 import { denied } from "./operator.ts";
@@ -258,6 +258,7 @@ export async function pushToMirrorTarget(
258258 };
259259 const origin = getOriginById(app.db, target.originId);
260260 if (!origin) return fail("the origin was disconnected; reconnect it");
261 if (origin.readOnly) return fail(READ_ONLY);
261262 const provider = providerForOrigin(app, origin);
262263 if (!provider.ok) return fail("the origin needs to be reconnected");
263264 const authEnv = await provider.value.gitAuthEnv(target.cloneUrl);
src/origins/types.ts +6
@@ -47,6 +47,12 @@ export interface Origin {
4747 * forge (stored as a Gitea origin, which is the dialect it speaks), else "".
4848 */
4949 readonly software: string;
50 /**
51 * A work repository (#10414): fetched from, never written to. Every write
52 * path refuses it (`writesPaused`), and it is private to its owner and the
53 * apps the owner grants (`core/origin_grants.ts`).
54 */
55 readonly readOnly: boolean;
5056 }
5157
5258 /** A repository as the origin describes it — the import picker's rows. */
src/origins/write-through.ts +3
@@ -24,6 +24,8 @@ export type WriteThroughError =
2424 | "origin_refused"
2525 /** The account behind the origin is not verified against the operator's rules yet. */
2626 | "origin_paused"
27 /** A work repository, connected read-only (#10414): nothing is written to it. */
28 | "origin_read_only"
2729 /** The operator protects the origin repository: propose from a fork. */
2830 | "origin_protected";
2931
@@ -52,6 +54,7 @@ export function writeThroughFor(
5254 ): Result<WriteThrough | undefined, WriteThroughError> {
5355 const link = originForRepo(app.db, repo.id);
5456 if (!link) return ok(undefined);
57 if (link.origin.readOnly) return err("origin_read_only");
5558 if (link.origin.userId !== actor.id) return err("origin_owner_only");
5659 if (writesPaused(app, link.origin.id) !== undefined)
5760 return err("origin_paused");
src/tui/screens/common.ts +1
@@ -982,6 +982,7 @@ const MESSAGES: Record<string, string> = {
982982 mirrored: "this repo mirrors an origin — do it there",
983983 origin_owner_only: "only whoever connected this origin can write through it",
984984 origin_refused: "the origin refused that; nothing changed here",
985 origin_read_only: "this is a work repository, read-only: nothing is written to it",
985986 origin_paused: "this connection is not verified yet; writes are paused",
986987 origin_protected: "the operator protects this repository at its origin: nothing is pushed to it from here; propose the change from your fork",
987988 origin_unreachable: "the origin could not be reached; nothing changed",
src/web/pages/branches.ts +2
@@ -341,6 +341,8 @@ export const CREATE_ERRORS: Record<string, string> = {
341341 "The origin refused that branch, so nothing was created here.",
342342 origin_protected:
343343 "The operator protects this repository at its origin, so no branch is pushed to it from here. Propose the change from your fork.",
344 origin_read_only:
345 "This is a work repository, connected read-only. Nothing was created.",
344346 origin_paused:
345347 "This connection is not verified yet, so writes through it are paused. Nothing was created. Check it again under Settings → Origins.",
346348 forbidden: "You need write access to create a branch.",
src/web/pages/browse.ts +2
@@ -950,6 +950,8 @@ export function forkFailure(error: string): string {
950950 return "The origin could not be reached. Nothing was created.";
951951 if (error === "origin_refused")
952952 return "The origin refused to fork that repository.";
953 if (error === "origin_read_only")
954 return "This is a work repository, connected read-only. Nothing was created.";
953955 if (error === "origin_paused")
954956 return "This connection is not verified yet, so writes through it are paused. Check it again under Settings → Origins.";
955957 if (error === "mirror_failed")
src/web/pages/edit.ts +2
@@ -128,6 +128,8 @@ export function editErrorText(error: unknown): string {
128128 return "The origin refused this change, so nothing landed here either.";
129129 if (error === "origin_protected")
130130 return "The operator protects this repository at its origin, so nothing is pushed to it from here. Propose the change from your fork.";
131 if (error === "origin_read_only")
132 return "This is a work repository, connected read-only. Nothing is written to it.";
131133 if (error === "origin_paused")
132134 return "This connection is not verified yet, so writes through it are paused. Check it again under Settings → Origins.";
133135 return "That edit could not be saved.";
src/web/pages/org.ts +2
@@ -54,6 +54,7 @@ import { icon } from "../icons.ts";
5454 import { ownerLine } from "../describe.ts";
5555 import { flashTo, page } from "../layout.ts";
5656 import { secretsSection } from "./secrets.ts";
57 import { workSection } from "./work_origins.ts";
5758 import { agentsOnForge, grantsSection, saveGrants } from "./subscriptions.ts";
5859 import { shelfRows } from "../studio/shelf.ts";
5960 import {
@@ -382,6 +383,7 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
382383 : null}
383384 ${apps.html}
384385 ${repos}
386 ${isOrg ? null : workSection(ctx, owner.id)}
385387 ${when(isOrg && accessAllows(access, "read"), () =>
386388 teamsSection(ctx, owner, canManage),
387389 )}
src/web/pages/origins.ts +8
@@ -592,6 +592,13 @@ function tokenSection(values: ConnectValues): Html {
592592 hint: "It is never displayed after this.",
593593 })}
594594 ${tokenNeeds(values.tokenHost)}
595 ${uiField({
596 label: "Work repository (read-only)",
597 name: "readOnly",
598 type: "checkbox",
599 value: "1",
600 hint: "Fetched from, never written to, and private to you and the apps you grant.",
601 })}
595602 <div class="form-actions">${btn("Connect")}</div>
596603 </form>`;
597604 }
@@ -972,6 +979,7 @@ export async function originConnectToken(ctx: Ctx): Promise<Response> {
972979 const connected = await connectOrigin(ctx.app, ctx.auth.user, {
973980 host,
974981 token,
982 ...(field(form, "readOnly") === "1" ? { readOnly: true } : {}),
975983 });
976984 if (!connected.ok) {
977985 // The host comes back; the token deliberately does not. Re-typing a
src/web/pages/thread.ts +2
@@ -94,6 +94,8 @@ export function originError(error: string): string | undefined {
9494 origin_refused: "The origin refused that. Nothing was changed here either.",
9595 origin_protected:
9696 "The operator protects this repository at its origin, so nothing is pushed to it from here. Propose the change from your fork.",
97 origin_read_only:
98 "This is a work repository, connected read-only. Nothing is written to it, and nothing was changed.",
9799 origin_paused:
98100 "This connection is not verified yet, so writes through it are paused. Nothing was changed. Check it again under Settings → Origins.",
99101 origin_unreachable: "The origin could not be reached. Nothing was changed.",
src/web/pages/work_origins.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * "work (read-only)" on a person's own profile (#10414): each work origin
3 * with its last fetch time, a failed fetch explained in one line, and who
4 * may see it. Shown to its owner alone; nobody else is told one exists.
5 */
6
7 import { fetchFailureLine, listWorkOrigins, WORK_VISIBILITY } from "../../actions/work_origins.ts";
8 import type { Ctx } from "../../http/context.ts";
9 import { html, type Html } from "../html.ts";
10 import { icon } from "../icons.ts";
11 import { row, listCard, time } from "../ui.ts";
12
13 export function workSection(ctx: Ctx, ownerId: string): Html | null {
14 const user = ctx.auth.user;
15 if (user === undefined || user.id !== ownerId) return null;
16 const origins = listWorkOrigins(ctx.app, user);
17 if (origins.length === 0) return null;
18 return html`<section class="settings-block mt" id="work">
19 <h2>work (read-only)</h2>
20 <p class="muted small">${WORK_VISIBILITY}</p>
21 ${listCard(
22 origins.map((o) => {
23 const failure = fetchFailureLine(o);
24 return row({
25 lead: icon("lock"),
26 title: `${o.login} @ ${o.webUrl.replace(/^https?:\/\//, "")}`,
27 meta: o.lastSyncAt === null
28 ? html`not fetched yet`
29 : html`last fetch ${time(o.lastSyncAt)}`,
30 facts: failure === "" ? [] : [{ label: "Last fetch failed", value: failure }],
31 });
32 }),
33 )}
34 </section>`;
35 }
test/security-floor-routes.test.ts +1
@@ -102,6 +102,7 @@ const UNSEEDED: Record<string, string> = {
102102 "/api/v1/user/origins/:id/browse/:owner/:name/tags": ORIGIN,
103103 "/api/v1/user/origins/:id/browse/:owner/:name/tree/:ref": ORIGIN,
104104 "/api/v1/user/origins/:id/browse/:owner/:name/tree/:ref/*path": ORIGIN,
105 "/api/v1/user/origins/:id/grants": ORIGIN,
105106 "/api/v1/user/origins/:id/mirror/:job": ORIGIN,
106107 "/api/v1/user/origins/:id/mirror/:job/stream": ORIGIN,
107108 "/api/v1/user/origins/:id/repos": ORIGIN,
test/tui-waves.test.ts +1
@@ -54,6 +54,7 @@ const remoteOf = (src: RepoSource): RepoSource => ({
5454 authKind: "pat",
5555 expiresAt: null,
5656 needsReauth: false,
57 readOnly: false,
5758 software: "",
5859 },
5960 fullName: "someone/else",
test/work-origin.test.ts added +211
@@ -0,0 +1,211 @@
1 /**
2 * A work repository as a read-only origin (#10414): fetched from, never
3 * written to, private to its owner and the apps granted.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { connectOrigin, startMirrorJob } from "../src/actions/origins.ts";
13 import { contribute, forkOrigin } from "../src/actions/contribute.ts";
14 import { openIssueThrough } from "../src/actions/issues.ts";
15 import { originPush } from "../src/actions/branches.ts";
16 import { updateRepoSettings } from "../src/actions/repos.ts";
17 import {
18 fetchFailureLine,
19 grantWorkRead,
20 listWorkOrigins,
21 revokeWorkRead,
22 } from "../src/actions/work_origins.ts";
23 import { carryBranchThrough, pushThrough, pushToMirrorTarget } from "../src/origins/push-through.ts";
24 import { mayRead } from "../src/core/origin_grants.ts";
25 import { listOrigins, recordSync } from "../src/core/origins.ts";
26 import { canRead, getRepoById } from "../src/core/repos.ts";
27 import { createUser, getUserByName, type User } from "../src/core/users.ts";
28 import { createSession } from "../src/core/sessions.ts";
29 import { settled } from "../src/origins/jobs.ts";
30 import { providerForOrigin, writesPaused } from "../src/origins/credential.ts";
31 import { forgetProviders } from "../src/origins/providers/index.ts";
32 import { promote } from "./helpers/members.ts";
33 import { seedAdmin } from "./helpers/admin.ts";
34 import { fastFirstFetch, quietLogs, withoutEnv } from "./helpers/globals.ts";
35 import { newFakeState, serveFakeForge, type FakeForge, type FakeState } from "./fake-origin.ts";
36
37 quietLogs();
38 fastFirstFetch();
39 withoutEnv("FORGE_ORIGIN_CLIENT_ID", "FORGE_ORIGIN_DENY_PUSH", "FORGE_URL");
40
41 const LOGIN = "octo";
42 const TOKEN = "octo-work-secret-5d2a";
43 const PASSWORD = "a-long-work-passphrase";
44 const basic = (user: string, secret: string): string =>
45 `Basic ${Buffer.from(`${user}:${secret}`).toString("base64")}`;
46
47 describe("a work repository as a read-only origin", () => {
48 let upDir: string;
49 let upApp: App;
50 let up: Servers;
51 let fake: FakeForge;
52 let state: FakeState;
53 let dir: string;
54 let app: App;
55 let servers: Servers;
56 let alice: User;
57 let bob: User;
58
59 const member = async (name: string): Promise<User> => {
60 const made = await createUser(app.db, {
61 username: name,
62 email: `${name}@forge.test`,
63 password: PASSWORD,
64 origin: "seed",
65 trusted: true,
66 });
67 if (!made.ok) throw new Error(`no account ${name}`);
68 promote(app.db, made.value);
69 return getUserByName(app.db, name)!;
70 };
71
72 beforeAll(async () => {
73 upDir = await mkdtemp(join(tmpdir(), "forge-work-up-"));
74 upApp = createApp({ dataDir: upDir, port: 0 });
75 up = await serve(upApp);
76 const seeded = await seedAdmin(upApp, { username: LOGIN, email: "[email protected]", password: TOKEN });
77 if (!seeded.ok) throw new Error("no git-host account");
78 const headers = { "content-type": "application/json", authorization: basic(LOGIN, TOKEN) };
79 await fetch(`${up.url}/api/v1/repos`, {
80 method: "POST",
81 headers,
82 body: JSON.stringify({ name: "widgets", visibility: "public" }),
83 });
84 await fetch(`${up.url}/api/v1/repos/octo/widgets/contents`, {
85 method: "POST",
86 headers,
87 body: JSON.stringify({ branch: "main", message: "first", files: [{ path: "README.md", content: "# w\n" }] }),
88 });
89 state = newFakeState("forgejo", LOGIN, TOKEN);
90 state.repos.push({
91 id: 41,
92 fullName: "octo/widgets",
93 // Public upstream: the copy must still be private.
94 cloneUrl: `${up.url}/octo/widgets.git`,
95 htmlUrl: `${up.url}/octo/widgets`,
96 pushedAt: "2026-10-01T00:00:00Z",
97 });
98 fake = serveFakeForge(state);
99 dir = await mkdtemp(join(tmpdir(), "forge-work-"));
100 app = createApp({ dataDir: dir, port: 0 });
101 servers = await serve(app);
102 alice = await member("alice");
103 bob = await member("bob");
104 createSession(app.db, alice.id);
105 });
106
107 afterAll(async () => {
108 fake.stop();
109 up.stop();
110 upApp.close();
111 servers.stop();
112 app.close();
113 forgetProviders(dir);
114 await rm(dir, { recursive: true, force: true });
115 await rm(upDir, { recursive: true, force: true });
116 });
117
118 test("every write path refuses it, and the origin is never asked", async () => {
119 const connected = await connectOrigin(app, alice, { host: fake.url, token: TOKEN, readOnly: true });
120 if (!connected.ok) throw new Error(`connect failed: ${JSON.stringify(connected.error)}`);
121 const id = connected.value.id;
122 expect(connected.value.readOnly).toBe(true);
123 expect(listWorkOrigins(app, alice).map((o) => o.id)).toEqual([id]);
124 expect(listWorkOrigins(app, bob)).toEqual([]);
125 expect(writesPaused(app, id)).toContain("read-only");
126
127 const job = startMirrorJob(app, alice, id, "octo/widgets", "widgets");
128 if (!job.ok) throw new Error("mirror refused");
129 const mirror = (await settled(job.value.id))!.repo!;
130
131 // Private by default, though the origin's repository is public.
132 expect(mirror.visibility).toBe("private");
133 expect(canRead(app.db, getRepoById(app.db, mirror.id)!, bob)).toBe(false);
134 expect(canRead(app.db, getRepoById(app.db, mirror.id)!, undefined)).toBe(false);
135 // And no setting makes it public.
136 const widened = await updateRepoSettings(app, alice, mirror, { visibility: "public" });
137 expect(widened.ok).toBe(false);
138 expect(getRepoById(app.db, mirror.id)!.visibility).toBe("private");
139
140 const writesBefore = state.requests.filter((r) => r.method !== "GET").length;
141 const issue = await openIssueThrough(app, alice, mirror, { title: "x" });
142 expect(!issue.ok && issue.error).toBe("origin_read_only");
143 const push = await originPush(app, alice, mirror);
144 expect(!push.ok && push.error).toBe("origin_read_only");
145 const carried = await carryBranchThrough(app, mirror, mirror, "topic", alice.id);
146 expect(!carried.ok && carried.error.message).toContain("read-only");
147 const pushed = await pushThrough(app, mirror, [{ ref: "refs/heads/main", oldOid: "0".repeat(40), newOid: "1".repeat(40) }], {}, alice.id);
148 expect(!pushed.ok && pushed.error.message).toContain("read-only");
149 const forked = await forkOrigin(app, alice, id, "octo/widgets");
150 expect(!forked.ok && forked.error).toBe("origin_read_only");
151 const proposed = await contribute(app, alice, {
152 originId: id,
153 fullName: "octo/widgets",
154 branch: "topic",
155 files: [{ path: "a.txt", content: "a" }],
156 });
157 expect(!proposed.ok && proposed.error).toBe("origin_read_only");
158 expect(await pushToMirrorTarget(app, mirror)).toEqual({ ok: true, value: 0 });
159
160 // The adapter itself refuses every request that is not a read.
161 const provider = providerForOrigin(app, listOrigins(app.db, alice.id)[0]!);
162 if (!provider.ok) throw new Error("no provider");
163 const p = provider.value;
164 const refused = [
165 await p.createIssue("octo/widgets", { title: "x", body: "" }),
166 await p.createComment("octo/widgets", 1, "x"),
167 await p.setState("octo/widgets", 1, "closed"),
168 await p.setLabels("octo/widgets", 1, ["a"]),
169 await p.createPull("octo/widgets", { title: "x", body: "", base: "main", head: "topic" }),
170 await p.submitReview("octo/widgets", 1, { state: "approved", body: "" }),
171 await p.forkRepo("octo/widgets"),
172 await p.archiveRepo("octo/widgets"),
173 ];
174 for (const r of refused) expect(!r.ok && r.error.error).toBe("forbidden");
175 // Nothing reached the origin.
176 expect(state.requests.filter((r) => r.method !== "GET").length).toBe(writesBefore);
177 });
178
179 test("the owner grants an app a read; nobody else can, and it can be withdrawn", async () => {
180 const [work] = listWorkOrigins(app, alice);
181 const appRepo = getRepoById(app.db, [...app.db.query<{ id: string }, []>("SELECT id FROM repo").all()][0]!.id)!;
182 expect(mayRead(app.db, work!.id, appRepo.id)).toBe(false);
183 // Bob does not own the origin: it does not exist for him.
184 expect(grantWorkRead(app, bob, work!.id, appRepo.id).ok).toBe(false);
185 // Alice may grant only an app she administers.
186 expect(grantWorkRead(app, alice, work!.id, appRepo.id).ok).toBe(true);
187 expect(mayRead(app.db, work!.id, appRepo.id)).toBe(true);
188 expect(revokeWorkRead(app, bob, work!.id, appRepo.id).ok).toBe(false);
189 expect(revokeWorkRead(app, alice, work!.id, appRepo.id).ok).toBe(true);
190 expect(mayRead(app.db, work!.id, appRepo.id)).toBe(false);
191 });
192
193 test("a failed fetch is one line, and the profile shows work (read-only) to its owner alone", async () => {
194 const [work] = listWorkOrigins(app, alice);
195 recordSync(app.db, work!.id, { at: "2026-11-09T10:00:00.000Z", error: "the origin refused the token\nstack stack stack" });
196 expect(fetchFailureLine(listWorkOrigins(app, alice)[0]!)).toBe("the origin refused the token");
197
198 const page = async (user: User | undefined): Promise<string> => {
199 const headers = new Headers();
200 if (user) headers.set("cookie", `forge_session=${createSession(app.db, user.id).token}`);
201 return (await fetch(`${servers.url}/alice`, { headers })).text();
202 };
203 const own = await page(alice);
204 expect(own).toContain("work (read-only)");
205 expect(own).toContain("the origin refused the token");
206 expect(own).not.toContain("stack stack");
207 expect(own).not.toContain(TOKEN);
208 for (const other of [await page(bob), await page(undefined)])
209 expect(other).not.toContain("work (read-only)");
210 });
211 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs