@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,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
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Errors } from '@mosetta/core';
|
|
2
|
+
import type { IDefaultService } from '@mosetta/host-platform/host';
|
|
3
|
+
import { ServiceProtocolError } from './errors';
|
|
4
|
+
import { ServiceProtocolCodec } from './protocolCodec';
|
|
5
|
+
import { LISTING_PATH } from './protocolTypes';
|
|
6
|
+
import type {
|
|
7
|
+
IServiceMutationSession,
|
|
8
|
+
IServiceOffer,
|
|
9
|
+
IServicesHost,
|
|
10
|
+
TServiceSessionIdentity,
|
|
11
|
+
} from './protocolTypes';
|
|
12
|
+
import { ServiceConnectionClient } from './serviceConnectionClient';
|
|
13
|
+
|
|
14
|
+
/** How long a default service that could not be connected is left alone before retry. */
|
|
15
|
+
const DEFAULT_RETRY_MS = 5 * 60_000;
|
|
16
|
+
const defaultsTried = new Map<string, number>();
|
|
17
|
+
|
|
18
|
+
/** Deduplicate concurrent default-service connects for the same site and brand inside one isolate. */
|
|
19
|
+
const defaultsInFlight = new Map<string, Promise<void>>();
|
|
20
|
+
|
|
21
|
+
/** How long an isolate caches a publisher's offered services list. */
|
|
22
|
+
const OFFER_TTL_MS = 5 * 60_000;
|
|
23
|
+
const offersKept = new Map<string, { at: number; offer: IServiceOffer | null }>();
|
|
24
|
+
|
|
25
|
+
/** Input options for `ServiceDefaultsCoordinator.connectDefaults`. */
|
|
26
|
+
export interface IConnectDefaultsOptions {
|
|
27
|
+
readonly url: URL;
|
|
28
|
+
readonly session: TServiceSessionIdentity;
|
|
29
|
+
readonly defaults: readonly IDefaultService[];
|
|
30
|
+
readonly now?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface IDefaultConnectContext {
|
|
34
|
+
readonly url: URL;
|
|
35
|
+
readonly session: TServiceSessionIdentity;
|
|
36
|
+
readonly now: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Coordinates automatic connection and version upgrades of host-configured
|
|
41
|
+
* default services, deduplicating concurrent installs and backing off failures.
|
|
42
|
+
*/
|
|
43
|
+
export class ServiceDefaultsCoordinator {
|
|
44
|
+
constructor(private readonly host: IServicesHost) {}
|
|
45
|
+
|
|
46
|
+
async connectDefaults(options: IConnectDefaultsOptions): Promise<void> {
|
|
47
|
+
if (!this.host.connections || !this.host.secret) return;
|
|
48
|
+
const now = options.now ?? Date.now();
|
|
49
|
+
for (const wanted of options.defaults) {
|
|
50
|
+
if (wanted.publisher === options.url.origin) continue;
|
|
51
|
+
const cacheKey = `${options.url.host}|${wanted.brand}`;
|
|
52
|
+
const running = defaultsInFlight.get(cacheKey);
|
|
53
|
+
if (running) {
|
|
54
|
+
await running;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if ((defaultsTried.get(cacheKey) ?? 0) > now) continue;
|
|
58
|
+
const work = this.connectSingleDefault(wanted, {
|
|
59
|
+
url: options.url,
|
|
60
|
+
session: options.session,
|
|
61
|
+
now,
|
|
62
|
+
});
|
|
63
|
+
defaultsInFlight.set(cacheKey, work);
|
|
64
|
+
try {
|
|
65
|
+
await work;
|
|
66
|
+
} finally {
|
|
67
|
+
if (defaultsInFlight.get(cacheKey) === work) defaultsInFlight.delete(cacheKey);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private async offeredNow(wanted: IDefaultService, now: number): Promise<IServiceOffer | null> {
|
|
73
|
+
const key = `${wanted.publisher}|${wanted.brand}`;
|
|
74
|
+
const kept = offersKept.get(key);
|
|
75
|
+
if (kept && now - kept.at < OFFER_TTL_MS) return kept.offer;
|
|
76
|
+
let offer: IServiceOffer | null = null;
|
|
77
|
+
try {
|
|
78
|
+
const res = await this.host.fetch(`${wanted.publisher}${LISTING_PATH}`, { headers: { accept: 'application/json' } });
|
|
79
|
+
if (res.ok) {
|
|
80
|
+
const listed = await res.json() as { services?: unknown };
|
|
81
|
+
offer = ServiceProtocolCodec.offersIn(listed).find((entry) => entry.brand === wanted.brand) ?? null;
|
|
82
|
+
} else {
|
|
83
|
+
await res.body?.cancel();
|
|
84
|
+
}
|
|
85
|
+
} catch (caught) {
|
|
86
|
+
// fallback: transient publisher listing failure caches null offer and retries after OFFER_TTL_MS
|
|
87
|
+
console.warn(`services: ${wanted.publisher} did not say what it offers`, Errors.toError(caught));
|
|
88
|
+
}
|
|
89
|
+
offersKept.set(key, { at: now, offer });
|
|
90
|
+
return offer;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private async applyDefaultOffer(
|
|
94
|
+
wanted: IDefaultService,
|
|
95
|
+
offer: IServiceOffer,
|
|
96
|
+
context: IDefaultConnectContext & { readonly upgraded: boolean; readonly started: number },
|
|
97
|
+
): Promise<void> {
|
|
98
|
+
const cacheKey = `${context.url.host}|${wanted.brand}`;
|
|
99
|
+
defaultsTried.set(cacheKey, context.now + DEFAULT_RETRY_MS);
|
|
100
|
+
let mutation: IServiceMutationSession | null = await this.host.management?.defaults(wanted) ?? null;
|
|
101
|
+
if (!mutation) {
|
|
102
|
+
throw new ServiceProtocolError({
|
|
103
|
+
appErrorType: 'SERVICE_MANAGEMENT_UNAVAILABLE',
|
|
104
|
+
message: 'A private service management adapter is required',
|
|
105
|
+
status: 501,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const made = await new ServiceConnectionClient(mutation.host).connectService(
|
|
110
|
+
{ publisher: wanted.publisher, brand: offer.brand, version: offer.version, grant: offer.grant },
|
|
111
|
+
{ url: context.url, session: context.session },
|
|
112
|
+
);
|
|
113
|
+
if (made.ok) {
|
|
114
|
+
await mutation.finish();
|
|
115
|
+
mutation = null;
|
|
116
|
+
defaultsTried.delete(cacheKey);
|
|
117
|
+
console.info(JSON.stringify({
|
|
118
|
+
tag: 'mosetta:telemetry',
|
|
119
|
+
event: 'services.defaults.connected',
|
|
120
|
+
host: context.url.host,
|
|
121
|
+
brand: wanted.brand,
|
|
122
|
+
version: offer.version,
|
|
123
|
+
upgraded: context.upgraded,
|
|
124
|
+
durationMs: Date.now() - context.started,
|
|
125
|
+
}));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const reason = (await made.text()).slice(0, 300);
|
|
129
|
+
await mutation.finish().catch(() => undefined);
|
|
130
|
+
mutation = null;
|
|
131
|
+
console.warn(JSON.stringify({
|
|
132
|
+
tag: 'mosetta:telemetry',
|
|
133
|
+
event: 'services.defaults.refused',
|
|
134
|
+
host: context.url.host,
|
|
135
|
+
brand: wanted.brand,
|
|
136
|
+
status: made.status,
|
|
137
|
+
durationMs: Date.now() - context.started,
|
|
138
|
+
reason,
|
|
139
|
+
}));
|
|
140
|
+
} catch (caught) {
|
|
141
|
+
if (mutation) {
|
|
142
|
+
await mutation.finish().catch(() => undefined);
|
|
143
|
+
}
|
|
144
|
+
throw caught;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private async connectSingleDefault(wanted: IDefaultService, context: IDefaultConnectContext): Promise<void> {
|
|
149
|
+
const started = Date.now();
|
|
150
|
+
try {
|
|
151
|
+
if ((await this.host.connections!.declined()).has(wanted.brand)) return;
|
|
152
|
+
const held = await this.host.connections!.get(wanted.brand);
|
|
153
|
+
const offer = await this.offeredNow(wanted, context.now);
|
|
154
|
+
if (!offer) {
|
|
155
|
+
if (!held) {
|
|
156
|
+
console.warn(JSON.stringify({
|
|
157
|
+
tag: 'mosetta:telemetry',
|
|
158
|
+
event: 'services.defaults.no_offer',
|
|
159
|
+
host: context.url.host,
|
|
160
|
+
brand: wanted.brand,
|
|
161
|
+
publisher: wanted.publisher,
|
|
162
|
+
durationMs: Date.now() - started,
|
|
163
|
+
}));
|
|
164
|
+
}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (held && (held.publisher !== wanted.publisher || !ServiceProtocolCodec.olderThan(held.version, offer.version))) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
await this.applyDefaultOffer(wanted, offer, { ...context, upgraded: Boolean(held), started });
|
|
171
|
+
} catch (caught) {
|
|
172
|
+
const error = Errors.toError(caught);
|
|
173
|
+
const message = `${error.name}: ${error.message}`;
|
|
174
|
+
console.warn(JSON.stringify({
|
|
175
|
+
tag: 'mosetta:telemetry',
|
|
176
|
+
event: 'services.defaults.error',
|
|
177
|
+
host: context.url.host,
|
|
178
|
+
brand: wanted.brand,
|
|
179
|
+
durationMs: Date.now() - started,
|
|
180
|
+
error: message.slice(0, 300),
|
|
181
|
+
}));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { verifyToken } from '@mosetta/host-platform/tokens';
|
|
2
|
+
import {
|
|
3
|
+
fullServerTileId,
|
|
4
|
+
HostContextCodec,
|
|
5
|
+
IDENTITY_HEADER,
|
|
6
|
+
serverActionRoute,
|
|
7
|
+
SITE_HEADER,
|
|
8
|
+
} from '@mosetta/server-action/core';
|
|
9
|
+
import { ServiceProtocolCodec } from './protocolCodec';
|
|
10
|
+
import {
|
|
11
|
+
INSTALL_ACTION,
|
|
12
|
+
INSTALLATION_KEY_PREFIX,
|
|
13
|
+
INSTALLATIONS_PATH,
|
|
14
|
+
PROOF_PREFIX,
|
|
15
|
+
SERVICE_TILE,
|
|
16
|
+
} from './protocolTypes';
|
|
17
|
+
import type {
|
|
18
|
+
IInstallation,
|
|
19
|
+
IServiceAsked,
|
|
20
|
+
IServicePerson,
|
|
21
|
+
IServicesHost,
|
|
22
|
+
} from './protocolTypes';
|
|
23
|
+
import type { IServiceTechnicalIncoming } from './serviceTechnicalIo';
|
|
24
|
+
|
|
25
|
+
interface IParsedInstallRequest {
|
|
26
|
+
readonly consumer: string;
|
|
27
|
+
readonly asked: IServiceAsked;
|
|
28
|
+
readonly grant: readonly string[];
|
|
29
|
+
readonly person: IServicePerson | null;
|
|
30
|
+
readonly proof: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface IInstallBody {
|
|
34
|
+
readonly consumer?: unknown;
|
|
35
|
+
readonly brand?: unknown;
|
|
36
|
+
readonly version?: unknown;
|
|
37
|
+
readonly grant?: unknown;
|
|
38
|
+
readonly person?: unknown;
|
|
39
|
+
readonly proof?: unknown;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Handles the public `/.well-known/mosetta/installations` handshake endpoints
|
|
44
|
+
* on both the consumer side (proof confirmation) and publisher side (install,
|
|
45
|
+
* status check, and consumer-initiated removal).
|
|
46
|
+
*/
|
|
47
|
+
export class ServiceHandshakeController {
|
|
48
|
+
constructor(private readonly host: IServicesHost) {}
|
|
49
|
+
|
|
50
|
+
async handleInstallations(request: Request): Promise<Response> {
|
|
51
|
+
const url = new URL(request.url);
|
|
52
|
+
const tail = url.pathname.slice(INSTALLATIONS_PATH.length);
|
|
53
|
+
if (request.method === 'GET' && tail.startsWith('/')) {
|
|
54
|
+
return this.confirmProof(decodeURIComponent(tail.slice(1)), url);
|
|
55
|
+
}
|
|
56
|
+
if (tail) return ServiceProtocolCodec.refusalResponse(404, 'NOT_FOUND');
|
|
57
|
+
if (request.method === 'POST') return this.install(request, url);
|
|
58
|
+
if (request.method === 'GET') return this.statusForConsumer(request);
|
|
59
|
+
if (request.method === 'DELETE') return this.removeForConsumer(request);
|
|
60
|
+
return ServiceProtocolCodec.refusalResponse(405, 'METHOD');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private async confirmProof(proof: string, url: URL): Promise<Response> {
|
|
64
|
+
if (!this.host.secret || !proof.startsWith(PROOF_PREFIX)) {
|
|
65
|
+
return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_PROOF');
|
|
66
|
+
}
|
|
67
|
+
const payload = await verifyToken(proof.slice(PROOF_PREFIX.length), this.host.secret);
|
|
68
|
+
const now = this.host.now?.() ?? new Date();
|
|
69
|
+
if (
|
|
70
|
+
!payload
|
|
71
|
+
|| payload.aud !== ServiceProtocolCodec.proofAudience(url.hostname)
|
|
72
|
+
|| typeof payload.exp !== 'number'
|
|
73
|
+
|| ServiceProtocolCodec.secondsOf(now) >= payload.exp
|
|
74
|
+
) {
|
|
75
|
+
return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_PROOF');
|
|
76
|
+
}
|
|
77
|
+
return ServiceProtocolCodec.jsonResponse(200, {
|
|
78
|
+
publisher: payload.publisher,
|
|
79
|
+
brand: payload.brand,
|
|
80
|
+
version: payload.version,
|
|
81
|
+
grant: payload.grant,
|
|
82
|
+
expiresAtMs: payload.exp * 1000,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private async findInstallationByKey(request: Request): Promise<IInstallation | null> {
|
|
87
|
+
const key = ServiceProtocolCodec.keyOfRequest(request);
|
|
88
|
+
if (!key || !this.host.installations) return null;
|
|
89
|
+
const id = ServiceProtocolCodec.installationIdOfKey(key);
|
|
90
|
+
if (!id) return null;
|
|
91
|
+
const found = await this.host.installations.byId(id);
|
|
92
|
+
if (!found) return null;
|
|
93
|
+
return found.keyHash === await ServiceProtocolCodec.hashKey(key) ? found : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private async statusForConsumer(request: Request): Promise<Response> {
|
|
97
|
+
const found = await this.findInstallationByKey(request);
|
|
98
|
+
if (!found) return ServiceProtocolCodec.refusalResponse(401, 'NOT_AN_INSTALLATION');
|
|
99
|
+
return ServiceProtocolCodec.jsonResponse(200, {
|
|
100
|
+
installation: found.id,
|
|
101
|
+
brand: found.brand,
|
|
102
|
+
version: found.version,
|
|
103
|
+
status: found.status,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private async removeForConsumer(request: Request): Promise<Response> {
|
|
108
|
+
const found = await this.findInstallationByKey(request);
|
|
109
|
+
if (!found) return ServiceProtocolCodec.refusalResponse(401, 'NOT_AN_INSTALLATION');
|
|
110
|
+
if (found.status === 'active') {
|
|
111
|
+
if (!this.host.technical) {
|
|
112
|
+
return ServiceProtocolCodec.refusalResponse(501, 'TECHNICAL_IO_UNAVAILABLE');
|
|
113
|
+
}
|
|
114
|
+
await this.host.technical.remove(found);
|
|
115
|
+
}
|
|
116
|
+
return ServiceProtocolCodec.jsonResponse(200, { ok: true });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private async parseInstallRequest(request: Request, url: URL): Promise<IParsedInstallRequest | Response> {
|
|
120
|
+
let body: IInstallBody;
|
|
121
|
+
try {
|
|
122
|
+
body = await request.json() as IInstallBody;
|
|
123
|
+
} catch {
|
|
124
|
+
// fallback: malformed JSON request body translates directly to a 400 refusal
|
|
125
|
+
return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'a JSON body');
|
|
126
|
+
}
|
|
127
|
+
const grant = ServiceProtocolCodec.grantOf(body.grant);
|
|
128
|
+
const person = ServiceProtocolCodec.personOf(body.person);
|
|
129
|
+
if (!ServiceProtocolCodec.isValidOrigin(body.consumer) || body.consumer === url.origin) {
|
|
130
|
+
return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'consumer: the connecting site\'s origin');
|
|
131
|
+
}
|
|
132
|
+
if (
|
|
133
|
+
!ServiceProtocolCodec.isValidBrand(body.brand)
|
|
134
|
+
|| !ServiceProtocolCodec.isValidVersion(body.version)
|
|
135
|
+
|| !grant
|
|
136
|
+
|| typeof body.proof !== 'string'
|
|
137
|
+
) {
|
|
138
|
+
return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'brand, version, grant and proof');
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
consumer: body.consumer,
|
|
142
|
+
asked: { publisher: url.origin, brand: body.brand, version: body.version, grant },
|
|
143
|
+
grant,
|
|
144
|
+
person,
|
|
145
|
+
proof: body.proof,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async verifyConsumerProof(parsed: IParsedInstallRequest): Promise<number | null> {
|
|
150
|
+
let confirmed: (Partial<IServiceAsked> & { expiresAtMs?: number }) | null = null;
|
|
151
|
+
try {
|
|
152
|
+
const proofUrl = `${parsed.consumer}${INSTALLATIONS_PATH}/${encodeURIComponent(parsed.proof)}`;
|
|
153
|
+
const res = await this.host.fetch(proofUrl, {
|
|
154
|
+
redirect: 'manual',
|
|
155
|
+
headers: { accept: 'application/json' },
|
|
156
|
+
});
|
|
157
|
+
confirmed = res.ok ? await res.json() as Partial<IServiceAsked> & { expiresAtMs?: number } : null;
|
|
158
|
+
} catch {
|
|
159
|
+
// fallback: unreachable consumer confirmation endpoint fails closed
|
|
160
|
+
confirmed = null;
|
|
161
|
+
}
|
|
162
|
+
const nowMs = (this.host.now?.() ?? new Date()).getTime();
|
|
163
|
+
if (
|
|
164
|
+
!confirmed
|
|
165
|
+
|| !ServiceProtocolCodec.sameAsked(parsed.asked, confirmed)
|
|
166
|
+
|| !Number.isSafeInteger(confirmed.expiresAtMs)
|
|
167
|
+
|| confirmed.expiresAtMs! <= nowMs
|
|
168
|
+
) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return confirmed.expiresAtMs!;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private async runInstallAction(
|
|
175
|
+
parsed: IParsedInstallRequest,
|
|
176
|
+
url: URL,
|
|
177
|
+
admitted: IServiceTechnicalIncoming,
|
|
178
|
+
): Promise<Response> {
|
|
179
|
+
const actionRoute = serverActionRoute(
|
|
180
|
+
fullServerTileId({ namespace: parsed.asked.brand, name: SERVICE_TILE, version: parsed.asked.version }),
|
|
181
|
+
INSTALL_ACTION,
|
|
182
|
+
);
|
|
183
|
+
const decided = await this.host.runAction!(new Request(`${url.origin}${actionRoute}`, {
|
|
184
|
+
method: 'POST',
|
|
185
|
+
headers: {
|
|
186
|
+
'content-type': 'application/json',
|
|
187
|
+
[IDENTITY_HEADER]: JSON.stringify({ via: 'service-install', site: parsed.consumer }),
|
|
188
|
+
[SITE_HEADER]: HostContextCodec.encodeSite({ origin: parsed.consumer }),
|
|
189
|
+
},
|
|
190
|
+
body: JSON.stringify({
|
|
191
|
+
consumer: parsed.consumer,
|
|
192
|
+
version: parsed.asked.version,
|
|
193
|
+
grant: parsed.grant,
|
|
194
|
+
...(parsed.person ? { person: parsed.person } : {}),
|
|
195
|
+
}),
|
|
196
|
+
}));
|
|
197
|
+
if (decided.status === 404) {
|
|
198
|
+
await decided.body?.cancel();
|
|
199
|
+
await admitted.refuse();
|
|
200
|
+
return ServiceProtocolCodec.refusalResponse(
|
|
201
|
+
404,
|
|
202
|
+
'SERVICE_NOT_OFFERED',
|
|
203
|
+
`${parsed.asked.brand}@${parsed.asked.version} is not offered as a service here`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
const verdict = await decided.json().catch(() => null) as { ok?: unknown; message?: unknown } | null;
|
|
207
|
+
if (!decided.ok || verdict?.ok !== true) {
|
|
208
|
+
if (decided.ok || (decided.status >= 400 && decided.status < 500)) await admitted.refuse();
|
|
209
|
+
else await admitted.uncertain();
|
|
210
|
+
const reason = typeof verdict?.message === 'string'
|
|
211
|
+
? verdict.message.slice(0, 300)
|
|
212
|
+
: 'the publisher does not serve this site';
|
|
213
|
+
return ServiceProtocolCodec.refusalResponse(403, 'INSTALL_REFUSED', reason);
|
|
214
|
+
}
|
|
215
|
+
const id = `ins_${crypto.randomUUID().replace(/-/g, '')}`;
|
|
216
|
+
const key = `${INSTALLATION_KEY_PREFIX}${id}.${ServiceProtocolCodec.randomSecret()}`;
|
|
217
|
+
await admitted.create({
|
|
218
|
+
id,
|
|
219
|
+
keyHash: await ServiceProtocolCodec.hashKey(key),
|
|
220
|
+
consumer: parsed.consumer,
|
|
221
|
+
brand: parsed.asked.brand,
|
|
222
|
+
version: parsed.asked.version,
|
|
223
|
+
grant: parsed.grant,
|
|
224
|
+
person: parsed.person,
|
|
225
|
+
status: 'active',
|
|
226
|
+
createdAt: (this.host.now?.() ?? new Date()).toISOString(),
|
|
227
|
+
});
|
|
228
|
+
return ServiceProtocolCodec.jsonResponse(200, { installation: id, key });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private async install(request: Request, url: URL): Promise<Response> {
|
|
232
|
+
if (!this.host.installations || !this.host.runAction) {
|
|
233
|
+
return ServiceProtocolCodec.refusalResponse(404, 'NO_SERVICES_HERE', 'this site offers no services');
|
|
234
|
+
}
|
|
235
|
+
const parsed = await this.parseInstallRequest(request, url);
|
|
236
|
+
if (parsed instanceof Response) return parsed;
|
|
237
|
+
const expiresAtMs = await this.verifyConsumerProof(parsed);
|
|
238
|
+
if (expiresAtMs === null) {
|
|
239
|
+
return ServiceProtocolCodec.refusalResponse(403, 'NOT_CONFIRMED', 'the connecting site did not confirm the request');
|
|
240
|
+
}
|
|
241
|
+
if (!this.host.technical) {
|
|
242
|
+
return ServiceProtocolCodec.refusalResponse(501, 'TECHNICAL_IO_UNAVAILABLE');
|
|
243
|
+
}
|
|
244
|
+
const admitted = await this.host.technical.incoming({
|
|
245
|
+
consumer: parsed.consumer,
|
|
246
|
+
...parsed.asked,
|
|
247
|
+
proof: parsed.proof,
|
|
248
|
+
expiresAtMs,
|
|
249
|
+
});
|
|
250
|
+
try {
|
|
251
|
+
return await this.runInstallAction(parsed, url, admitted);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
await admitted.uncertain();
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|