@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.
- package/LICENSE +21 -0
- package/package.json +33 -3
- package/src/errors.ts +59 -0
- package/src/platformServices.ts +221 -0
- package/src/protocol.ts +11 -0
- package/src/protocolCodec.ts +236 -0
- package/src/protocolEntry.ts +4 -0
- package/src/protocolTypes.ts +170 -0
- package/src/publisherServiceInvocation.ts +286 -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 +169 -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 +8 -0
- package/README.md +0 -3
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { identityConsumerOf } from '@mosetta/auth-service/consumer';
|
|
2
|
+
import type { IIdentityConsumerEnv } from '@mosetta/auth-service/consumer';
|
|
3
|
+
import { AppError, ErrorGate } from '@mosetta/core';
|
|
4
|
+
import type { IRootSourceAdmission, IRootSourcePolicies, IRootSourcePolicyPort } from '@mosetta/host-platform/bridges';
|
|
5
|
+
import { callerOutboundRequest, hostCallbackDestinations } from '@mosetta/host-platform/host';
|
|
6
|
+
import { IdentityError } from '@mosetta/identity';
|
|
7
|
+
import type { IIdentityRequestCaller } from '@mosetta/identity';
|
|
8
|
+
import type { ISiteCode } from '@mosetta/server-action/core';
|
|
9
|
+
import type { IExecutionTarget, IRequestExecution } from '@mosetta/server/factoryGate';
|
|
10
|
+
import type { IHostContext } from '@mosetta/server/storeCapability';
|
|
11
|
+
import type { IProjectRecord, IProjectRegistry } from '@mosetta/tenancy';
|
|
12
|
+
import { ExternalServiceUnavailableError } from './errors';
|
|
13
|
+
import type { IInstallations, IServiceConnections } from './protocol';
|
|
14
|
+
import { checkServiceInvocationProps, serviceHostEntry } from './serviceHostCall';
|
|
15
|
+
import { PublisherServiceInvocation } from './serviceInvocation';
|
|
16
|
+
import type { IServiceInvocationPlan, TServiceRun } from './serviceInvocation';
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
checkServiceInvocationProps,
|
|
20
|
+
serviceCallFor,
|
|
21
|
+
serviceConsumerOf,
|
|
22
|
+
serviceInstallRun,
|
|
23
|
+
} from './serviceHostCall';
|
|
24
|
+
export type {
|
|
25
|
+
IServiceCallConfig,
|
|
26
|
+
IServiceCallOptions,
|
|
27
|
+
IServiceConsumerOptions,
|
|
28
|
+
IServiceDelegator,
|
|
29
|
+
IServiceInstallRunOptions,
|
|
30
|
+
} from './serviceHostCall';
|
|
31
|
+
|
|
32
|
+
/** Server-private native entrypoint props. Only the delegated child crosses this boundary. */
|
|
33
|
+
export interface IServiceInvocationProps {
|
|
34
|
+
readonly plan: IServiceInvocationPlan;
|
|
35
|
+
readonly credential: string;
|
|
36
|
+
readonly expiresAtMs: number;
|
|
37
|
+
readonly clientAddress?: string;
|
|
38
|
+
readonly callbackTarget?: IExecutionTarget;
|
|
39
|
+
readonly content?: IRootSourceAdmission;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Built from the current entrypoint event's env. No binding or transport belongs to warm config. */
|
|
43
|
+
export interface IServiceHostRuntime {
|
|
44
|
+
readonly sourcePolicies?: IRootSourcePolicies;
|
|
45
|
+
readonly contentSourcePolicy?: Pick<IRootSourcePolicyPort, 'bind'>;
|
|
46
|
+
readonly registry: Pick<IProjectRegistry, 'byId' | 'byNamespace' | 'palette'>;
|
|
47
|
+
readonly apiOrigin: string | null;
|
|
48
|
+
/** Resolve a canonical installation origin through the actual registry, never a body projectId. */
|
|
49
|
+
project(origin: string): Promise<IProjectRecord | null>;
|
|
50
|
+
origin(project: IProjectRecord): string;
|
|
51
|
+
connections(consumer: IProjectRecord): IServiceConnections;
|
|
52
|
+
installations(publisher: IProjectRecord): IInstallations;
|
|
53
|
+
publisher(request: Request, publisher: IProjectRecord, admit: (request: Request, run: TServiceRun) => Promise<Response>): Promise<Response>;
|
|
54
|
+
/** Fresh API binding or private platform reentry. The request already carries the same child. */
|
|
55
|
+
forward(request: Request, content?: IRootSourceAdmission): Promise<Response>;
|
|
56
|
+
resources?(publisher: IProjectRecord, target: IExecutionTarget): Promise<Pick<IRequestExecution, 'store' | 'secrets' | 'database'>>;
|
|
57
|
+
/** Header name used to forward the host-supplied client IP address (default: `'cf-connecting-ip'`). */
|
|
58
|
+
readonly clientIpHeader?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface ISelectedProjects {
|
|
62
|
+
readonly consumer: IProjectRecord;
|
|
63
|
+
readonly publisher: IProjectRecord;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface IServiceGuardBundle {
|
|
67
|
+
readonly guard: PublisherServiceInvocation;
|
|
68
|
+
readonly publisher: IProjectRecord;
|
|
69
|
+
readonly code: () => Promise<(ISiteCode & { readonly projectId: string }) | null>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function failure(error: unknown): Response {
|
|
73
|
+
const headers = { 'cache-control': 'no-store' };
|
|
74
|
+
if (error instanceof IdentityError) {
|
|
75
|
+
return Response.json(
|
|
76
|
+
{ error: { code: error.code, message: error.message } },
|
|
77
|
+
{ status: error.status, headers },
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const { payload, isAppError } = ErrorGate.normalize(error);
|
|
81
|
+
if (isAppError && AppError.isAnyAppError(error) && error.exposure === 'public') {
|
|
82
|
+
return Response.json(
|
|
83
|
+
{ error: { code: payload.code, message: payload.message } },
|
|
84
|
+
{ status: payload.status, headers },
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const fallback = new IdentityError('IDENTITY_UNAVAILABLE');
|
|
88
|
+
return Response.json(
|
|
89
|
+
{ error: { code: fallback.code, message: fallback.message } },
|
|
90
|
+
{ status: fallback.status, headers },
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isActiveProjectAt(
|
|
95
|
+
project: IProjectRecord | null,
|
|
96
|
+
expectedOrigin: string,
|
|
97
|
+
runtime: IServiceHostRuntime,
|
|
98
|
+
): project is IProjectRecord {
|
|
99
|
+
return Boolean(
|
|
100
|
+
project
|
|
101
|
+
&& project.status === 'active'
|
|
102
|
+
&& project.ready === true
|
|
103
|
+
&& runtime.origin(project) === expectedOrigin,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Per-event context for `ServiceHost`, `serviceInvocationFetch`, and `serviceCallbackFetch`. */
|
|
108
|
+
export interface IServiceHostContext {
|
|
109
|
+
readonly env: IIdentityConsumerEnv;
|
|
110
|
+
readonly ctx: IHostContext;
|
|
111
|
+
readonly props: IServiceInvocationProps;
|
|
112
|
+
readonly runtime: IServiceHostRuntime;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Recreated on every private entrypoint fetch, including every later callback. */
|
|
116
|
+
export class ServiceHost {
|
|
117
|
+
private readonly env: IIdentityConsumerEnv;
|
|
118
|
+
|
|
119
|
+
private readonly ctx: IHostContext;
|
|
120
|
+
|
|
121
|
+
private readonly props: IServiceInvocationProps;
|
|
122
|
+
|
|
123
|
+
private readonly runtime: IServiceHostRuntime;
|
|
124
|
+
|
|
125
|
+
constructor(context: IServiceHostContext) {
|
|
126
|
+
this.env = context.env;
|
|
127
|
+
this.ctx = context.ctx;
|
|
128
|
+
this.props = context.props;
|
|
129
|
+
this.runtime = context.runtime;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async selected(externalUnavailable = false): Promise<ISelectedProjects> {
|
|
133
|
+
checkServiceInvocationProps(this.props);
|
|
134
|
+
const { plan } = this.props;
|
|
135
|
+
const [consumer, candidate] = await Promise.all([
|
|
136
|
+
this.runtime.registry.byId(plan.consumerProjectId),
|
|
137
|
+
this.runtime.project(plan.publisherOrigin),
|
|
138
|
+
]);
|
|
139
|
+
if (!isActiveProjectAt(consumer, plan.consumerOrigin, this.runtime)) {
|
|
140
|
+
throw new IdentityError('FORBIDDEN');
|
|
141
|
+
}
|
|
142
|
+
if (!candidate && externalUnavailable) {
|
|
143
|
+
throw new ExternalServiceUnavailableError();
|
|
144
|
+
}
|
|
145
|
+
const publisher = candidate ? await this.runtime.registry.byId(candidate.id) : null;
|
|
146
|
+
if (!isActiveProjectAt(publisher, plan.publisherOrigin, this.runtime)) {
|
|
147
|
+
throw new IdentityError('FORBIDDEN');
|
|
148
|
+
}
|
|
149
|
+
return { consumer, publisher };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private async guard(externalUnavailable = false): Promise<IServiceGuardBundle> {
|
|
153
|
+
const { consumer, publisher } = await this.selected(externalUnavailable);
|
|
154
|
+
const { plan } = this.props;
|
|
155
|
+
const caller = async (): Promise<IIdentityRequestCaller> => {
|
|
156
|
+
checkServiceInvocationProps(this.props);
|
|
157
|
+
const request = new Request(plan.consumerOrigin, { headers: { authorization: 'Bearer ' + this.props.credential } });
|
|
158
|
+
const result = await identityConsumerOf(this.env).caller(request, consumer.id, { fresh: true });
|
|
159
|
+
if (!result) throw new IdentityError('INVALID_PASS');
|
|
160
|
+
return result;
|
|
161
|
+
};
|
|
162
|
+
const code = async (): Promise<(ISiteCode & { readonly projectId: string }) | null> => {
|
|
163
|
+
if (!this.runtime.apiOrigin) return null;
|
|
164
|
+
const [owner, palette] = await Promise.all([
|
|
165
|
+
this.runtime.registry.byNamespace(consumer.namespace),
|
|
166
|
+
this.runtime.registry.palette(consumer.namespace),
|
|
167
|
+
]);
|
|
168
|
+
if (owner?.id !== consumer.id || (palette && palette.projectId !== consumer.id)) {
|
|
169
|
+
throw new IdentityError('FORBIDDEN');
|
|
170
|
+
}
|
|
171
|
+
return { api: this.runtime.apiOrigin, palette: consumer.namespace, projectId: consumer.id };
|
|
172
|
+
};
|
|
173
|
+
const guard = new PublisherServiceInvocation(plan, {
|
|
174
|
+
installations: this.runtime.installations(publisher),
|
|
175
|
+
connection: () => this.runtime.connections(consumer).get(plan.brand),
|
|
176
|
+
caller,
|
|
177
|
+
code,
|
|
178
|
+
contentAllowed: () => this.props.content !== undefined,
|
|
179
|
+
callback: async (target) => {
|
|
180
|
+
const callback = serviceHostEntry(this.ctx, 'ServiceCallback');
|
|
181
|
+
if (!callback) throw new IdentityError('INVALID_CONFIG');
|
|
182
|
+
const content = await this.runtime.contentSourcePolicy?.bind(target, 'content') ?? null;
|
|
183
|
+
return callback({ props: { ...this.props, callbackTarget: target, ...(content ? { content } : {}) } });
|
|
184
|
+
},
|
|
185
|
+
...(this.runtime.resources ? { resources: (target: IExecutionTarget) => this.runtime.resources!(publisher, target) } : {}),
|
|
186
|
+
});
|
|
187
|
+
return { guard, publisher, code };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async invocation(request: Request): Promise<Response> {
|
|
191
|
+
const { guard, publisher } = await this.guard(true);
|
|
192
|
+
return this.runtime.publisher(request, publisher, (selected, run) => guard.admit(selected, run));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async callback(request: Request): Promise<Response> {
|
|
196
|
+
const { guard, code } = await this.guard();
|
|
197
|
+
const destinations = hostCallbackDestinations(this.props.plan.consumerOrigin, await code(), this.props.content !== undefined);
|
|
198
|
+
return guard.callback(request, {
|
|
199
|
+
fetch: async (clean) => {
|
|
200
|
+
checkServiceInvocationProps(this.props);
|
|
201
|
+
const routed = callerOutboundRequest(
|
|
202
|
+
clean,
|
|
203
|
+
{
|
|
204
|
+
credential: this.props.credential,
|
|
205
|
+
expiresAtMs: this.props.expiresAtMs,
|
|
206
|
+
destinations,
|
|
207
|
+
...(this.props.clientAddress ? { clientAddress: this.props.clientAddress } : {}),
|
|
208
|
+
},
|
|
209
|
+
Date.now(),
|
|
210
|
+
this.runtime.clientIpHeader,
|
|
211
|
+
);
|
|
212
|
+
if (routed instanceof Response) return routed;
|
|
213
|
+
return this.runtime.forward(routed, this.props.content);
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A concrete WorkerEntrypoint exposes fetch only; runtime readers stay in this event's closure. */
|
|
220
|
+
export async function serviceInvocationFetch(
|
|
221
|
+
request: Request,
|
|
222
|
+
context: IServiceHostContext,
|
|
223
|
+
): Promise<Response> {
|
|
224
|
+
const outcome = await ErrorGate.run(() => new ServiceHost(context).invocation(request));
|
|
225
|
+
return outcome.ok ? outcome.value : failure(outcome.cause);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function serviceCallbackFetch(
|
|
229
|
+
request: Request,
|
|
230
|
+
context: IServiceHostContext,
|
|
231
|
+
): Promise<Response> {
|
|
232
|
+
const outcome = await ErrorGate.run(() => new ServiceHost(context).callback(request));
|
|
233
|
+
return outcome.ok ? outcome.value : failure(outcome.cause);
|
|
234
|
+
}
|
|
@@ -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
|
+
}
|