feat(knowledge): project safe domain access status

This commit is contained in:
冰朔 2026-08-10 03:23:34 +08:00
commit 7d33184822
2 changed files with 308 additions and 0 deletions

View file

@ -0,0 +1,199 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
import { domainManifestSigningBytes } from './domain-access.js';
import { DomainAccessOrchestrator } from './domain-access-orchestrator.js';
import { TrustedSignerSnapshotLoader } from './trusted-signer-snapshot.js';
const NOW = 1_786_291_200_000;
const DOMAIN_ID = 'DOM-FIFTH-0001';
const NODE_ID = 'LOCAL-001';
const COMMIT = 'a'.repeat(40);
const ANCHOR_URL = 'https://guanghulab.com/api/ai/v1/anchor';
const REGISTRY_URL = `https://guanghulab.com/code/bingshuo/guanghu-ice-heart/raw/commit/${COMMIT}/routing/trusted-domain-manifest-signers.json`;
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
function anchor() {
return {
schema: 'guanghu.public-navigation-anchor/v1',
anchor_id: 'GLW-PUBLIC-NAV-ANCHOR-001',
state: 'CURRENT_CANONICAL',
repository_id: 'REPO-012',
branch: 'main',
public_entry: ANCHOR_URL,
code_entry: 'https://guanghulab.com/code/bingshuo/guanghu-ice-heart',
maps: {
trusted_domain_manifest_signers: {
path: 'routing/trusted-domain-manifest-signers.json',
id: 'GH-AIOS-TRUSTED-DOMAIN-MANIFEST-SIGNERS-001',
version: '1.0.0',
},
},
navigation_source: {
anchor_id: 'GLW-PUBLIC-NAV-ANCHOR-001',
source_commit: COMMIT,
source_mode: 'REPO-012_MAIN_GIT_SNAPSHOT',
source_degraded: false,
},
};
}
function registry(signers: unknown[] = []) {
return {
registryId: 'GH-AIOS-TRUSTED-DOMAIN-MANIFEST-SIGNERS-001',
schema: 'gh-aios.trusted-domain-manifest-signers/v1',
signers,
state: 'CURRENT',
version: '1.0.0',
};
}
function activeSigner() {
return {
algorithm: 'Ed25519',
domainIds: [DOMAIN_ID],
publicKeyPem: publicKey.export({ format: 'pem', type: 'spki' }).toString(),
repositoryId: 'REPO-014',
signerId: 'GH-LIGHTHOUSE-001',
status: 'ACTIVE',
};
}
function loader(readRegistry: () => unknown = () => registry()) {
return new TrustedSignerSnapshotLoader({
async fetchJson(url) {
if (url === ANCHOR_URL) return anchor();
if (url === REGISTRY_URL) return readRegistry();
throw new Error('unexpected_url');
},
});
}
function validHandoff() {
const payload = {
domainId: DOMAIN_ID,
repositoryId: 'REPO-014',
schema: 'gh-aios.domain-manifest/v1',
signerId: 'GH-LIGHTHOUSE-001',
sourceCommit: 'b'.repeat(40),
} as const;
const bytes = domainManifestSigningBytes(payload);
const digest = createHash('sha256').update(bytes).digest('hex');
return {
connectionReceipt: {
connectionId: 'CONN-001',
domainId: DOMAIN_ID,
manifestDigest: digest,
nodeId: NODE_ID,
receiptId: 'RECEIPT-001',
state: 'online',
},
manifest: {
digest,
...payload,
signature: sign(null, bytes, privateKey).toString('base64'),
},
sessionCapability: {
capabilityId: 'CAP-001',
domainId: DOMAIN_ID,
expiresAt: NOW + 60_000,
nodeId: NODE_ID,
scopes: ['domain:enter'],
},
};
}
test('projects public trust health without asking for a handoff before login', async () => {
let handoffReads = 0;
const orchestrator = new DomainAccessOrchestrator(
loader(),
{ async read() { return { accountVerified: false, nodeId: '' }; } },
{ async read() { handoffReads += 1; return null; } },
);
const status = await orchestrator.domainAccess(DOMAIN_ID, NOW);
assert.equal(handoffReads, 0);
assert.equal(status.stage, 'login-required');
assert.equal(status.runtimeReady, false);
assert.equal(status.localWorkspaceAllowed, true);
assert.deepEqual(status.trustSource, {
status: 'CURRENT',
sourceCommit: COMMIT,
registryVersion: '1.0.0',
signerCount: 0,
});
});
test('an authenticated node without a verified handoff remains identity-only', async () => {
const orchestrator = new DomainAccessOrchestrator(
loader(),
{ async read() { return { accountVerified: true, nodeId: NODE_ID }; } },
{ async read() { return null; } },
);
const status = await orchestrator.domainAccess(DOMAIN_ID, NOW);
assert.equal(status.stage, 'identity-verified');
assert.equal(status.runtimeReady, false);
assert.ok(status.blockers.includes('verified_domain_manifest_missing'));
});
test('a loaded signer snapshot and verified handoff project runtime-ready', async () => {
const orchestrator = new DomainAccessOrchestrator(
loader(() => registry([activeSigner()])),
{ async read() { return { accountVerified: true, nodeId: NODE_ID }; } },
{ async read() {
return {
handoff: validHandoff(),
signerLookup: { repositoryId: 'REPO-014', signerId: 'GH-LIGHTHOUSE-001' },
};
} },
);
const status = await orchestrator.domainAccess(DOMAIN_ID, NOW);
assert.equal(status.stage, 'runtime-ready');
assert.equal(status.runtimeReady, true);
assert.deepEqual(status.blockers, []);
assert.equal(status.trustSource.status, 'CURRENT');
});
test('source and handoff failures are reduced to safe status without raw details', async () => {
const orchestrator = new DomainAccessOrchestrator(
new TrustedSignerSnapshotLoader({ async fetchJson() { throw new Error('secret source detail'); } }),
{ async read() { return { accountVerified: true, nodeId: NODE_ID }; } },
{ async read() { throw new Error('secret handoff detail'); } },
);
const status = await orchestrator.domainAccess(DOMAIN_ID, NOW);
assert.equal(status.stage, 'identity-verified');
assert.equal(status.runtimeReady, false);
assert.equal(status.trustSource.status, 'UNAVAILABLE');
assert.equal(status.trustSource.reason, 'SOURCE_UNAVAILABLE');
assert.equal(JSON.stringify(status).includes('secret'), false);
});
test('a last-known-good signer can project access while preserving degraded health', async () => {
let currentRegistry: unknown = registry([activeSigner()]);
const signerLoader = loader(() => currentRegistry);
await signerLoader.refresh();
currentRegistry = { ...registry([activeSigner()]), version: 'invalid' };
const orchestrator = new DomainAccessOrchestrator(
signerLoader,
{ async read() { return { accountVerified: true, nodeId: NODE_ID }; } },
{ async read() {
return {
handoff: validHandoff(),
signerLookup: { repositoryId: 'REPO-014', signerId: 'GH-LIGHTHOUSE-001' },
};
} },
);
const status = await orchestrator.domainAccess(DOMAIN_ID, NOW);
assert.equal(status.runtimeReady, true);
assert.equal(status.trustSource.status, 'DEGRADED_LAST_KNOWN_GOOD');
assert.equal(status.trustSource.reason, 'REGISTRY_INVALID');
});

