@mosetta/services 0.0.0-stage → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ import { IdentityError } from '@mosetta/identity';
2
+ import { ProjectAllowances, PROJECT_ACCESS_HEADER } from '@mosetta/server-action/access';
3
+ import {
4
+ BLOCK_GIVEN_HEADER,
5
+ BLOCK_HEADER,
6
+ BLOCK_ORIGIN_HEADER,
7
+ DRAFT_ACCESS_HEADER,
8
+ ENDPOINT_HEADER,
9
+ IDENTITY_HEADER,
10
+ PUBLISH_TARGET_HEADER,
11
+ SERVICE_CALL_HEADER,
12
+ SITE_HEADER,
13
+ fullServerTileId,
14
+ } from '@mosetta/server-action/core';
15
+ import type { ICallerFetch, ISiteCode } from '@mosetta/server-action/core';
16
+ import type { IExecutionTarget, IRequestExecution, TRequestExecution } from '@mosetta/server/factoryGate';
17
+ import type { IIdentityRequestCaller } from '@mosetta/identity';
18
+ import { ServiceProtocolCodec } from './protocol';
19
+ import type { IInstallations, IServiceConnection, IServiceConnections } from './protocol';
20
+
21
+ export { PublisherServiceInvocation } from './publisherServiceInvocation';
22
+
23
+ export type TServiceRun = (request: Request, executionOverride?: TRequestExecution) => Promise<Response>;
24
+
25
+ /** These are selectors, never human claims. The Root transport derives authority from its original pass. */
26
+ export interface IServiceSelection {
27
+ readonly brand: string;
28
+ readonly installation: string;
29
+ readonly publisher: string;
30
+ readonly block: string | null;
31
+ }
32
+
33
+ /** Stored only in a trusted event closure, never a public route or serialized module environment. */
34
+ export interface IServiceInvocationPort {
35
+ invoke(request: Request, selected: IServiceSelection): Promise<Response>;
36
+ }
37
+
38
+ /** Data-only invocation bounds. Raw credentials remain in Root-owned WorkerEntrypoint props. */
39
+ export interface IServiceInvocationPlan {
40
+ readonly consumerOrigin: string;
41
+ readonly consumerProjectId: string;
42
+ readonly publisherOrigin: string;
43
+ readonly brand: string;
44
+ readonly version: string;
45
+ readonly installation: string;
46
+ readonly grant: readonly string[];
47
+ readonly block: string | null;
48
+ }
49
+
50
+ export interface IServiceDispatchTransport {
51
+ /** Mint a bounded delegated child from the selected parent, then dispatch through the private Fetcher. */
52
+ dispatch(request: Request, plan: IServiceInvocationPlan): Promise<Response>;
53
+ }
54
+
55
+ export interface IServicePublisherPorts {
56
+ readonly installations: IInstallations;
57
+ /** Authoritative consumer connection reader through a trusted private port, evaluated on every operation. */
58
+ connection(): Promise<IServiceConnection | null>;
59
+ /** Real Root verification/current of the child; no HTTP metadata is accepted as this result. */
60
+ caller(): Promise<IIdentityRequestCaller>;
61
+ /** A native ctx.exports WorkerEntrypoint Fetcher, freshly bound to this invocation. */
62
+ callback(target: IExecutionTarget): Promise<ICallerFetch>;
63
+ contentAllowed?(): boolean;
64
+ /** The consumer's actual registry-bound code target, not a namespace supplied in an action body. */
65
+ code?(): Promise<(ISiteCode & { readonly projectId: string }) | null>;
66
+ /** Publisher resources remain distinct from consumer identity. Root owns their source/SRI policy. */
67
+ resources?(target: IExecutionTarget): Promise<Pick<IRequestExecution, 'store' | 'secrets' | 'database'>>;
68
+ }
69
+
70
+ const STRIPPED_HEADERS = [
71
+ IDENTITY_HEADER,
72
+ PROJECT_ACCESS_HEADER,
73
+ SITE_HEADER,
74
+ SERVICE_CALL_HEADER,
75
+ BLOCK_GIVEN_HEADER,
76
+ BLOCK_HEADER,
77
+ BLOCK_ORIGIN_HEADER,
78
+ DRAFT_ACCESS_HEADER,
79
+ ENDPOINT_HEADER,
80
+ PUBLISH_TARGET_HEADER,
81
+ 'x-mosetta-vouched',
82
+ 'x-mosetta-service-person',
83
+ 'x-mosetta-service-site',
84
+ 'x-mosetta-service-code',
85
+ 'x-mosetta-service-block',
86
+ ];
87
+
88
+ /** Validates an origin string strictly (scheme + host + optional port, no credentials). */
89
+ export function assertValidServiceOrigin(raw: string): string {
90
+ try {
91
+ const url = new URL(raw);
92
+ if (url.origin === raw && !url.username && !url.password && ['https:', 'http:'].includes(url.protocol)) {
93
+ return raw;
94
+ }
95
+ } catch {
96
+ // fallback: malformed origin string fails closed via IdentityError below
97
+ }
98
+ throw new IdentityError('INVALID_CONFIG');
99
+ }
100
+
101
+ /** Strips reserved internal and credential headers before forwarding across a service boundary. */
102
+ export function stripServiceRequestHeaders(request: Request): Request {
103
+ const headers = new Headers(request.headers);
104
+ for (const name of [...STRIPPED_HEADERS, 'authorization', 'cookie']) {
105
+ headers.delete(name);
106
+ }
107
+ return new Request(request, { headers, redirect: 'manual' });
108
+ }
109
+
110
+ /** Configuration for `ConsumerServiceInvocation`. */
111
+ export interface IConsumerServiceInvocationOptions {
112
+ readonly consumerOrigin: string;
113
+ readonly consumerProjectId: string;
114
+ readonly connections: IServiceConnections;
115
+ readonly transport: IServiceDispatchTransport;
116
+ }
117
+
118
+ /** Consumer-side connection selection is reread; no MSI key or human header enters the outgoing request. */
119
+ export class ConsumerServiceInvocation implements IServiceInvocationPort {
120
+ private readonly consumerOrigin: string;
121
+
122
+ private readonly consumerProjectId: string;
123
+
124
+ private readonly connections: IServiceConnections;
125
+
126
+ private readonly transport: IServiceDispatchTransport;
127
+
128
+ constructor(options: IConsumerServiceInvocationOptions) {
129
+ assertValidServiceOrigin(options.consumerOrigin);
130
+ if (!ProjectAllowances.isId(options.consumerProjectId)) throw new IdentityError('INVALID_CONFIG');
131
+ this.consumerOrigin = options.consumerOrigin;
132
+ this.consumerProjectId = options.consumerProjectId;
133
+ this.connections = options.connections;
134
+ this.transport = options.transport;
135
+ }
136
+
137
+ async invoke(request: Request, selected: IServiceSelection): Promise<Response> {
138
+ const current = await this.connections.get(selected.brand);
139
+ const url = new URL(request.url);
140
+ const action = ServiceProtocolCodec.actionOfPath(url.pathname);
141
+ if (
142
+ !current
143
+ || current.brand !== selected.brand
144
+ || current.installation !== selected.installation
145
+ || current.publisher !== selected.publisher
146
+ || !action
147
+ || action.brand !== current.brand
148
+ || action.fullId !== fullServerTileId({ namespace: current.brand, name: action.tile, version: current.version })
149
+ || url.origin !== this.consumerOrigin
150
+ ) {
151
+ throw new IdentityError('FORBIDDEN');
152
+ }
153
+ assertValidServiceOrigin(current.publisher);
154
+ const target = new Request(
155
+ new URL(url.pathname + url.search, current.publisher),
156
+ stripServiceRequestHeaders(request),
157
+ );
158
+ return this.transport.dispatch(target, {
159
+ consumerOrigin: this.consumerOrigin,
160
+ consumerProjectId: this.consumerProjectId,
161
+ publisherOrigin: current.publisher,
162
+ brand: current.brand,
163
+ version: current.version,
164
+ installation: current.installation,
165
+ grant: [...current.grant],
166
+ block: selected.block,
167
+ });
168
+ }
169
+ }
@@ -0,0 +1,203 @@
1
+ import type { IServiceConnection } from '@mosetta/host-platform/host';
2
+ import type { ISession } from '@mosetta/host-platform/tokens';
3
+ import { ServiceProtocolCodec } from './protocolCodec';
4
+ import {
5
+ GRANT_MAX,
6
+ INSTALLATIONS_PATH,
7
+ LISTING_PATH,
8
+ REVOKED_STATUS,
9
+ } from './protocolTypes';
10
+ import type { IServicesHost } from './protocolTypes';
11
+ import { ServiceConnectionClient } from './serviceConnectionClient';
12
+
13
+ export type { IServiceConnectContext } from './serviceConnectionClient';
14
+
15
+ /** Caller authorization context for `ServiceManagementController.handleServices`. */
16
+ export interface IServiceManagementAuth {
17
+ readonly session: ISession;
18
+ readonly owner: boolean;
19
+ }
20
+
21
+ interface IConnectBody {
22
+ readonly publisher?: unknown;
23
+ readonly brand?: unknown;
24
+ readonly version?: unknown;
25
+ readonly grant?: unknown;
26
+ }
27
+
28
+ /**
29
+ * Handles `/__mosetta__/services` consumer & publisher management operations
30
+ * (listing, publisher offer discovery, connecting, disconnecting, and revoking).
31
+ */
32
+ export class ServiceManagementController {
33
+ constructor(private readonly host: IServicesHost) {}
34
+
35
+ async handleServices(request: Request, auth: IServiceManagementAuth): Promise<Response> {
36
+ const url = new URL(request.url);
37
+ if (url.searchParams.has('installations') || url.searchParams.has('installation')) {
38
+ return this.handleOwnInstallations(request, url, auth.owner);
39
+ }
40
+ if (!this.host.connections) {
41
+ return ServiceProtocolCodec.refusalResponse(501, 'NO_SERVICES', 'this host keeps no services');
42
+ }
43
+ if (request.method === 'GET') {
44
+ const asked = url.searchParams.get('publisher');
45
+ return asked !== null ? this.offeredBy(asked) : this.listServices(url, auth.owner);
46
+ }
47
+ if (!auth.owner) {
48
+ return ServiceProtocolCodec.refusalResponse(403, 'OWNER_ONLY', 'the site\'s owner connects and ends services');
49
+ }
50
+ if (request.method === 'DELETE') return this.disconnectService(url, auth.session);
51
+ if (request.method !== 'POST') return ServiceProtocolCodec.refusalResponse(405, 'METHOD');
52
+ return this.connectRequestedService(request, url, auth.session);
53
+ }
54
+
55
+ private async handleOwnInstallations(request: Request, url: URL, owner: boolean): Promise<Response> {
56
+ const installations = this.host.installations;
57
+ if (request.method === 'GET') {
58
+ const rows = installations ? (await installations.list()).map((item) => ServiceProtocolCodec.shownInstallation(item)) : [];
59
+ return ServiceProtocolCodec.jsonResponse(200, { installations: rows, mayChange: owner });
60
+ }
61
+ if (!owner) {
62
+ return ServiceProtocolCodec.refusalResponse(403, 'OWNER_ONLY', 'the site\'s owner stops and resumes serving a site');
63
+ }
64
+ if (!installations) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_INSTALLATION');
65
+ const found = await installations.byId(url.searchParams.get('installation') ?? '');
66
+ if (!found) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_INSTALLATION');
67
+ if (request.method === 'DELETE') {
68
+ if (found.status === 'active') await installations.setStatus(found.id, REVOKED_STATUS);
69
+ const nextStatus = found.status === 'active' ? REVOKED_STATUS : found.status;
70
+ return ServiceProtocolCodec.jsonResponse(200, {
71
+ ok: true,
72
+ installation: ServiceProtocolCodec.shownInstallation({ ...found, status: nextStatus }),
73
+ });
74
+ }
75
+ if (request.method === 'PUT') {
76
+ if (found.status !== REVOKED_STATUS) {
77
+ return ServiceProtocolCodec.refusalResponse(409, 'NOT_STOPPED', `the installation is ${found.status}`);
78
+ }
79
+ await installations.setStatus(found.id, 'active');
80
+ return ServiceProtocolCodec.jsonResponse(200, {
81
+ ok: true,
82
+ installation: ServiceProtocolCodec.shownInstallation({ ...found, status: 'active' }),
83
+ });
84
+ }
85
+ return ServiceProtocolCodec.refusalResponse(405, 'METHOD');
86
+ }
87
+
88
+ private async offeredBy(publisher: string): Promise<Response> {
89
+ if (!ServiceProtocolCodec.isValidOrigin(publisher)) {
90
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'publisher: a site\'s origin, https://host');
91
+ }
92
+ let listed: { services?: unknown } | null;
93
+ try {
94
+ const res = await this.host.fetch(`${publisher}${LISTING_PATH}`, { headers: { accept: 'application/json' } });
95
+ listed = res.ok ? await res.json() as { services?: unknown } : null;
96
+ } catch {
97
+ // fallback: network failure maps to a 502 PUBLISHER_UNREACHABLE response below
98
+ listed = null;
99
+ }
100
+ if (!listed) {
101
+ return ServiceProtocolCodec.refusalResponse(502, 'PUBLISHER_UNREACHABLE', `${publisher} did not say what it offers`);
102
+ }
103
+ return ServiceProtocolCodec.jsonResponse(200, { publisher, offered: ServiceProtocolCodec.offersIn(listed) });
104
+ }
105
+
106
+ private async stateAtPublisher(connection: IServiceConnection): Promise<string> {
107
+ try {
108
+ const res = await this.host.fetch(`${connection.publisher}${INSTALLATIONS_PATH}`, {
109
+ redirect: 'manual',
110
+ headers: { accept: 'application/json', authorization: `Bearer ${connection.key}` },
111
+ });
112
+ if (res.status === 401) {
113
+ await res.body?.cancel();
114
+ return 'unknown';
115
+ }
116
+ const said = res.ok ? await res.json().catch(() => null) as { status?: unknown } | null : null;
117
+ if (!res.ok) await res.body?.cancel();
118
+ return typeof said?.status === 'string' ? said.status.slice(0, 40) : 'unreachable';
119
+ } catch {
120
+ // fallback: unreachable publisher reports literal 'unreachable' status in health check
121
+ return 'unreachable';
122
+ }
123
+ }
124
+
125
+ private async listServices(url: URL, owner: boolean): Promise<Response> {
126
+ const connections = this.host.connections!;
127
+ const [list, declined] = await Promise.all([connections.list(), connections.declined()]);
128
+ const states = url.searchParams.has('check')
129
+ ? await Promise.all(list.map((connection) => this.stateAtPublisher(connection)))
130
+ : null;
131
+ const defaults = this.host.defaults ?? [];
132
+ return ServiceProtocolCodec.jsonResponse(200, {
133
+ services: list.map(({ key: _key, ...shown }, index) => ({
134
+ ...shown,
135
+ ...(states ? { state: states[index] } : {}),
136
+ ...(defaults.some((item) => item.brand === shown.brand && item.publisher === shown.publisher) ? { byDefault: true } : {}),
137
+ })),
138
+ defaults: defaults.filter((item) => item.publisher !== url.origin).map((item) => ({
139
+ publisher: item.publisher,
140
+ brand: item.brand,
141
+ connected: list.some((conn) => conn.brand === item.brand && conn.publisher === item.publisher),
142
+ declined: declined.has(item.brand),
143
+ })),
144
+ mayChange: owner,
145
+ });
146
+ }
147
+
148
+ private async disconnectService(url: URL, session: ISession): Promise<Response> {
149
+ const connections = this.host.connections!;
150
+ const brand = url.searchParams.get('brand') ?? '';
151
+ const connection = await connections.get(brand);
152
+ if (!connection) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_SERVICE');
153
+ await this.host.fetch(`${connection.publisher}${INSTALLATIONS_PATH}`, {
154
+ method: 'DELETE',
155
+ redirect: 'manual',
156
+ headers: { authorization: `Bearer ${connection.key}` },
157
+ })
158
+ .then((res) => res.body?.cancel())
159
+ .catch((error: unknown) => console.warn(`services: ${connection.publisher} was not told ${brand} ended`, error));
160
+ await connections.remove(brand);
161
+ if ((this.host.defaults ?? []).some((item) => item.brand === brand)) {
162
+ await connections.decline(brand, session.login);
163
+ }
164
+ await this.host.composition?.detach(brand)
165
+ .catch((error: unknown) => console.warn(`services: ${brand} stayed in the site's composition`, error));
166
+ return ServiceProtocolCodec.jsonResponse(200, { ok: true, brand });
167
+ }
168
+
169
+ private async connectRequestedService(request: Request, url: URL, session: ISession): Promise<Response> {
170
+ if (!this.host.secret) return ServiceProtocolCodec.refusalResponse(501, 'NO_SESSION_KEY');
171
+ let body: IConnectBody;
172
+ try {
173
+ body = await request.json() as IConnectBody;
174
+ } catch {
175
+ // fallback: malformed JSON payload produces a 400 refusal
176
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'a JSON body: {publisher, brand, version, grant}');
177
+ }
178
+ const grant = ServiceProtocolCodec.grantOf(body.grant ?? []);
179
+ if (!ServiceProtocolCodec.isValidOrigin(body.publisher)) {
180
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'publisher: the publishing site\'s origin, https://host');
181
+ }
182
+ if (!ServiceProtocolCodec.isValidBrand(body.brand)) {
183
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'brand: the palette\'s brand');
184
+ }
185
+ if (!ServiceProtocolCodec.isValidVersion(body.version)) {
186
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'version: the palette\'s released version, X.Y.Z');
187
+ }
188
+ if (!grant) {
189
+ return ServiceProtocolCodec.refusalResponse(
190
+ 400,
191
+ 'BAD_REQUEST',
192
+ `grant: up to ${GRANT_MAX} palettes or palette/tile of this site the service may call`,
193
+ );
194
+ }
195
+ if (body.publisher === url.origin) {
196
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'a site takes its own palettes as code, not as a service');
197
+ }
198
+ return new ServiceConnectionClient(this.host).connectService(
199
+ { publisher: body.publisher, brand: body.brand, version: body.version, grant },
200
+ { url, session },
201
+ );
202
+ }
203
+ }
@@ -0,0 +1,166 @@
1
+ import { FixedCredentialProjectAuthority, rootResourceRuntime } from '@mosetta/host-platform/authorities';
2
+ import type { IRootResourceRuntimeConfig } from '@mosetta/host-platform/authorities';
3
+ import type { IHostInvocationIdentity } from '@mosetta/host-platform/bridges';
4
+ import { IdentityError, IdentitySecrets, ProjectCataloguePolicy } from '@mosetta/identity';
5
+ import type { ProjectSecrets } from '@mosetta/server/secrets';
6
+ import { SqlProjectIo } from '@mosetta/tenancy';
7
+ import type { IProjectIoOperation, IProjectIoTarget, IProjectRecord, ISqlDatabase } from '@mosetta/tenancy';
8
+ import { SealedServiceConnections } from './protocol';
9
+ import type {
10
+ IDefaultService,
11
+ IServiceConnections,
12
+ IServiceManagementPort,
13
+ IServiceMutationSession,
14
+ IServicesHost,
15
+ } from './protocol';
16
+ import { GuardedServiceComposition } from './serviceCompositionIo';
17
+ import { GuardedServiceInstallations } from './serviceInstallationsIo';
18
+ import { GuardedServiceSecrets } from './serviceSecretsIo';
19
+
20
+ export interface IRootServiceIoConfig extends IRootResourceRuntimeConfig {
21
+ readonly projectId: string;
22
+ readonly secrets: ProjectSecrets;
23
+ readonly internal: ISqlDatabase;
24
+ readonly host: IServicesHost;
25
+ publisher(origin: string): Promise<IProjectRecord | null>;
26
+ }
27
+
28
+ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
29
+ const BODYLESS_STATUSES = new Set([204, 205, 304]);
30
+
31
+ async function sha256Hex(payload: BufferSource): Promise<string> {
32
+ const digest = await crypto.subtle.digest('SHA-256', payload);
33
+ return [...new Uint8Array(digest)].map((one) => one.toString(16).padStart(2, '0')).join('');
34
+ }
35
+
36
+ function buildGuardedConnections(held: IServiceConnections, wanted?: IDefaultService): IServiceConnections {
37
+ if (!wanted) return held;
38
+ return {
39
+ list: () => held.list(),
40
+ get: (brand) => held.get(brand),
41
+ declined: () => held.declined(),
42
+ put: (connection) => {
43
+ if (connection.brand !== wanted.brand || connection.publisher !== wanted.publisher) {
44
+ throw new IdentityError('FORBIDDEN');
45
+ }
46
+ return held.put(connection);
47
+ },
48
+ remove: () => Promise.reject(new IdentityError('FORBIDDEN')),
49
+ decline: () => Promise.reject(new IdentityError('FORBIDDEN')),
50
+ };
51
+ }
52
+
53
+ function buildGuardedFetch(baseFetch: typeof fetch, executor: SqlProjectIo, handle: object): typeof fetch {
54
+ return async (input, init) => {
55
+ const prepared = new Request(input, init);
56
+ if (!MUTATING_METHODS.has(prepared.method)) return baseFetch(prepared);
57
+ const bytes = await prepared.clone().arrayBuffer();
58
+ const bodyHash = [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))];
59
+ const digest = await ProjectCataloguePolicy.hash(
60
+ JSON.stringify([prepared.url, prepared.method, [...prepared.headers], bodyHash]),
61
+ );
62
+ return executor.step(handle, crypto.randomUUID(), digest, async (checkpoint) => {
63
+ checkpoint();
64
+ const response = await baseFetch(prepared);
65
+ const body = await response.arrayBuffer();
66
+ if (response.status >= 500 || (response.status >= 300 && response.status < 400)) {
67
+ throw new IdentityError('IDENTITY_UNAVAILABLE');
68
+ }
69
+ return {
70
+ confirmed: true,
71
+ status: response.status,
72
+ value: new Response(BODYLESS_STATUSES.has(response.status) ? null : body, response),
73
+ };
74
+ });
75
+ };
76
+ }
77
+
78
+ /** Selected pass stays in this event. Root config/defaults cannot come from a public body. */
79
+ export function serviceManagementOf(identity: IHostInvocationIdentity, config: IRootServiceIoConfig): IServiceManagementPort {
80
+ let captured: IProjectIoTarget | null = null;
81
+ const open = async (request: Request | null, wanted?: IDefaultService): Promise<IServiceMutationSession> => {
82
+ if (wanted && !(config.host.defaults ?? []).some((one) => one.brand === wanted.brand && one.publisher === wanted.publisher)) {
83
+ throw new IdentityError('FORBIDDEN');
84
+ }
85
+ const payload = request
86
+ ? new Uint8Array(await request.clone().arrayBuffer())
87
+ : new TextEncoder().encode(JSON.stringify(wanted));
88
+ const payloadDigest = await sha256Hex(payload);
89
+ let mutation: IServiceMutationSession | null = null;
90
+ const port = await identity.bindInvocation(async (selected) => {
91
+ const runtime = await rootResourceRuntime(config, config.projectId, selected.credential);
92
+ if (runtime.source.project.ready !== true) throw new IdentityError('FORBIDDEN');
93
+ const permission = wanted ? 'services.defaults' : 'services.manage';
94
+ const authority = new FixedCredentialProjectAuthority(selected.credential, config.projectId, permission, config.verifier, runtime.current);
95
+ const check = await authority.read(captured ?? undefined);
96
+ const target: IProjectIoTarget = {
97
+ projectId: config.projectId,
98
+ name: 'services',
99
+ sourceKey: check.catalogue.sourceKey,
100
+ sourceGeneration: check.catalogue.sourceGeneration,
101
+ providerGeneration: await ProjectCataloguePolicy.hash(
102
+ JSON.stringify(['root-service-internal-v1', config.projectId, check.catalogue.sourceKey]),
103
+ ),
104
+ };
105
+ if (captured && JSON.stringify(captured) !== JSON.stringify(target)) throw new IdentityError('FORBIDDEN');
106
+ captured = Object.freeze(target);
107
+ const operation: IProjectIoOperation = {
108
+ id: crypto.randomUUID(),
109
+ nonce: crypto.randomUUID(),
110
+ capability: IdentitySecrets.random(),
111
+ target,
112
+ permission,
113
+ payloadDigest,
114
+ credentialKey: await IdentitySecrets.hash(selected.credential),
115
+ originalProof: selected.proof,
116
+ };
117
+ const executor = new SqlProjectIo(config.database, () => authority.read(target));
118
+ const handle = await executor.open(operation);
119
+ const defaults = wanted ? new Set([`SERVICE_${wanted.brand.toUpperCase().replace(/-/g, '_')}`]) : undefined;
120
+ const secrets = config.secrets.withStore(
121
+ (store) => new GuardedServiceSecrets({
122
+ db: config.database,
123
+ underlying: store,
124
+ operation,
125
+ executor,
126
+ handle,
127
+ defaults,
128
+ }),
129
+ );
130
+ const connections = buildGuardedConnections(
131
+ new SealedServiceConnections({ values: secrets, projectId: config.projectId, now: Date.now, cacheMs: 0 }),
132
+ wanted,
133
+ );
134
+ const installations = new GuardedServiceInstallations(config.internal, {
135
+ step: (digest, send) => executor.step(handle, crypto.randomUUID(), digest, async (checkpoint, deadlineMs) => {
136
+ const value = await send({ checkpoint, deadlineMs });
137
+ return { confirmed: true, status: 204, value };
138
+ }),
139
+ });
140
+ const composition = new GuardedServiceComposition({
141
+ db: config.database,
142
+ operation,
143
+ executor,
144
+ handle,
145
+ publisher: config.publisher,
146
+ transitioned: (previous, next) => {
147
+ if (!captured || captured.sourceGeneration !== previous) throw new IdentityError('FORBIDDEN');
148
+ captured = Object.freeze({ ...captured, sourceGeneration: next });
149
+ },
150
+ defaults: wanted ? new Set([`${wanted.brand}\n${wanted.publisher}`]) : undefined,
151
+ });
152
+ const guardedFetch = buildGuardedFetch(config.host.fetch, executor, handle);
153
+ mutation = {
154
+ host: { ...config.host, management: undefined, connections, installations, composition, fetch: guardedFetch },
155
+ finish: () => executor.finish(handle),
156
+ };
157
+ return { fetch: () => Promise.resolve(new Response(null, { status: 204 })) };
158
+ }, wanted ? { allowEditNavigation: true } : undefined);
159
+ if (!port || !mutation) throw new IdentityError('INVALID_PASS');
160
+ return mutation;
161
+ };
162
+ return {
163
+ human: (request) => open(request),
164
+ defaults: (wanted) => open(null, wanted),
165
+ };
166
+ }
@@ -0,0 +1,71 @@
1
+ import { Errors } from '@mosetta/core';
2
+ import type { IServiceConnection } from '@mosetta/host-platform/host';
3
+ import {
4
+ BLOCK_GIVEN_HEADER,
5
+ BLOCK_HEADER,
6
+ BLOCK_ORIGIN_HEADER,
7
+ SERVICE_CALL_HEADER,
8
+ } from '@mosetta/server-action/core';
9
+ import { ServiceProtocolCodec } from './protocolCodec';
10
+ import { SERVICE_BLOCK_MAX } from './protocolTypes';
11
+ import type { IServicesHost } from './protocolTypes';
12
+
13
+ /**
14
+ * Consumer-side proxy client that probes block context and forwards human
15
+ * server-action calls exclusively over the trusted private invocation bridge.
16
+ */
17
+ export class ServiceProxyClient {
18
+ constructor(private readonly host: IServicesHost) {}
19
+
20
+ /**
21
+ * Probes the local runner (`SERVICE_CALL_HEADER`) for the published block context
22
+ * of an incoming action call, or returns `null` when unavailable.
23
+ */
24
+ static async probeServiceBlock(
25
+ request: Request,
26
+ ask: (probe: Request) => Promise<Response>,
27
+ ): Promise<string | null> {
28
+ if (!request.headers.has(BLOCK_ORIGIN_HEADER)) return null;
29
+ const headers = new Headers(request.headers);
30
+ headers.delete(BLOCK_GIVEN_HEADER);
31
+ headers.delete('content-length');
32
+ headers.set(SERVICE_CALL_HEADER, '1');
33
+ try {
34
+ const answer = await ask(new Request(request.url, { method: 'POST', headers }));
35
+ await answer.body?.cancel();
36
+ return answer.headers.has(SERVICE_CALL_HEADER) ? answer.headers.get(BLOCK_HEADER) : null;
37
+ } catch (caught) {
38
+ // fallback: block probe failure degrades to null context rather than blocking the service call
39
+ console.warn('services: the calling block was not read', Errors.toError(caught));
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /** Forwards a human service action call through the private invocation bridge. */
45
+ async forward(
46
+ request: Request,
47
+ connection: IServiceConnection,
48
+ block: string | null = null,
49
+ ): Promise<Response> {
50
+ const action = ServiceProtocolCodec.actionOfPath(new URL(request.url).pathname);
51
+ if (!action || action.brand !== connection.brand) {
52
+ return ServiceProtocolCodec.refusalResponse(403, 'NOT_THIS_PALETTE');
53
+ }
54
+ if (!this.host.invocation) {
55
+ return ServiceProtocolCodec.refusalResponse(
56
+ 501,
57
+ 'PRIVATE_SERVICE_UNAVAILABLE',
58
+ 'Human service calls require a trusted same-installation bridge.',
59
+ );
60
+ }
61
+ const answer = await this.host.invocation.invoke(request, {
62
+ brand: connection.brand,
63
+ installation: connection.installation,
64
+ publisher: connection.publisher,
65
+ block: block && block.length <= SERVICE_BLOCK_MAX ? block : null,
66
+ });
67
+ const back = new Response(answer.body, answer);
68
+ back.headers.delete('set-cookie');
69
+ return back;
70
+ }
71
+ }