Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

The brain owner's own remote credential can edit, append to and relabel private pages it reads (GST-2091)

garrytanabca1a3abe89
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index a0a17e2ca4..baf7bd889f 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -12,7 +12,7 @@ import { authorizedSlug, type Principal, type SqlEngine, type WriteAuthority, ty
import { authorizePageVisibility, excludesPrivateWritesAtAdmission } from './page-visibility.ts';
import { currentCallerAccess } from '../search/private-visibility.ts';
import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
-import { sameAttestedActor } from '../access/member-facts.ts';
+import { ownerSpeaksForItself, sameAttestedActor } from '../access/member-facts.ts';
import { perCallWriteSource, storedPerCallWriteSource } from '../access/attest-sources.ts';
import { pipelined, transactionMemo } from '../page-state/transactions.ts';
@@ -37,6 +37,8 @@ function liveDelegation(row: Record<string, unknown>, jobId: unknown): readonly
const key = jobNamespaceKey(jobId);
return mode === 'job' && listed === null && key !== undefined ? [`wiki/agents/${key}/*`] : [];
}
+/** GST-2091: the page writes the brain owner's own credential may make to a private page it reads. */
+const OWNER_PRIVATE_WRITES = new Set(['put_page', 'edit_page', 'append_page']);
function skillWrite(operation: string): boolean {
return ['put_skill', 'delete_skill', 'adopt_skillpack'].includes(operation);
}
@@ -85,6 +87,8 @@ export async function submissionAuthority(ctx: OperationContext, operation: stri
delegatedPrefixes: ctx.allowedSlugPrefixes?.length ? [...ctx.allowedSlugPrefixes]
: typeof ctx.subagentId === 'number' ? [`wiki/agents/${ctx.subagentId}/*`] : [] } : {}),
};
+ const owner = access?.remotePolicy?.ownerMember;
+ if (owner && OWNER_PRIVATE_WRITES.has(operation) && hasScope(a.scopes, 'write') && ownerSpeaksForItself(ctx)) a.ownerWrite = `member:${owner}`;
if (ctx.auth?.sourceId != null && ctx.auth.sourceId !== sourceId && !a.attestedSource) deny('The source is outside this writer grant.');
if (!prefixAllowed(a.slugPrefixes, slug)) deny('The target is outside this writer grant.');
await authorizeWrite(ctx.engine, a, operation, slug);
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 23da0cab27..dbb85fac07 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -38,6 +38,12 @@ export interface WriteAuthority {
* holding page, which is gbrain's own companion to it.
*/
heldFor?: string;
+ /**
+ * GST-2091: the brain owner (`member:<id>`) whose own credential, with write scope and speaking for itself, made this
+ * page write (put_page, edit_page or append_page; put_pages and page uploads store those). Preparation and publication
+ * lift the privacy part of the writer's read policy only while storedOwnerWrite still holds; member access always applies.
+ */
+ ownerWrite?: string;
databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'relative_root' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached' | 'entity_page_missing';
autoLinkTrusted?: boolean;
restrictedNamespace?: boolean;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7cb7d38d11..b914059562 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -38,7 +38,7 @@ import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import { authorizeWrite, slugDisclosable } from './authority.ts';
-import { remoteLabelsChecked, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
+import { remoteLabelsChecked, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders, storedOwnerWrite } from './page-visibility.ts';
import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from './file-claims.ts';
import { digest, sha256 } from './digest.ts';
import { replaceableFile } from '../facts/file-body-guard.ts';
@@ -1125,7 +1125,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// GST-2518: a lower-tier local write keeps the page's privacy labels it would widen (GST-2521: and the owner as a reader); its proposal carries the request.
const labelGuard = await privacyLabelGuard(engine, row, trust, snapshot?.page ?? null, storedTier, incoming);
let heldLabels: HeldPrivacyLabels | null = null;
- const defaultSourceWriter = row.operation === 'restore_page' || row.operation === 'revert_version' ? null : await defaultSourceMemberWriter(engine, row.authority), defaultSourceOwner = await defaultSourceWriterIsOwner(engine, defaultSourceWriter);
+ const defaultSourceWriter = row.operation === 'restore_page' || row.operation === 'revert_version' ? null : await defaultSourceMemberWriter(engine, row.authority), defaultSourceOwner = await defaultSourceWriterIsOwner(engine, defaultSourceWriter), ownerRewrite = row.operation === 'put_page' && await storedOwnerWrite(engine, row.authority);
// The apply diet: the publisher's locked read of row.slug is the import base, and one read after the
// last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).
const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;
@@ -1148,7 +1148,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
suppliedTrustMarker = page.frontmatter.trust_tier;
if (labelGuard) heldLabels = holdPrivacyLabels(page.frontmatter, snapshot?.page.frontmatter, labelGuard);
stampPageTrustMarker(row, page.frontmatter, trust, storedTier, snapshot?.page.frontmatter);
- defaultSourceWriterReaders(defaultSourceWriter, page.frontmatter, snapshot?.page, defaultSourceOwner);
+ defaultSourceWriterReaders(defaultSourceWriter, page.frontmatter, snapshot?.page, defaultSourceOwner, ownerRewrite);
if (privateRequest) assertPrivateRequestKept(row, page.frontmatter);
},
prepare: async value => { prepared = value; return value.result; },
diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.ts
index 23e0405fcd..2b3701382c 100644
--- a/src/core/persistence/page-visibility.ts
+++ b/src/core/persistence/page-visibility.ts
@@ -11,6 +11,7 @@ import { catalogueError } from '../error-catalogue.ts';
import { authorizedSlug, type SqlEngine, type WriteAuthority } from './model.ts';
import type { BrainEngine } from '../engine.ts';
import { noGrantFloorReads } from '../source-resolver.ts';
+import { hasScope } from '../scope.ts';
/** Publication uses fresh policy, independent of the read-side telemetry cache (read through the resolver). */
export async function excludesPrivateWrites(engine: SqlEngine, remote: boolean): Promise<boolean> {
@@ -54,21 +55,25 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writ
}
const anyLabelled = excludePrivate ? probe?.any_labelled ?? true : await anyLabelledOnlyMember(engine);
const labelled = anyLabelled && await writerLabelledOnly(engine, authority, await writerIdentities(engine, authority));
+ // GST-2091: the owner's own page write (storedOwnerWrite) is held to member access without the privacy part. It is
+ // judged only for a page the privacy part hides, so every other write costs no extra lookup.
+ let owner: boolean | undefined;
if (!labelled && excludePrivate) {
// Privacy is hidden whatever the policy says, and an empty identity is the strictest reading (an identity only
// opens a page that names readers or sits under a folder rule), so a page visible with none needs no policy read
// or member lookup.
probe ??= (await engine.executeRaw<{ identity_may_open: boolean | null }>(`SELECT (${hiddenSql}) AS identity_may_open`, [authority.sourceId, slug]))[0];
if (probe?.identity_may_open == null) return;
- if (!probe.identity_may_open) throw pageNotVisibleError();
+ if (!probe.identity_may_open && !(owner = await storedOwnerWrite(engine, authority))) throw pageNotVisibleError();
}
const policy = await readRemotePolicyNow(engine);
- const hidePrivate = (authority.excludePrivate ?? true) || !policy.privacyRelaxed;
+ const hidePrivate = excludePrivate || !policy.privacyRelaxed;
if (!hidePrivate && !policy.restricted && !labelled) return;
- const fragment = await writerReadPolicySql(engine, authority, 'pages', hidePrivate, policy.restricted);
- const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2
- AND NOT (${fragment}) LIMIT 1`, [authority.sourceId, slug]);
- if (rows.length) throw pageNotVisibleError();
+ const hiddenUnder = async (hide: boolean) => (await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2
+ AND NOT (${await writerReadPolicySql(engine, authority, 'pages', hide, policy.restricted)}) LIMIT 1`, [authority.sourceId, slug])).length > 0;
+ if (!await hiddenUnder(hidePrivate && owner !== true)) return;
+ if (hidePrivate && owner === undefined && await storedOwnerWrite(engine, authority) && !await hiddenUnder(false)) return;
+ throw pageNotVisibleError();
}
/**
@@ -288,24 +293,48 @@ export async function defaultSourceWriterIsOwner(engine: SqlEngine, writer: stri
* subagent and no slug fence, and the principal's member is the enabled owner now. A credential unbound, a member
* disabled or an owner changed after submission is not the owner here.
*/
-export async function storedOwnerSpeaksForItself(engine: SqlEngine, authority: WriteAuthority): Promise<boolean> {
+export async function storedOwnerSpeaksForItself(engine: SqlEngine, authority: WriteAuthority, member?: string): Promise<boolean> {
if (!authority.remote || authority.actingFor || authority.restrictedNamespace || authority.slugPrefixes != null) return false;
- return defaultSourceWriterIsOwner(engine, (await memberIdentityFor(engine, authority)).find(p => p.startsWith('member:')) ?? null);
+ const bound = (await memberIdentityFor(engine, authority)).find(p => p.startsWith('member:')) ?? null;
+ return (member === undefined || bound === member) && defaultSourceWriterIsOwner(engine, bound);
+}
+
+/**
+ * GST-2091: whether a stored page write is the brain owner's own (WriteAuthority.ownerWrite), judged live: it still holds
+ * write scope and storedOwnerSpeaksForItself still names the same owner member. Such a write reaches a private page the
+ * owner reads; readable_by and folder rules still apply to it, like to every other writer.
+ */
+export async function storedOwnerWrite(engine: SqlEngine, authority: WriteAuthority): Promise<boolean> {
+ return !!authority.ownerWrite && hasScope(authority.scopes, 'write') && await storedOwnerSpeaksForItself(engine, authority, authority.ownerWrite);
}
/**
* GST-2051: the readers a page written by a default-source member writer (defaultSourceMemberWriter) keeps when its content
* names none: the stored page's readers when it has them, else the writer alone for a page this write creates, unless
* the writer is the brain owner (GST-2059), whose new pages stay shared. An existing page with no readers stays as it
- * is. Only ever narrows: a page naming readers is left to the caller.
+ * is. Only ever narrows: a page naming readers is left to the caller. `ownerRewrite` (GST-2091): first keep the stored labels the
+ * owner's own whole-page rewrite leaves out (ownerWriteKeepsLabels).
*/
-export function defaultSourceWriterReaders(writer: string | null, frontmatter: Record<string, unknown>, stored: { frontmatter?: unknown; deleted_at?: unknown } | null | undefined, owner = false): void {
+export function defaultSourceWriterReaders(writer: string | null, frontmatter: Record<string, unknown>, stored: { frontmatter?: unknown; deleted_at?: unknown } | null | undefined, owner = false,
+ ownerRewrite = false): void {
+ if (ownerRewrite) ownerWriteKeepsLabels(frontmatter, stored);
if (!writer || hasReaders(frontmatter)) return;
const live = stored && stored.deleted_at == null ? stored : null;
if (live && hasReaders(live.frontmatter)) frontmatter.readable_by = (live.frontmatter as Record<string, unknown>).readable_by;
else if (!live && !owner) frontmatter.readable_by = [writer];
}
+/**
+ * GST-2091: a whole-page rewrite (put_page) by the brain owner's own credential (storedOwnerWrite) keeps the live stored
+ * page's visibility and readable_by when its content leaves them out; a value the content states replaces the stored one.
+ */
+function ownerWriteKeepsLabels(frontmatter: Record<string, unknown>, stored: { frontmatter?: unknown; deleted_at?: unknown } | null | undefined): void {
+ const live = stored && stored.deleted_at == null && typeof stored.frontmatter === 'object' && stored.frontmatter !== null ? stored.frontmatter as Record<string, unknown> : null;
+ if (!live) return;
+ if (!Object.prototype.hasOwnProperty.call(frontmatter, 'visibility') && live.visibility !== undefined) frontmatter.visibility = live.visibility;
+ if (!hasReaders(frontmatter) && hasReaders(live)) frontmatter.readable_by = live.readable_by;
+}
+
/** The one refusal a remote writer gets for a target it may not see; other visibility refusals reuse it verbatim. */
export function pageNotVisibleError() {
return opError('page_not_found', 'Page not found.', 'This page does not exist or is not visible to this connection, so nothing was written. Do not retry this slug as a create; ask the user whether the page exists and who can read it, or write to a different slug.');
diff --git a/src/core/persistence/upload-streamed.ts b/src/core/persistence/upload-streamed.ts
index 2fbf2443a5..02679a5d56 100644
--- a/src/core/persistence/upload-streamed.ts
+++ b/src/core/persistence/upload-streamed.ts
@@ -41,7 +41,7 @@ import { stagedUploadParts, stagedUploadWork, type StagingBodyRef } from './page
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import { assertPrivateRequestKept, privateRequestGuarded, readPrivateRequest } from './visibility-request.ts';
-import { assertLabelledOnlyCreate, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders } from './page-visibility.ts';
+import { assertLabelledOnlyCreate, defaultSourceMemberWriter, defaultSourceWriterIsOwner, defaultSourceWriterReaders, storedOwnerWrite } from './page-visibility.ts';
const text = (value: unknown) => (typeof value === 'string' ? value : null);
@@ -95,6 +95,7 @@ export async function prepareStreamedUpload(engine: BrainEngine, row: WriteReque
const storedTier = remote && snapshot ? await storedPageTier(engine, row.source_id, row.slug) : null;
const defaultSourceWriter = await defaultSourceMemberWriter(engine, row.authority);
const defaultSourceOwner = await defaultSourceWriterIsOwner(engine, defaultSourceWriter);
+ const ownerRewrite = await storedOwnerWrite(engine, row.authority);
let trust: WriteTrust | undefined;
const dir = await mkdtemp(join(tmpdir(), 'gbrain-upload-'));
let ready: StreamedPreparedImport | undefined;
@@ -122,7 +123,7 @@ export async function prepareStreamedUpload(engine: BrainEngine, row: WriteReque
stamp: (frontmatter: Record<string, unknown>) => {
keepStoredProvenance(frontmatter, snapshot?.page.frontmatter);
stampPageTrustMarker(row, frontmatter, trust, storedTier, snapshot?.page.frontmatter);
- defaultSourceWriterReaders(defaultSourceWriter, frontmatter, snapshot?.page, defaultSourceOwner);
+ defaultSourceWriterReaders(defaultSourceWriter, frontmatter, snapshot?.page, defaultSourceOwner, ownerRewrite);
},
} } : {}) },
coordinated: { snapshot, sha256: ref.sha256, slug: row.slug, prepare: async value => { ready = value; return value.result; },