View file

@ -0,0 +1,109 @@
import {
evaluateDomainAccess,
verifyDomainAccessHandoffFromSnapshot,
type DomainAccessEvidence,
type DomainAccessStatus,
} from './domain-access.js';
import {
TrustedSignerSnapshotLoader,
type TrustedSignerSnapshotReceipt,
} from './trusted-signer-snapshot.js';
const IDENTIFIER_PATTERN = /^[A-Z0-9][A-Z0-9._:-]{1,159}$/;
export interface DomainIdentityProjection {
accountVerified: boolean;
nodeId: string;
}
export interface DomainIdentitySource {
read(domainId: string): Promise<DomainIdentityProjection>;
}
export interface DomainRuntimeHandoffCandidate {
handoff: unknown;
signerLookup: {
repositoryId: string;
signerId: string;
};
}
export interface DomainRuntimeHandoffSource {
read(domainId: string, nodeId: string): Promise<DomainRuntimeHandoffCandidate | null>;
}
export interface DomainAccessProjection {
blockers: readonly string[];
domainId: string;
localWorkspaceAllowed: true;
nodeId: string;
runtimeReady: boolean;
stage: DomainAccessStatus['stage'];
trustSource: Readonly<TrustedSignerSnapshotReceipt>;
}
function safeIdentity(input: unknown): DomainIdentityProjection {
if (typeof input !== 'object' || input === null || Array.isArray(input)) {
return { accountVerified: false, nodeId: '' };
}
const candidate = input as Record<string, unknown>;
const nodeId = typeof candidate.nodeId === 'string' && IDENTIFIER_PATTERN.test(candidate.nodeId)
? candidate.nodeId
: '';
return {
accountVerified: candidate.accountVerified === true && Boolean(nodeId),
nodeId,
};
}
export class DomainAccessOrchestrator {
constructor(
private readonly signerSnapshots: TrustedSignerSnapshotLoader,
private readonly identities: DomainIdentitySource,
private readonly handoffs: DomainRuntimeHandoffSource,
) {}
async domainAccess(domainId: string, now = Date.now()): Promise<Readonly<DomainAccessProjection>> {
if (!IDENTIFIER_PATTERN.test(domainId)) throw new Error('domain_access_domain_invalid');
const [snapshot, identity] = await Promise.all([
this.signerSnapshots.refresh(),
this.identities.read(domainId).then(safeIdentity, () => safeIdentity(null)),
]);
const evidence: DomainAccessEvidence = {
accountVerified: identity.accountVerified,
domainId,
nodeId: identity.nodeId,
};
if (identity.accountVerified) {
let candidate: DomainRuntimeHandoffCandidate | null = null;
try {
candidate = await this.handoffs.read(domainId, identity.nodeId);
} catch {
candidate = null;
}
if (candidate) {
try {
const verified = verifyDomainAccessHandoffFromSnapshot(
candidate.handoff,
domainId,
identity.nodeId,
candidate.signerLookup,
snapshot,
now,
);
Object.assign(evidence, verified.handoff);
} catch {
// Untrusted or incomplete handoffs remain absent from the projection.
}
}
}
const status = evaluateDomainAccess(evidence, now);
return Object.freeze({
...status,
blockers: Object.freeze([...status.blockers]),
trustSource: snapshot.receipt,
});
}
}