@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,296 @@
|
|
|
1
|
+
import { isValidPackageName } from '@mosetta/core/naming';
|
|
2
|
+
import { CONTENT_COMMAND_PATH, PROJECT_MEMORY_PATH } from '@mosetta/content';
|
|
3
|
+
import { IdentityError } from '@mosetta/identity';
|
|
4
|
+
import type { IIdentityRequestCaller } from '@mosetta/identity';
|
|
5
|
+
import { hostMediaPath } from '@mosetta/media/host';
|
|
6
|
+
import { AccessPolicy, ProjectAccess, ProjectAllowances } from '@mosetta/server-action/access';
|
|
7
|
+
import {
|
|
8
|
+
BLOCK_GIVEN_HEADER,
|
|
9
|
+
fullServerTileId,
|
|
10
|
+
HostContextCodec,
|
|
11
|
+
IDENTITY_HEADER,
|
|
12
|
+
SITE_HEADER,
|
|
13
|
+
} from '@mosetta/server-action/core';
|
|
14
|
+
import type { ICallerFetch, ISiteCode } from '@mosetta/server-action/core';
|
|
15
|
+
import {
|
|
16
|
+
CODE_GRANT,
|
|
17
|
+
MEDIA_GRANT,
|
|
18
|
+
PREVIEWS_GRANT,
|
|
19
|
+
REPOSITORIES_GRANT,
|
|
20
|
+
SERVICE_BLOCK_MAX,
|
|
21
|
+
ServiceProtocolCodec,
|
|
22
|
+
} from './protocol';
|
|
23
|
+
import type { IServiceActionAddress } from './protocol';
|
|
24
|
+
import { assertValidServiceOrigin, stripServiceRequestHeaders } from './serviceInvocation';
|
|
25
|
+
import type { IServiceInvocationPlan, IServicePublisherPorts, TServiceRun } from './serviceInvocation';
|
|
26
|
+
|
|
27
|
+
interface IFreshService {
|
|
28
|
+
readonly caller: IIdentityRequestCaller;
|
|
29
|
+
readonly grants: readonly (readonly string[])[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]{1,40})?$/;
|
|
33
|
+
const SOURCE_OPS = new Set(['sources', 'check', 'draft', 'release']);
|
|
34
|
+
const BUILT_OPS = new Set(['plan', 'push', 'draft', 'drafts']);
|
|
35
|
+
|
|
36
|
+
function tailAfterPalette(pathname: string, kind: string, palette: string): string | null {
|
|
37
|
+
for (const seg of [palette, encodeURIComponent(palette)]) {
|
|
38
|
+
const prefix = `${kind}${seg}/`;
|
|
39
|
+
if (pathname.startsWith(prefix)) return pathname.slice(prefix.length);
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function codeCallbackOperation(pathname: string, palette: string, method: string): 'code.edit' | 'code.release' | null {
|
|
45
|
+
const srcOp = tailAfterPalette(pathname, '/v1/palettes/', palette);
|
|
46
|
+
if (srcOp && SOURCE_OPS.has(srcOp)) return method === (srcOp === 'sources' ? 'GET' : 'POST') ? (srcOp === 'release' ? 'code.release' : 'code.edit') : null;
|
|
47
|
+
if (method !== 'POST') return null;
|
|
48
|
+
const builtOp = tailAfterPalette(pathname, '/v1/code/palettes/', palette);
|
|
49
|
+
if (builtOp && BUILT_OPS.has(builtOp)) return builtOp === 'plan' || builtOp === 'push' ? 'code.release' : 'code.edit';
|
|
50
|
+
return pathname === `/v1/builds/palettes/${palette}` || pathname === `/v1/builds/palettes/${encodeURIComponent(palette)}` ? 'code.edit' : null;
|
|
51
|
+
}
|
|
52
|
+
const PERSONAL_MEMORY_ACTIONS = new Set([
|
|
53
|
+
'listConversations',
|
|
54
|
+
'readConversation',
|
|
55
|
+
'keepConversation',
|
|
56
|
+
'removeConversation',
|
|
57
|
+
'takeTask',
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
function validatePlan(plan: IServiceInvocationPlan): IServiceInvocationPlan {
|
|
61
|
+
assertValidServiceOrigin(plan.consumerOrigin);
|
|
62
|
+
assertValidServiceOrigin(plan.publisherOrigin);
|
|
63
|
+
const grant = ServiceProtocolCodec.grantOf(plan.grant);
|
|
64
|
+
if (
|
|
65
|
+
!ProjectAllowances.isId(plan.consumerProjectId)
|
|
66
|
+
|| !ProjectAllowances.isId(plan.installation)
|
|
67
|
+
|| !isValidPackageName(plan.brand)
|
|
68
|
+
|| !VERSION_RE.test(plan.version)
|
|
69
|
+
|| !grant
|
|
70
|
+
|| (plan.block !== null && (typeof plan.block !== 'string' || plan.block.length > SERVICE_BLOCK_MAX))
|
|
71
|
+
) {
|
|
72
|
+
throw new IdentityError('INVALID_CONFIG');
|
|
73
|
+
}
|
|
74
|
+
return { ...plan, grant };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function validateDelegatedCaller(caller: IIdentityRequestCaller, consumerProjectId: string): void {
|
|
78
|
+
const { proof, person, current } = caller;
|
|
79
|
+
if (proof.expiresAt * 1000 <= Date.now()) throw new IdentityError('INVALID_PASS');
|
|
80
|
+
if (!Number.isSafeInteger(current.expiresAtMs) || (current.cacheable && current.expiresAtMs <= Date.now())) {
|
|
81
|
+
throw new IdentityError('IDENTITY_UNAVAILABLE');
|
|
82
|
+
}
|
|
83
|
+
const matchesIds = person.id === proof.personId
|
|
84
|
+
&& current.personId === proof.personId
|
|
85
|
+
&& current.sessionId === proof.sessionId
|
|
86
|
+
&& current.tokenId === proof.tokenId
|
|
87
|
+
&& current.projectId === consumerProjectId;
|
|
88
|
+
const allowancesValid = current.may.length > 0
|
|
89
|
+
&& current.may.every((allowance) => allowance.permission !== '*' && allowance.projectId === current.projectId);
|
|
90
|
+
if (proof.kind !== 'delegated' || current.kind !== 'delegated' || !matchesIds || !allowancesValid) {
|
|
91
|
+
throw new IdentityError('FORBIDDEN');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function escapeNonAscii(value: string): string {
|
|
96
|
+
return value.replace(/[\u007f-\uffff]/g, (letter) => `\\u${letter.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Pure per-event admission logic used inside the Root-owned private publisher entrypoint. */
|
|
100
|
+
export class PublisherServiceInvocation {
|
|
101
|
+
readonly plan: IServiceInvocationPlan;
|
|
102
|
+
|
|
103
|
+
constructor(plan: IServiceInvocationPlan, private readonly ports: IServicePublisherPorts) {
|
|
104
|
+
this.plan = validatePlan(plan);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private async fresh(): Promise<IFreshService> {
|
|
108
|
+
const [installation, connection, caller] = await Promise.all([
|
|
109
|
+
this.ports.installations.byId(this.plan.installation),
|
|
110
|
+
this.ports.connection(),
|
|
111
|
+
this.ports.caller(),
|
|
112
|
+
]);
|
|
113
|
+
const validInstallation = Boolean(
|
|
114
|
+
installation
|
|
115
|
+
&& installation.status === 'active'
|
|
116
|
+
&& installation.id === this.plan.installation
|
|
117
|
+
&& installation.consumer === this.plan.consumerOrigin
|
|
118
|
+
&& installation.brand === this.plan.brand
|
|
119
|
+
&& installation.version === this.plan.version,
|
|
120
|
+
);
|
|
121
|
+
const validConnection = Boolean(
|
|
122
|
+
connection
|
|
123
|
+
&& connection.installation === this.plan.installation
|
|
124
|
+
&& connection.brand === this.plan.brand
|
|
125
|
+
&& connection.publisher === this.plan.publisherOrigin
|
|
126
|
+
&& connection.version === this.plan.version,
|
|
127
|
+
);
|
|
128
|
+
if (!validInstallation || !validConnection) throw new IdentityError('FORBIDDEN');
|
|
129
|
+
validateDelegatedCaller(caller, this.plan.consumerProjectId);
|
|
130
|
+
return { caller, grants: [this.plan.grant, connection!.grant, installation!.grant] };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** An uncacheable answer is usable only for its fresh call, never carried over an awaited operation. */
|
|
134
|
+
private async beforeUse(fresh: IFreshService): Promise<IFreshService> {
|
|
135
|
+
if (!fresh.caller.current.cacheable) return this.fresh();
|
|
136
|
+
if (fresh.caller.proof.expiresAt * 1000 <= Date.now()) throw new IdentityError('INVALID_PASS');
|
|
137
|
+
if (fresh.caller.current.expiresAtMs <= Date.now()) throw new IdentityError('IDENTITY_UNAVAILABLE');
|
|
138
|
+
return fresh;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private async code(fresh: IFreshService): Promise<ISiteCode | null> {
|
|
142
|
+
if (!fresh.grants.every((grant) => grant.includes(CODE_GRANT)) || !this.ports.code) return null;
|
|
143
|
+
const code = await this.ports.code();
|
|
144
|
+
if (!code) return null;
|
|
145
|
+
if (code.projectId !== this.plan.consumerProjectId || !isValidPackageName(code.palette)) {
|
|
146
|
+
throw new IdentityError('FORBIDDEN');
|
|
147
|
+
}
|
|
148
|
+
assertValidServiceOrigin(code.api);
|
|
149
|
+
return { api: code.api, palette: code.palette };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private module(request: Request): IServiceActionAddress {
|
|
153
|
+
const url = new URL(request.url);
|
|
154
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
155
|
+
if (
|
|
156
|
+
url.origin !== this.plan.publisherOrigin
|
|
157
|
+
|| !action
|
|
158
|
+
|| action.brand !== this.plan.brand
|
|
159
|
+
|| action.fullId !== fullServerTileId({ namespace: this.plan.brand, name: action.tile, version: this.plan.version })
|
|
160
|
+
) {
|
|
161
|
+
throw new IdentityError('FORBIDDEN');
|
|
162
|
+
}
|
|
163
|
+
return action;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async admit(request: Request, run: TServiceRun): Promise<Response> {
|
|
167
|
+
this.module(request);
|
|
168
|
+
await this.fresh();
|
|
169
|
+
const admitted = stripServiceRequestHeaders(request);
|
|
170
|
+
if (this.plan.block !== null) admitted.headers.set(BLOCK_GIVEN_HEADER, this.plan.block);
|
|
171
|
+
return run(admitted, async (selected, target) => {
|
|
172
|
+
const action = this.module(selected);
|
|
173
|
+
if (target.moduleId !== action.fullId || target.endpoint) throw new IdentityError('FORBIDDEN');
|
|
174
|
+
let fresh = await this.fresh();
|
|
175
|
+
const code = await this.code(fresh);
|
|
176
|
+
const resources = this.ports.resources ? await this.ports.resources(target) : {};
|
|
177
|
+
const callerOutbound = await this.ports.callback(target);
|
|
178
|
+
fresh = await this.beforeUse(fresh);
|
|
179
|
+
const { proof, person, current } = fresh.caller;
|
|
180
|
+
const access = { projectId: current.projectId, scopeIds: current.scopeIds };
|
|
181
|
+
const safe = { ...person, kind: proof.kind, sessionId: proof.sessionId, tokenId: proof.tokenId, through: [...proof.via], may: current.may, access };
|
|
182
|
+
const inward = stripServiceRequestHeaders(selected);
|
|
183
|
+
const headers = new Headers(inward.headers);
|
|
184
|
+
headers.set(IDENTITY_HEADER, escapeNonAscii(JSON.stringify({
|
|
185
|
+
via: 'service',
|
|
186
|
+
installation: this.plan.installation,
|
|
187
|
+
site: this.plan.consumerOrigin,
|
|
188
|
+
kind: proof.kind,
|
|
189
|
+
sessionId: proof.sessionId,
|
|
190
|
+
tokenId: proof.tokenId,
|
|
191
|
+
through: [...proof.via],
|
|
192
|
+
person: safe,
|
|
193
|
+
})));
|
|
194
|
+
headers.set(SITE_HEADER, HostContextCodec.encodeSite({
|
|
195
|
+
origin: this.plan.consumerOrigin,
|
|
196
|
+
...(code && fresh.grants.every((grant) => grant.includes(CODE_GRANT)) ? { code } : {}),
|
|
197
|
+
}));
|
|
198
|
+
return { ...resources, request: ProjectAccess.withContext(new Request(inward, { headers }), access), callerOutbound };
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private authorizeCodeCallback(request: Request, url: URL, context: { readonly fresh: IFreshService; readonly code: ISiteCode }): void {
|
|
203
|
+
const { fresh, code } = context;
|
|
204
|
+
if (!fresh.grants.every((set) => set.includes(CODE_GRANT))) throw new IdentityError('FORBIDDEN');
|
|
205
|
+
const operation = codeCallbackOperation(url.pathname, code.palette, request.method);
|
|
206
|
+
if (!operation) throw new IdentityError('FORBIDDEN');
|
|
207
|
+
const policy = new AccessPolicy(fresh.caller.current.projectId, fresh.caller.current.scopeIds);
|
|
208
|
+
if (!policy.can(fresh.caller.current, operation, '*')) throw new IdentityError('FORBIDDEN');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private authorizeDoorCallback(request: Request, url: URL, fresh: IFreshService): void {
|
|
212
|
+
const door = url.pathname === '/__mosetta__/preview/share'
|
|
213
|
+
? PREVIEWS_GRANT
|
|
214
|
+
: hostMediaPath(url.pathname)
|
|
215
|
+
? MEDIA_GRANT
|
|
216
|
+
: url.pathname === '/__mosetta__/repositories'
|
|
217
|
+
? REPOSITORIES_GRANT
|
|
218
|
+
: null;
|
|
219
|
+
if (door === MEDIA_GRANT && !this.ports.contentAllowed?.()) throw new IdentityError('FORBIDDEN');
|
|
220
|
+
const methodOk = door === REPOSITORIES_GRANT
|
|
221
|
+
? request.method === 'GET'
|
|
222
|
+
: door === MEDIA_GRANT && url.pathname.startsWith('/__mosetta__/media/resource/')
|
|
223
|
+
? ['GET', 'HEAD'].includes(request.method)
|
|
224
|
+
: request.method === 'POST';
|
|
225
|
+
if (!door || !fresh.grants.every((set) => set.includes(door)) || !methodOk) {
|
|
226
|
+
throw new IdentityError('FORBIDDEN');
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async dispatchReadCallback(
|
|
231
|
+
request: Request,
|
|
232
|
+
url: URL,
|
|
233
|
+
context: { readonly fresh: IFreshService; readonly send: ICallerFetch },
|
|
234
|
+
): Promise<Response | null> {
|
|
235
|
+
if (request.method !== 'GET') return null;
|
|
236
|
+
const { fresh, send } = context;
|
|
237
|
+
if (url.pathname === '/__mosetta__/project') {
|
|
238
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
239
|
+
}
|
|
240
|
+
if (url.pathname === '/__mosetta__/scopes' && fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, '@mosetta/editor', 'content'))) {
|
|
241
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
242
|
+
}
|
|
243
|
+
if (url.pathname === '/api/server-action/') {
|
|
244
|
+
let answer = await send.fetch(stripServiceRequestHeaders(request));
|
|
245
|
+
for (const grant of fresh.grants) answer = await ServiceProtocolCodec.grantedListing(answer, grant);
|
|
246
|
+
return answer;
|
|
247
|
+
}
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private async dispatchConsumerCallback(request: Request, url: URL, context: { readonly fresh: IFreshService; readonly send: ICallerFetch }): Promise<Response> {
|
|
252
|
+
const { fresh, send } = context;
|
|
253
|
+
if (url.pathname === PROJECT_MEMORY_PATH || url.pathname === CONTENT_COMMAND_PATH) {
|
|
254
|
+
const tile = url.pathname === PROJECT_MEMORY_PATH ? 'memory' : 'content';
|
|
255
|
+
const allowed = fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, '@mosetta/editor', tile));
|
|
256
|
+
if (request.method !== 'POST' || !this.ports.contentAllowed?.() || !allowed) {
|
|
257
|
+
throw new IdentityError('FORBIDDEN');
|
|
258
|
+
}
|
|
259
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
260
|
+
}
|
|
261
|
+
const readHandled = await this.dispatchReadCallback(request, url, context);
|
|
262
|
+
if (readHandled) return readHandled;
|
|
263
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
264
|
+
if (action) {
|
|
265
|
+
const allowed = fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, action.brand, action.tile));
|
|
266
|
+
if (
|
|
267
|
+
request.method !== 'POST'
|
|
268
|
+
|| (action.tile === 'memory' && PERSONAL_MEMORY_ACTIONS.has(action.action))
|
|
269
|
+
|| !allowed
|
|
270
|
+
) {
|
|
271
|
+
throw new IdentityError('FORBIDDEN');
|
|
272
|
+
}
|
|
273
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
274
|
+
}
|
|
275
|
+
this.authorizeDoorCallback(request, url, fresh);
|
|
276
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Install this guard inside the Root-owned callback WorkerEntrypoint; never serialize this class as a port. */
|
|
280
|
+
async callback(request: Request, send: ICallerFetch): Promise<Response> {
|
|
281
|
+
let fresh = await this.fresh();
|
|
282
|
+
if (request.headers.has('authorization') || request.headers.has('cookie')) {
|
|
283
|
+
throw new IdentityError('FORBIDDEN');
|
|
284
|
+
}
|
|
285
|
+
const url = new URL(request.url);
|
|
286
|
+
if (url.username || url.password || url.hash) throw new IdentityError('FORBIDDEN');
|
|
287
|
+
const code = await this.code(fresh);
|
|
288
|
+
fresh = await this.beforeUse(fresh);
|
|
289
|
+
if (code && url.origin === code.api) {
|
|
290
|
+
this.authorizeCodeCallback(request, url, { fresh, code });
|
|
291
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
292
|
+
}
|
|
293
|
+
if (url.origin !== this.plan.consumerOrigin) throw new IdentityError('FORBIDDEN');
|
|
294
|
+
return this.dispatchConsumerCallback(request, url, { fresh, send });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { IdentityError, ProjectCataloguePolicy } from '@mosetta/identity';
|
|
2
|
+
import type { IProjectIoOperation, IProjectRecord, ISqlDatabase, SqlProjectIo } from '@mosetta/tenancy';
|
|
3
|
+
import type { IServiceConnection, IServicesComposition } from './protocol';
|
|
4
|
+
|
|
5
|
+
/** Configuration for `GuardedServiceComposition`. */
|
|
6
|
+
export interface IGuardedServiceCompositionOptions {
|
|
7
|
+
readonly db: ISqlDatabase;
|
|
8
|
+
readonly operation: IProjectIoOperation;
|
|
9
|
+
readonly executor: SqlProjectIo;
|
|
10
|
+
readonly handle: object;
|
|
11
|
+
readonly publisher: (origin: string) => Promise<IProjectRecord | null>;
|
|
12
|
+
readonly transitioned: (previous: number, next: number) => void;
|
|
13
|
+
readonly defaults?: ReadonlySet<string>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Actual affected-project configuration mutation; no application SQL or HTTP metadata enters it. */
|
|
17
|
+
export class GuardedServiceComposition implements IServicesComposition {
|
|
18
|
+
private readonly db: ISqlDatabase;
|
|
19
|
+
|
|
20
|
+
private readonly operation: IProjectIoOperation;
|
|
21
|
+
|
|
22
|
+
private readonly executor: SqlProjectIo;
|
|
23
|
+
|
|
24
|
+
private readonly handle: object;
|
|
25
|
+
|
|
26
|
+
private readonly publisher: (origin: string) => Promise<IProjectRecord | null>;
|
|
27
|
+
|
|
28
|
+
private readonly transitioned: (previous: number, next: number) => void;
|
|
29
|
+
|
|
30
|
+
private readonly defaults?: ReadonlySet<string>;
|
|
31
|
+
|
|
32
|
+
constructor(options: IGuardedServiceCompositionOptions) {
|
|
33
|
+
this.db = options.db;
|
|
34
|
+
this.operation = options.operation;
|
|
35
|
+
this.executor = options.executor;
|
|
36
|
+
this.handle = options.handle;
|
|
37
|
+
this.publisher = options.publisher;
|
|
38
|
+
this.transitioned = options.transitioned;
|
|
39
|
+
this.defaults = options.defaults;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async attach(connection: IServiceConnection): Promise<boolean> {
|
|
43
|
+
if (this.defaults && !this.defaults.has(`${connection.brand}\n${connection.publisher}`)) {
|
|
44
|
+
throw new IdentityError('FORBIDDEN');
|
|
45
|
+
}
|
|
46
|
+
const publisher = await this.publisher(connection.publisher);
|
|
47
|
+
if (!publisher || publisher.status !== 'active' || publisher.ready !== true) {
|
|
48
|
+
throw new IdentityError('FORBIDDEN');
|
|
49
|
+
}
|
|
50
|
+
const digest = await ProjectCataloguePolicy.hash(
|
|
51
|
+
JSON.stringify(['service.attach', connection.brand, connection.publisher, publisher.id]),
|
|
52
|
+
);
|
|
53
|
+
const step = crypto.randomUUID();
|
|
54
|
+
await this.executor.commit(this.handle, step, digest, () => [
|
|
55
|
+
this.db.prepare(
|
|
56
|
+
'INSERT INTO palette_attachments(project_id,brand,attached_at,served_by) SELECT ?,t.brand,?,? FROM tile_palettes t JOIN projects publisher ON publisher.id=t.project_id '
|
|
57
|
+
+ 'WHERE t.brand=? AND t.project_id=? AND t.project_id<>? AND publisher.status=\'active\' AND publisher.ready=1 '
|
|
58
|
+
+ 'ON CONFLICT(project_id,brand) DO UPDATE SET served_by=excluded.served_by WHERE palette_attachments.served_by IS NOT excluded.served_by',
|
|
59
|
+
).bind(
|
|
60
|
+
this.operation.target.projectId,
|
|
61
|
+
connection.at,
|
|
62
|
+
connection.publisher,
|
|
63
|
+
connection.brand,
|
|
64
|
+
publisher.id,
|
|
65
|
+
this.operation.target.projectId,
|
|
66
|
+
),
|
|
67
|
+
this.db.prepare(
|
|
68
|
+
'INSERT INTO project_io_assert(required) SELECT NULL WHERE changes()<>1 AND NOT EXISTS(SELECT 1 FROM palette_attachments WHERE project_id=? AND brand=? AND served_by=?)',
|
|
69
|
+
).bind(this.operation.target.projectId, connection.brand, connection.publisher),
|
|
70
|
+
...this.receipt(step),
|
|
71
|
+
]);
|
|
72
|
+
await this.record(step);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async detach(brand: string): Promise<void> {
|
|
77
|
+
if (this.defaults) throw new IdentityError('FORBIDDEN');
|
|
78
|
+
const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.detach', brand]));
|
|
79
|
+
const step = crypto.randomUUID();
|
|
80
|
+
await this.executor.commit(this.handle, step, digest, () => [
|
|
81
|
+
this.db.prepare('DELETE FROM palette_attachments WHERE project_id=? AND brand=? AND served_by IS NOT NULL')
|
|
82
|
+
.bind(this.operation.target.projectId, brand),
|
|
83
|
+
...this.receipt(step),
|
|
84
|
+
]);
|
|
85
|
+
await this.record(step);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private receipt(step: string): ReturnType<ISqlDatabase['prepare']>[] {
|
|
89
|
+
const { projectId, sourceKey, sourceGeneration } = this.operation.target;
|
|
90
|
+
return [
|
|
91
|
+
this.db.prepare(
|
|
92
|
+
'INSERT INTO project_io_configuration_steps(operation_id,step_id,previous_generation,next_generation) '
|
|
93
|
+
+ 'SELECT ?,?,?,source_generation FROM project_resource_catalogues WHERE project_id=? AND source_key=? AND source_generation IN(?,?+1)',
|
|
94
|
+
).bind(this.operation.id, step, sourceGeneration, projectId, sourceKey, sourceGeneration, sourceGeneration),
|
|
95
|
+
this.db.prepare('INSERT INTO project_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private async record(step: string): Promise<void> {
|
|
100
|
+
const row = await this.db
|
|
101
|
+
.prepare('SELECT previous_generation,next_generation FROM project_io_configuration_steps WHERE operation_id=? AND step_id=?')
|
|
102
|
+
.bind(this.operation.id, step)
|
|
103
|
+
.first<{ previous_generation: number; next_generation: number }>();
|
|
104
|
+
if (!row || row.previous_generation !== this.operation.target.sourceGeneration) {
|
|
105
|
+
throw new IdentityError('FORBIDDEN');
|
|
106
|
+
}
|
|
107
|
+
this.transitioned(row.previous_generation, row.next_generation);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Errors } from '@mosetta/core';
|
|
2
|
+
import type { IServiceConnection } from '@mosetta/host-platform/host';
|
|
3
|
+
import { signToken } from '@mosetta/host-platform/tokens';
|
|
4
|
+
import { ServiceProtocolCodec } from './protocolCodec';
|
|
5
|
+
import {
|
|
6
|
+
INSTALLATION_KEY_PREFIX,
|
|
7
|
+
INSTALLATIONS_PATH,
|
|
8
|
+
LISTING_PATH,
|
|
9
|
+
PROOF_PREFIX,
|
|
10
|
+
PROOF_TTL_SECONDS,
|
|
11
|
+
} from './protocolTypes';
|
|
12
|
+
import type {
|
|
13
|
+
IServiceAsked,
|
|
14
|
+
IServiceOffer,
|
|
15
|
+
IServicesHost,
|
|
16
|
+
TServiceSessionIdentity,
|
|
17
|
+
} from './protocolTypes';
|
|
18
|
+
import type { IServiceTechnicalOutgoing } from './serviceTechnicalIo';
|
|
19
|
+
|
|
20
|
+
/** Context passed into `ServiceConnectionClient.connectService`. */
|
|
21
|
+
export interface IServiceConnectContext {
|
|
22
|
+
readonly url: URL;
|
|
23
|
+
readonly session: TServiceSessionIdentity;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface IPublisherInstallReply {
|
|
27
|
+
readonly installation?: unknown;
|
|
28
|
+
readonly key?: unknown;
|
|
29
|
+
readonly error?: { readonly code?: unknown; readonly message?: unknown };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface IAcceptedInstall {
|
|
33
|
+
readonly installation: string;
|
|
34
|
+
readonly key: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Consumer-side handshake client that signs confirmation proofs, requests
|
|
39
|
+
* installations from a publisher, seals connection keys, and attaches blocks.
|
|
40
|
+
*/
|
|
41
|
+
export class ServiceConnectionClient {
|
|
42
|
+
constructor(private readonly host: IServicesHost) {}
|
|
43
|
+
|
|
44
|
+
async connectService(asked: IServiceAsked, context: IServiceConnectContext): Promise<Response> {
|
|
45
|
+
if (!this.host.secret) return ServiceProtocolCodec.refusalResponse(501, 'NO_SESSION_KEY');
|
|
46
|
+
if (!this.host.technical) return ServiceProtocolCodec.refusalResponse(501, 'TECHNICAL_IO_UNAVAILABLE');
|
|
47
|
+
const now = this.host.now?.() ?? new Date();
|
|
48
|
+
const exp = Math.min(ServiceProtocolCodec.secondsOf(now) + PROOF_TTL_SECONDS, context.session.exp ?? Number.MAX_SAFE_INTEGER);
|
|
49
|
+
const token = await signToken(
|
|
50
|
+
{ aud: ServiceProtocolCodec.proofAudience(context.url.hostname), jti: crypto.randomUUID(), ...asked, exp },
|
|
51
|
+
this.host.secret,
|
|
52
|
+
);
|
|
53
|
+
const proof = `${PROOF_PREFIX}${token}`;
|
|
54
|
+
const attempt = await this.host.technical.outgoing({ consumer: context.url.origin, ...asked, proof });
|
|
55
|
+
try {
|
|
56
|
+
const reply = await this.requestPublisherInstall({ asked, context, proof, attempt });
|
|
57
|
+
if (reply instanceof Response) return reply;
|
|
58
|
+
return await this.finalizeConnection({ asked, context, now, attempt, accepted: reply });
|
|
59
|
+
} catch (error) {
|
|
60
|
+
await attempt.uncertain();
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private async settleRejectedInstall(
|
|
66
|
+
answer: Response,
|
|
67
|
+
said: IPublisherInstallReply | null,
|
|
68
|
+
attempt: IServiceTechnicalOutgoing,
|
|
69
|
+
): Promise<Response> {
|
|
70
|
+
if (answer.status >= 400 && answer.status < 500) {
|
|
71
|
+
await attempt.finish().catch(() => attempt.uncertain());
|
|
72
|
+
} else {
|
|
73
|
+
await attempt.uncertain();
|
|
74
|
+
}
|
|
75
|
+
const code = typeof said?.error?.code === 'string' ? said.error.code : `PUBLISHER_${answer.status}`;
|
|
76
|
+
const status = answer.ok ? 502 : answer.status === 403 ? 403 : 502;
|
|
77
|
+
const message = typeof said?.error?.message === 'string'
|
|
78
|
+
? said.error.message
|
|
79
|
+
: 'the publisher did not connect the service';
|
|
80
|
+
return ServiceProtocolCodec.refusalResponse(status, code, message);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private async requestPublisherInstall(input: {
|
|
84
|
+
readonly asked: IServiceAsked;
|
|
85
|
+
readonly context: IServiceConnectContext;
|
|
86
|
+
readonly proof: string;
|
|
87
|
+
readonly attempt: IServiceTechnicalOutgoing;
|
|
88
|
+
}): Promise<IAcceptedInstall | Response> {
|
|
89
|
+
const { asked, context, proof, attempt } = input;
|
|
90
|
+
let answer: Response;
|
|
91
|
+
try {
|
|
92
|
+
answer = await this.host.fetch(`${asked.publisher}${INSTALLATIONS_PATH}`, {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
redirect: 'manual',
|
|
95
|
+
headers: { 'content-type': 'application/json' },
|
|
96
|
+
body: JSON.stringify({
|
|
97
|
+
consumer: context.url.origin,
|
|
98
|
+
brand: asked.brand,
|
|
99
|
+
version: asked.version,
|
|
100
|
+
grant: asked.grant,
|
|
101
|
+
person: { id: context.session.sub, via: context.session.via, login: context.session.login },
|
|
102
|
+
proof,
|
|
103
|
+
}),
|
|
104
|
+
});
|
|
105
|
+
} catch (caught) {
|
|
106
|
+
const error = Errors.toError(caught);
|
|
107
|
+
await attempt.uncertain();
|
|
108
|
+
return ServiceProtocolCodec.refusalResponse(502, 'PUBLISHER_UNREACHABLE', error.message);
|
|
109
|
+
}
|
|
110
|
+
const said = await answer.json().catch(() => null) as IPublisherInstallReply | null;
|
|
111
|
+
if (
|
|
112
|
+
!answer.ok
|
|
113
|
+
|| typeof said?.installation !== 'string'
|
|
114
|
+
|| typeof said.key !== 'string'
|
|
115
|
+
|| !said.key.startsWith(INSTALLATION_KEY_PREFIX)
|
|
116
|
+
) {
|
|
117
|
+
return this.settleRejectedInstall(answer, said, attempt);
|
|
118
|
+
}
|
|
119
|
+
return { installation: said.installation, key: said.key };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private async finalizeConnection(input: {
|
|
123
|
+
readonly asked: IServiceAsked;
|
|
124
|
+
readonly context: IServiceConnectContext;
|
|
125
|
+
readonly now: Date;
|
|
126
|
+
readonly attempt: IServiceTechnicalOutgoing;
|
|
127
|
+
readonly accepted: IAcceptedInstall;
|
|
128
|
+
}): Promise<Response> {
|
|
129
|
+
const { asked, context, now, attempt, accepted } = input;
|
|
130
|
+
const connections = this.host.connections!;
|
|
131
|
+
const offer = await this.offerOf(asked);
|
|
132
|
+
const connection: IServiceConnection = {
|
|
133
|
+
...asked,
|
|
134
|
+
installation: accepted.installation,
|
|
135
|
+
key: accepted.key,
|
|
136
|
+
at: now.toISOString(),
|
|
137
|
+
by: context.session.login,
|
|
138
|
+
...(offer?.workbench ? { workbench: offer.workbench } : {}),
|
|
139
|
+
};
|
|
140
|
+
const older = await connections.get(asked.brand);
|
|
141
|
+
await connections.put(connection);
|
|
142
|
+
await attempt.finish();
|
|
143
|
+
if (older && older.installation !== connection.installation) {
|
|
144
|
+
await this.notifyReplacedConnection(older);
|
|
145
|
+
}
|
|
146
|
+
const composed = await this.attachComposition(connection);
|
|
147
|
+
const { key: _key, ...shown } = connection;
|
|
148
|
+
return ServiceProtocolCodec.jsonResponse(200, { ok: true, service: shown, composed });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async offerOf(asked: Pick<IServiceAsked, 'publisher' | 'brand' | 'version'>): Promise<IServiceOffer | null> {
|
|
152
|
+
try {
|
|
153
|
+
const res = await this.host.fetch(`${asked.publisher}${LISTING_PATH}`, { headers: { accept: 'application/json' } });
|
|
154
|
+
if (!res.ok) {
|
|
155
|
+
await res.body?.cancel();
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
const listed = await res.json() as { services?: unknown };
|
|
159
|
+
return ServiceProtocolCodec.offersIn(listed)
|
|
160
|
+
.find((offer) => offer.brand === asked.brand && offer.version === asked.version) ?? null;
|
|
161
|
+
} catch {
|
|
162
|
+
// fallback: missing offer metadata is non-fatal; connection proceeds without workbench roles
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private async notifyReplacedConnection(older: IServiceConnection): Promise<void> {
|
|
168
|
+
await this.host.fetch(`${older.publisher}${INSTALLATIONS_PATH}`, {
|
|
169
|
+
method: 'DELETE',
|
|
170
|
+
redirect: 'manual',
|
|
171
|
+
headers: { authorization: `Bearer ${older.key}` },
|
|
172
|
+
})
|
|
173
|
+
.then((res) => res.body?.cancel())
|
|
174
|
+
.catch((error: unknown) => console.warn(`services: ${older.publisher} was not told ${older.installation} ended`, error));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private async attachComposition(connection: IServiceConnection): Promise<boolean> {
|
|
178
|
+
if (!this.host.composition) return false;
|
|
179
|
+
return this.host.composition.attach(connection).catch((error: unknown) => {
|
|
180
|
+
console.warn(`services: ${connection.brand} did not join the site's composition`, error);
|
|
181
|
+
return false;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|