@mosetta/services 0.0.0-stage → 0.0.10
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.
- package/LICENSE +21 -0
- package/package.json +33 -3
- package/src/brandSecretKey.ts +71 -0
- package/src/errors.ts +59 -0
- package/src/platformServices.ts +221 -0
- package/src/protocol.ts +11 -0
- package/src/protocolCodec.ts +259 -0
- package/src/protocolEntry.ts +4 -0
- package/src/protocolTypes.ts +170 -0
- package/src/publisherServiceInvocation.ts +296 -0
- package/src/serviceCompositionIo.ts +109 -0
- package/src/serviceConnectionClient.ts +184 -0
- package/src/serviceDefaultsCoordinator.ts +184 -0
- package/src/serviceHandshakeController.ts +257 -0
- package/src/serviceHost.ts +234 -0
- package/src/serviceHostCall.ts +239 -0
- package/src/serviceInstallationsIo.ts +126 -0
- package/src/serviceInvocation.ts +176 -0
- package/src/serviceManagementController.ts +203 -0
- package/src/serviceManagementIo.ts +166 -0
- package/src/serviceProxyClient.ts +71 -0
- package/src/serviceSecretsIo.ts +138 -0
- package/src/serviceStores.ts +214 -0
- package/src/serviceTechnicalIo.ts +272 -0
- package/src/services.ts +15 -0
- package/README.md +0 -3
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type { IHostCallbackIdentity } from '@mosetta/host-platform/host';
|
|
2
|
+
import { IdentityError } from '@mosetta/identity';
|
|
3
|
+
import type { IIdentityDelegatedAccess, IIdentityDelegationRequest, IIdentityRequestCaller } from '@mosetta/identity';
|
|
4
|
+
import { AccessPolicy, ProjectAccess } from '@mosetta/server-action/access';
|
|
5
|
+
import { HostContextCodec, IDENTITY_HEADER, SITE_HEADER } from '@mosetta/server-action/core';
|
|
6
|
+
import type { ICallerFetch } from '@mosetta/server-action/core';
|
|
7
|
+
import type { IExecutionTarget, IRequestExecution } from '@mosetta/server/factoryGate';
|
|
8
|
+
import type { IHostContext } from '@mosetta/server/storeCapability';
|
|
9
|
+
import {
|
|
10
|
+
INSTALLATIONS_PATH,
|
|
11
|
+
SERVICES_PATH,
|
|
12
|
+
ServiceDefaultsCoordinator,
|
|
13
|
+
ServiceHandshakeController,
|
|
14
|
+
ServiceManagementController,
|
|
15
|
+
ServiceProtocolCodec,
|
|
16
|
+
ServiceProxyClient,
|
|
17
|
+
} from './protocol';
|
|
18
|
+
import type { IServiceConnections, IServicesHost } from './protocol';
|
|
19
|
+
import type { IServiceInvocationProps } from './serviceHost';
|
|
20
|
+
import { ConsumerServiceInvocation } from './serviceInvocation';
|
|
21
|
+
import type { IServiceInvocationPort, TServiceRun } from './serviceInvocation';
|
|
22
|
+
|
|
23
|
+
/** Configuration for `serviceCallFor`. */
|
|
24
|
+
export interface IServiceCallConfig {
|
|
25
|
+
readonly projectId: string;
|
|
26
|
+
readonly origin: string;
|
|
27
|
+
readonly services: IServicesHost;
|
|
28
|
+
readonly clientIp?: (request: Request) => string | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Optional flags for a single invocation of the `serviceCallFor` handler. */
|
|
32
|
+
export interface IServiceCallOptions {
|
|
33
|
+
readonly defaultsBootstrap?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface IServiceDelegator {
|
|
37
|
+
delegate(selection: IIdentityDelegationRequest): Promise<IIdentityDelegatedAccess>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Options for `serviceConsumerOf`. */
|
|
41
|
+
export interface IServiceConsumerOptions {
|
|
42
|
+
readonly identity: IServiceDelegator;
|
|
43
|
+
readonly ctx: IHostContext | undefined;
|
|
44
|
+
readonly origin: string;
|
|
45
|
+
readonly projectId: string;
|
|
46
|
+
readonly connections: IServiceConnections;
|
|
47
|
+
readonly clientAddress?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Options for `serviceInstallRun`. */
|
|
51
|
+
export interface IServiceInstallRunOptions {
|
|
52
|
+
readonly run: TServiceRun;
|
|
53
|
+
readonly publisherOrigin: string;
|
|
54
|
+
readonly publisherId: string;
|
|
55
|
+
readonly resources?: (target: IExecutionTarget) => Promise<Pick<IRequestExecution, 'store' | 'secrets' | 'database'>>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type TServiceEntry = (options: { props: IServiceInvocationProps }) => ICallerFetch;
|
|
59
|
+
|
|
60
|
+
const JWT_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
61
|
+
const MAX_CREDENTIAL_LENGTH = 16_384;
|
|
62
|
+
const MAX_CLIENT_ADDRESS_LENGTH = 128;
|
|
63
|
+
|
|
64
|
+
export function serviceHostEntry(
|
|
65
|
+
ctx: IHostContext | undefined,
|
|
66
|
+
name: 'ServiceInvocation' | 'ServiceCallback',
|
|
67
|
+
): TServiceEntry | null {
|
|
68
|
+
const value = ctx?.exports?.[name];
|
|
69
|
+
return typeof value === 'function' ? value as TServiceEntry : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isInvalidClientAddress(address: string | undefined): boolean {
|
|
73
|
+
if (address === undefined) return false;
|
|
74
|
+
return !address || address.length > MAX_CLIENT_ADDRESS_LENGTH || /[\r\n]/.test(address);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Validates private entrypoint props before trusting credentials, expiry, or client address. */
|
|
78
|
+
export function checkServiceInvocationProps(props: IServiceInvocationProps): void {
|
|
79
|
+
if (
|
|
80
|
+
!props
|
|
81
|
+
|| typeof props.credential !== 'string'
|
|
82
|
+
|| props.credential.length > MAX_CREDENTIAL_LENGTH
|
|
83
|
+
|| !JWT_RE.test(props.credential)
|
|
84
|
+
|| !Number.isSafeInteger(props.expiresAtMs)
|
|
85
|
+
|| props.expiresAtMs <= Date.now()
|
|
86
|
+
|| isInvalidClientAddress(props.clientAddress)
|
|
87
|
+
) {
|
|
88
|
+
throw new IdentityError('INVALID_PASS');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Installed on a consumer event; Root delegate preserves the selected parent's current/frozen floor. */
|
|
93
|
+
export function serviceConsumerOf(options: IServiceConsumerOptions): IServiceInvocationPort | null {
|
|
94
|
+
const { identity, ctx, origin, projectId, connections, clientAddress } = options;
|
|
95
|
+
const invocation = serviceHostEntry(ctx, 'ServiceInvocation');
|
|
96
|
+
if (!invocation) return null;
|
|
97
|
+
return new ConsumerServiceInvocation({
|
|
98
|
+
consumerOrigin: origin,
|
|
99
|
+
consumerProjectId: projectId,
|
|
100
|
+
connections,
|
|
101
|
+
transport: {
|
|
102
|
+
dispatch: async (request, plan) => {
|
|
103
|
+
const child = await identity.delegate({ via: 'service:' + plan.installation, projects: [{ projectId }] });
|
|
104
|
+
const props: IServiceInvocationProps = {
|
|
105
|
+
plan,
|
|
106
|
+
credential: child.accessToken,
|
|
107
|
+
expiresAtMs: child.expiresAt * 1000,
|
|
108
|
+
...(clientAddress ? { clientAddress } : {}),
|
|
109
|
+
};
|
|
110
|
+
checkServiceInvocationProps(props);
|
|
111
|
+
return invocation({ props }).fetch(request);
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Only handleInstallations' verified technical handshake may call this closure, never public HTTP claims. */
|
|
118
|
+
export function serviceInstallRun(options: IServiceInstallRunOptions): (request: Request) => Promise<Response> {
|
|
119
|
+
const { run, publisherOrigin, publisherId, resources } = options;
|
|
120
|
+
return async (request) => {
|
|
121
|
+
const url = new URL(request.url);
|
|
122
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
123
|
+
if (url.origin !== publisherOrigin || !action || action.tile !== 'service' || action.action !== 'install' || request.method !== 'POST') {
|
|
124
|
+
throw new IdentityError('FORBIDDEN');
|
|
125
|
+
}
|
|
126
|
+
const body: unknown = await request.clone().json();
|
|
127
|
+
const consumer = body && typeof body === 'object' && 'consumer' in body ? body.consumer : null;
|
|
128
|
+
if (typeof consumer !== 'string' || new URL(consumer).origin !== consumer || consumer === publisherOrigin) {
|
|
129
|
+
throw new IdentityError('FORBIDDEN');
|
|
130
|
+
}
|
|
131
|
+
return run(request, async (selected, target) => {
|
|
132
|
+
if (target.moduleId !== action.fullId || target.endpoint) throw new IdentityError('FORBIDDEN');
|
|
133
|
+
const headers = new Headers(selected.headers);
|
|
134
|
+
for (const name of ['authorization', 'cookie', IDENTITY_HEADER, SITE_HEADER]) headers.delete(name);
|
|
135
|
+
headers.set(IDENTITY_HEADER, JSON.stringify({ via: 'service-install', site: consumer }));
|
|
136
|
+
headers.set(SITE_HEADER, HostContextCodec.encodeSite({ origin: consumer }));
|
|
137
|
+
return {
|
|
138
|
+
...(resources ? await resources(target) : {}),
|
|
139
|
+
request: ProjectAccess.withContext(new Request(selected, { headers }), { projectId: publisherId, scopeIds: [] }),
|
|
140
|
+
callerOutbound: null,
|
|
141
|
+
};
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function readValidCaller(
|
|
147
|
+
read: () => Promise<IIdentityRequestCaller | null>,
|
|
148
|
+
projectId: string,
|
|
149
|
+
): Promise<IIdentityRequestCaller> {
|
|
150
|
+
const caller = await read();
|
|
151
|
+
if (!caller) throw new IdentityError('INVALID_PASS');
|
|
152
|
+
if (caller.current.projectId !== projectId || !caller.current.may.length) {
|
|
153
|
+
throw new IdentityError('FORBIDDEN');
|
|
154
|
+
}
|
|
155
|
+
return caller;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function handleServicesEndpoint(input: {
|
|
159
|
+
readonly request: Request;
|
|
160
|
+
readonly url: URL;
|
|
161
|
+
readonly host: IServicesHost;
|
|
162
|
+
readonly identity: IHostCallbackIdentity;
|
|
163
|
+
readonly projectId: string;
|
|
164
|
+
readonly options?: IServiceCallOptions;
|
|
165
|
+
}): Promise<Response> {
|
|
166
|
+
const { request, url, host, identity, projectId, options } = input;
|
|
167
|
+
const readCaller = (): Promise<IIdentityRequestCaller | null> => (
|
|
168
|
+
options?.defaultsBootstrap && request.method === 'GET' && identity.caller
|
|
169
|
+
? identity.caller()
|
|
170
|
+
: identity.callbackCaller()
|
|
171
|
+
);
|
|
172
|
+
let caller = await readValidCaller(readCaller, projectId);
|
|
173
|
+
const session = {
|
|
174
|
+
sub: caller.person.id,
|
|
175
|
+
via: caller.person.via,
|
|
176
|
+
login: caller.person.login,
|
|
177
|
+
iat: caller.proof.issuedAt,
|
|
178
|
+
exp: caller.proof.expiresAt,
|
|
179
|
+
};
|
|
180
|
+
if (request.method === 'GET' && host.defaults?.length) {
|
|
181
|
+
await new ServiceDefaultsCoordinator(host).connectDefaults({ url, session, defaults: host.defaults });
|
|
182
|
+
if (!caller.current.cacheable || caller.current.expiresAtMs <= Date.now()) {
|
|
183
|
+
caller = await readValidCaller(readCaller, projectId);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (caller.proof.expiresAt * 1000 <= Date.now()) throw new IdentityError('INVALID_PASS');
|
|
187
|
+
if (caller.current.cacheable && caller.current.expiresAtMs <= Date.now()) throw new IdentityError('IDENTITY_UNAVAILABLE');
|
|
188
|
+
const mayChange = new AccessPolicy(projectId, caller.current.scopeIds).can(caller.current, 'services.manage', '*');
|
|
189
|
+
if (request.method === 'GET' || !mayChange) {
|
|
190
|
+
return new ServiceManagementController(host).handleServices(request, { session, owner: mayChange });
|
|
191
|
+
}
|
|
192
|
+
const mutation = await host.management?.human(request);
|
|
193
|
+
if (!mutation) throw new IdentityError('INVALID_CONFIG');
|
|
194
|
+
const response = await new ServiceManagementController({ ...mutation.host, runAction: host.runAction })
|
|
195
|
+
.handleServices(request, { session, owner: true });
|
|
196
|
+
if (response.ok) await mutation.finish();
|
|
197
|
+
else await mutation.finish().catch(() => undefined);
|
|
198
|
+
return response;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The host's one serviceCall attachment: public technical management or bounded private human handoff. */
|
|
202
|
+
export function serviceCallFor(
|
|
203
|
+
identity: IHostCallbackIdentity,
|
|
204
|
+
ctx: IHostContext | undefined,
|
|
205
|
+
config: IServiceCallConfig,
|
|
206
|
+
): (request: Request, run: TServiceRun, options?: IServiceCallOptions) => Promise<Response | null> {
|
|
207
|
+
return async (request, run, options) => {
|
|
208
|
+
const { services, projectId, origin } = config;
|
|
209
|
+
const url = new URL(request.url);
|
|
210
|
+
if (url.origin !== origin) throw new IdentityError('FORBIDDEN');
|
|
211
|
+
const host: IServicesHost = {
|
|
212
|
+
...services,
|
|
213
|
+
runAction: serviceInstallRun({ run, publisherOrigin: origin, publisherId: projectId }),
|
|
214
|
+
};
|
|
215
|
+
if (url.pathname === INSTALLATIONS_PATH || url.pathname.startsWith(INSTALLATIONS_PATH + '/')) {
|
|
216
|
+
return new ServiceHandshakeController(host).handleInstallations(request);
|
|
217
|
+
}
|
|
218
|
+
if (url.pathname === SERVICES_PATH) {
|
|
219
|
+
return handleServicesEndpoint({ request, url, host, identity, projectId, options });
|
|
220
|
+
}
|
|
221
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
222
|
+
const connection = action ? await services.connections?.get(action.brand) : null;
|
|
223
|
+
if (!connection) return null;
|
|
224
|
+
const ip = config.clientIp ? config.clientIp(request) : (request.headers.get('cf-connecting-ip') ?? undefined);
|
|
225
|
+
const invocation = serviceConsumerOf({
|
|
226
|
+
identity,
|
|
227
|
+
ctx,
|
|
228
|
+
origin,
|
|
229
|
+
projectId,
|
|
230
|
+
connections: services.connections!,
|
|
231
|
+
clientAddress: ip,
|
|
232
|
+
});
|
|
233
|
+
const proxy = new ServiceProxyClient({ ...host, invocation });
|
|
234
|
+
if (!invocation) return proxy.forward(request, connection);
|
|
235
|
+
await readValidCaller(() => identity.callbackCaller(), projectId);
|
|
236
|
+
const block = await ServiceProxyClient.probeServiceBlock(request, run);
|
|
237
|
+
return proxy.forward(request, connection, block);
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { IdentityError, ProjectCataloguePolicy } from '@mosetta/identity';
|
|
2
|
+
import { PROJECT_IO_SQL_NOW as RESOURCE_SQL_NOW } from '@mosetta/tenancy';
|
|
3
|
+
import type { IProjectIoLease, ISqlDatabase } from '@mosetta/tenancy';
|
|
4
|
+
import type { IInstallation, IInstallations } from './protocol';
|
|
5
|
+
|
|
6
|
+
/** Explicit private INTERNAL migration. Primary and business DATABASE never run this schema. */
|
|
7
|
+
export const SERVICE_IO_INTERNAL_MIGRATIONS = [{
|
|
8
|
+
name: 'root_service_io_0001',
|
|
9
|
+
sql: `
|
|
10
|
+
CREATE TABLE IF NOT EXISTS mosetta_installations(id TEXT PRIMARY KEY,key_hash TEXT NOT NULL,consumer TEXT NOT NULL,brand TEXT NOT NULL,version TEXT NOT NULL,grant_list TEXT NOT NULL,person TEXT,status TEXT NOT NULL,created_at TEXT NOT NULL);
|
|
11
|
+
CREATE TABLE root_service_io_receipts(operation_id TEXT PRIMARY KEY,installation_id TEXT NOT NULL,command_digest TEXT NOT NULL,command TEXT NOT NULL);
|
|
12
|
+
CREATE TABLE root_service_io_assert(required INTEGER NOT NULL);
|
|
13
|
+
`,
|
|
14
|
+
}];
|
|
15
|
+
|
|
16
|
+
export interface IServiceInternalIo {
|
|
17
|
+
/** One fresh primary claim per actual INTERNAL primitive; no frozen mayChange flag. */
|
|
18
|
+
step<T>(digest: string, send: (lease: IProjectIoLease) => Promise<T>): Promise<T>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface IInstallationRow {
|
|
22
|
+
readonly id: string;
|
|
23
|
+
readonly key_hash: string;
|
|
24
|
+
readonly consumer: string;
|
|
25
|
+
readonly brand: string;
|
|
26
|
+
readonly version: string;
|
|
27
|
+
readonly grant_list: string;
|
|
28
|
+
readonly person: string | null;
|
|
29
|
+
readonly status: string;
|
|
30
|
+
readonly created_at: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const ALLOWED_STATUSES = new Set(['active', 'revoked', 'removed']);
|
|
34
|
+
|
|
35
|
+
function decodeInstallation(row: IInstallationRow): IInstallation {
|
|
36
|
+
return {
|
|
37
|
+
id: row.id,
|
|
38
|
+
keyHash: row.key_hash,
|
|
39
|
+
consumer: row.consumer,
|
|
40
|
+
brand: row.brand,
|
|
41
|
+
version: row.version,
|
|
42
|
+
grant: JSON.parse(row.grant_list) as string[],
|
|
43
|
+
person: row.person === null ? null : JSON.parse(row.person) as IInstallation['person'],
|
|
44
|
+
status: row.status,
|
|
45
|
+
createdAt: row.created_at,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Event-local actual-project INTERNAL adapter; only the host's domain methods are exposed. */
|
|
50
|
+
export class GuardedServiceInstallations implements IInstallations {
|
|
51
|
+
private readonly observed = new Map<string, IInstallation>();
|
|
52
|
+
|
|
53
|
+
constructor(private readonly db: ISqlDatabase, private readonly io: IServiceInternalIo) {}
|
|
54
|
+
|
|
55
|
+
async byId(id: string): Promise<IInstallation | null> {
|
|
56
|
+
const row = await this.db.prepare('SELECT * FROM mosetta_installations WHERE id=?').bind(id).first<IInstallationRow>();
|
|
57
|
+
const found = row ? decodeInstallation(row) : null;
|
|
58
|
+
if (found) this.observed.set(id, found);
|
|
59
|
+
return found;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async list(): Promise<IInstallation[]> {
|
|
63
|
+
const { results } = await this.db
|
|
64
|
+
.prepare('SELECT * FROM mosetta_installations ORDER BY created_at DESC LIMIT 500')
|
|
65
|
+
.all<IInstallationRow>();
|
|
66
|
+
return results.map((row) => {
|
|
67
|
+
const found = decodeInstallation(row);
|
|
68
|
+
this.observed.set(found.id, found);
|
|
69
|
+
return found;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async create(input: IInstallation): Promise<void> {
|
|
74
|
+
const held = structuredClone(input);
|
|
75
|
+
const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.install', held]));
|
|
76
|
+
const operationId = crypto.randomUUID();
|
|
77
|
+
await this.io.step(digest, async (lease) => {
|
|
78
|
+
lease.checkpoint();
|
|
79
|
+
await this.db.batch([
|
|
80
|
+
this.db.prepare(
|
|
81
|
+
`INSERT INTO root_service_io_receipts(operation_id,installation_id,command_digest,command) SELECT ?,?,?,'create' WHERE ?>${RESOURCE_SQL_NOW} AND NOT EXISTS(SELECT 1 FROM mosetta_installations WHERE id=?)`,
|
|
82
|
+
).bind(operationId, held.id, digest, lease.deadlineMs, held.id),
|
|
83
|
+
this.db.prepare('INSERT INTO root_service_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
84
|
+
this.db.prepare(
|
|
85
|
+
`INSERT INTO mosetta_installations(id,key_hash,consumer,brand,version,grant_list,person,status,created_at) SELECT ?,?,?,?,?,?,?,?,? WHERE ?>${RESOURCE_SQL_NOW}`,
|
|
86
|
+
).bind(
|
|
87
|
+
held.id,
|
|
88
|
+
held.keyHash,
|
|
89
|
+
held.consumer,
|
|
90
|
+
held.brand,
|
|
91
|
+
held.version,
|
|
92
|
+
JSON.stringify(held.grant),
|
|
93
|
+
held.person === null ? null : JSON.stringify(held.person),
|
|
94
|
+
held.status,
|
|
95
|
+
held.createdAt,
|
|
96
|
+
lease.deadlineMs,
|
|
97
|
+
),
|
|
98
|
+
this.db.prepare('INSERT INTO root_service_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
99
|
+
]);
|
|
100
|
+
lease.checkpoint();
|
|
101
|
+
});
|
|
102
|
+
this.observed.set(held.id, held);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async setStatus(id: string, status: string): Promise<void> {
|
|
106
|
+
const held = this.observed.get(id) ?? await this.byId(id);
|
|
107
|
+
if (!held || !ALLOWED_STATUSES.has(status)) throw new IdentityError('FORBIDDEN');
|
|
108
|
+
const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.status', held, status]));
|
|
109
|
+
const operationId = crypto.randomUUID();
|
|
110
|
+
await this.io.step(digest, async (lease) => {
|
|
111
|
+
lease.checkpoint();
|
|
112
|
+
await this.db.batch([
|
|
113
|
+
this.db.prepare(
|
|
114
|
+
`INSERT INTO root_service_io_receipts(operation_id,installation_id,command_digest,command) SELECT ?,?,?,'status' WHERE ?>${RESOURCE_SQL_NOW} AND EXISTS(SELECT 1 FROM mosetta_installations WHERE id=? AND key_hash=? AND status=?)`,
|
|
115
|
+
).bind(operationId, id, digest, lease.deadlineMs, id, held.keyHash, held.status),
|
|
116
|
+
this.db.prepare('INSERT INTO root_service_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
117
|
+
this.db.prepare(
|
|
118
|
+
`UPDATE mosetta_installations SET status=? WHERE id=? AND key_hash=? AND status=? AND ?>${RESOURCE_SQL_NOW}`,
|
|
119
|
+
).bind(status, id, held.keyHash, held.status, lease.deadlineMs),
|
|
120
|
+
this.db.prepare('INSERT INTO root_service_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
121
|
+
]);
|
|
122
|
+
lease.checkpoint();
|
|
123
|
+
});
|
|
124
|
+
this.observed.set(id, { ...held, status });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// Architectural invariants for consumer-to-publisher service invocation:
|
|
2
|
+
// - Service palette calls ALWAYS proxy through the consumer host (browser never calls publisher
|
|
3
|
+
// directly -> no CORS required, and the connection key never leaves the consumer host).
|
|
4
|
+
// - Outgoing requests strip `authorization`, `cookie`, and all reserved internal headers via
|
|
5
|
+
// `stripServiceRequestHeaders()`; the consumer host mints a short-lived human delegation on the
|
|
6
|
+
// private dispatch transport instead of forwarding raw credentials.
|
|
7
|
+
// - Action handler code remains identical across local code mode and remote service mode.
|
|
8
|
+
import { IdentityError } from '@mosetta/identity';
|
|
9
|
+
import { ProjectAllowances, PROJECT_ACCESS_HEADER } from '@mosetta/server-action/access';
|
|
10
|
+
import {
|
|
11
|
+
BLOCK_GIVEN_HEADER,
|
|
12
|
+
BLOCK_HEADER,
|
|
13
|
+
BLOCK_ORIGIN_HEADER,
|
|
14
|
+
DRAFT_ACCESS_HEADER,
|
|
15
|
+
ENDPOINT_HEADER,
|
|
16
|
+
IDENTITY_HEADER,
|
|
17
|
+
PUBLISH_TARGET_HEADER,
|
|
18
|
+
SERVICE_CALL_HEADER,
|
|
19
|
+
SITE_HEADER,
|
|
20
|
+
fullServerTileId,
|
|
21
|
+
} from '@mosetta/server-action/core';
|
|
22
|
+
import type { ICallerFetch, ISiteCode } from '@mosetta/server-action/core';
|
|
23
|
+
import type { IExecutionTarget, IRequestExecution, TRequestExecution } from '@mosetta/server/factoryGate';
|
|
24
|
+
import type { IIdentityRequestCaller } from '@mosetta/identity';
|
|
25
|
+
import { ServiceProtocolCodec } from './protocol';
|
|
26
|
+
import type { IInstallations, IServiceConnection, IServiceConnections } from './protocol';
|
|
27
|
+
|
|
28
|
+
export { PublisherServiceInvocation } from './publisherServiceInvocation';
|
|
29
|
+
|
|
30
|
+
export type TServiceRun = (request: Request, executionOverride?: TRequestExecution) => Promise<Response>;
|
|
31
|
+
|
|
32
|
+
/** These are selectors, never human claims. The Root transport derives authority from its original pass. */
|
|
33
|
+
export interface IServiceSelection {
|
|
34
|
+
readonly brand: string;
|
|
35
|
+
readonly installation: string;
|
|
36
|
+
readonly publisher: string;
|
|
37
|
+
readonly block: string | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Stored only in a trusted event closure, never a public route or serialized module environment. */
|
|
41
|
+
export interface IServiceInvocationPort {
|
|
42
|
+
invoke(request: Request, selected: IServiceSelection): Promise<Response>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Data-only invocation bounds. Raw credentials remain in Root-owned WorkerEntrypoint props. */
|
|
46
|
+
export interface IServiceInvocationPlan {
|
|
47
|
+
readonly consumerOrigin: string;
|
|
48
|
+
readonly consumerProjectId: string;
|
|
49
|
+
readonly publisherOrigin: string;
|
|
50
|
+
readonly brand: string;
|
|
51
|
+
readonly version: string;
|
|
52
|
+
readonly installation: string;
|
|
53
|
+
readonly grant: readonly string[];
|
|
54
|
+
readonly block: string | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface IServiceDispatchTransport {
|
|
58
|
+
/** Mint a bounded delegated child from the selected parent, then dispatch through the private Fetcher. */
|
|
59
|
+
dispatch(request: Request, plan: IServiceInvocationPlan): Promise<Response>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface IServicePublisherPorts {
|
|
63
|
+
readonly installations: IInstallations;
|
|
64
|
+
/** Authoritative consumer connection reader through a trusted private port, evaluated on every operation. */
|
|
65
|
+
connection(): Promise<IServiceConnection | null>;
|
|
66
|
+
/** Real Root verification/current of the child; no HTTP metadata is accepted as this result. */
|
|
67
|
+
caller(): Promise<IIdentityRequestCaller>;
|
|
68
|
+
/** A native ctx.exports WorkerEntrypoint Fetcher, freshly bound to this invocation. */
|
|
69
|
+
callback(target: IExecutionTarget): Promise<ICallerFetch>;
|
|
70
|
+
contentAllowed?(): boolean;
|
|
71
|
+
/** The consumer's actual registry-bound code target, not a namespace supplied in an action body. */
|
|
72
|
+
code?(): Promise<(ISiteCode & { readonly projectId: string }) | null>;
|
|
73
|
+
/** Publisher resources remain distinct from consumer identity. Root owns their source/SRI policy. */
|
|
74
|
+
resources?(target: IExecutionTarget): Promise<Pick<IRequestExecution, 'store' | 'secrets' | 'database'>>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const STRIPPED_HEADERS = [
|
|
78
|
+
IDENTITY_HEADER,
|
|
79
|
+
PROJECT_ACCESS_HEADER,
|
|
80
|
+
SITE_HEADER,
|
|
81
|
+
SERVICE_CALL_HEADER,
|
|
82
|
+
BLOCK_GIVEN_HEADER,
|
|
83
|
+
BLOCK_HEADER,
|
|
84
|
+
BLOCK_ORIGIN_HEADER,
|
|
85
|
+
DRAFT_ACCESS_HEADER,
|
|
86
|
+
ENDPOINT_HEADER,
|
|
87
|
+
PUBLISH_TARGET_HEADER,
|
|
88
|
+
'x-mosetta-vouched',
|
|
89
|
+
'x-mosetta-service-person',
|
|
90
|
+
'x-mosetta-service-site',
|
|
91
|
+
'x-mosetta-service-code',
|
|
92
|
+
'x-mosetta-service-block',
|
|
93
|
+
];
|
|
94
|
+
|
|
95
|
+
/** Validates an origin string strictly (scheme + host + optional port, no credentials). */
|
|
96
|
+
export function assertValidServiceOrigin(raw: string): string {
|
|
97
|
+
try {
|
|
98
|
+
const url = new URL(raw);
|
|
99
|
+
if (url.origin === raw && !url.username && !url.password && ['https:', 'http:'].includes(url.protocol)) {
|
|
100
|
+
return raw;
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
// fallback: malformed origin string fails closed via IdentityError below
|
|
104
|
+
}
|
|
105
|
+
throw new IdentityError('INVALID_CONFIG');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Strips reserved internal and credential headers before forwarding across a service boundary. */
|
|
109
|
+
export function stripServiceRequestHeaders(request: Request): Request {
|
|
110
|
+
const headers = new Headers(request.headers);
|
|
111
|
+
for (const name of [...STRIPPED_HEADERS, 'authorization', 'cookie']) {
|
|
112
|
+
headers.delete(name);
|
|
113
|
+
}
|
|
114
|
+
return new Request(request, { headers, redirect: 'manual' });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Configuration for `ConsumerServiceInvocation`. */
|
|
118
|
+
export interface IConsumerServiceInvocationOptions {
|
|
119
|
+
readonly consumerOrigin: string;
|
|
120
|
+
readonly consumerProjectId: string;
|
|
121
|
+
readonly connections: IServiceConnections;
|
|
122
|
+
readonly transport: IServiceDispatchTransport;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Consumer-side connection selection is reread; no MSI key or human header enters the outgoing request. */
|
|
126
|
+
export class ConsumerServiceInvocation implements IServiceInvocationPort {
|
|
127
|
+
private readonly consumerOrigin: string;
|
|
128
|
+
|
|
129
|
+
private readonly consumerProjectId: string;
|
|
130
|
+
|
|
131
|
+
private readonly connections: IServiceConnections;
|
|
132
|
+
|
|
133
|
+
private readonly transport: IServiceDispatchTransport;
|
|
134
|
+
|
|
135
|
+
constructor(options: IConsumerServiceInvocationOptions) {
|
|
136
|
+
assertValidServiceOrigin(options.consumerOrigin);
|
|
137
|
+
if (!ProjectAllowances.isId(options.consumerProjectId)) throw new IdentityError('INVALID_CONFIG');
|
|
138
|
+
this.consumerOrigin = options.consumerOrigin;
|
|
139
|
+
this.consumerProjectId = options.consumerProjectId;
|
|
140
|
+
this.connections = options.connections;
|
|
141
|
+
this.transport = options.transport;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async invoke(request: Request, selected: IServiceSelection): Promise<Response> {
|
|
145
|
+
const current = await this.connections.get(selected.brand);
|
|
146
|
+
const url = new URL(request.url);
|
|
147
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
148
|
+
if (
|
|
149
|
+
!current
|
|
150
|
+
|| current.brand !== selected.brand
|
|
151
|
+
|| current.installation !== selected.installation
|
|
152
|
+
|| current.publisher !== selected.publisher
|
|
153
|
+
|| !action
|
|
154
|
+
|| action.brand !== current.brand
|
|
155
|
+
|| action.fullId !== fullServerTileId({ namespace: current.brand, name: action.tile, version: current.version })
|
|
156
|
+
|| url.origin !== this.consumerOrigin
|
|
157
|
+
) {
|
|
158
|
+
throw new IdentityError('FORBIDDEN');
|
|
159
|
+
}
|
|
160
|
+
assertValidServiceOrigin(current.publisher);
|
|
161
|
+
const target = new Request(
|
|
162
|
+
new URL(url.pathname + url.search, current.publisher),
|
|
163
|
+
stripServiceRequestHeaders(request),
|
|
164
|
+
);
|
|
165
|
+
return this.transport.dispatch(target, {
|
|
166
|
+
consumerOrigin: this.consumerOrigin,
|
|
167
|
+
consumerProjectId: this.consumerProjectId,
|
|
168
|
+
publisherOrigin: current.publisher,
|
|
169
|
+
brand: current.brand,
|
|
170
|
+
version: current.version,
|
|
171
|
+
installation: current.installation,
|
|
172
|
+
grant: [...current.grant],
|
|
173
|
+
block: selected.block,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|