@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mosetta contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mosetta/services",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.0.9",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Portable Mosetta cross-site services protocol: installation handshake, sealed connections, action forwarding, grant filtering, and SQL-guarded service IO.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"files": [
|
|
8
|
+
"src"
|
|
9
|
+
],
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./src/services.ts",
|
|
12
|
+
"./protocol": "./src/protocolEntry.ts"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@mosetta/auth-service": "0.0.9",
|
|
16
|
+
"@mosetta/core": "0.0.44",
|
|
17
|
+
"@mosetta/content": "0.0.44",
|
|
18
|
+
"@mosetta/host-platform": "0.0.9",
|
|
19
|
+
"@mosetta/identity": "0.0.44",
|
|
20
|
+
"@mosetta/media": "0.0.9",
|
|
21
|
+
"@mosetta/server-action": "0.0.44",
|
|
22
|
+
"@mosetta/server": "0.0.44",
|
|
23
|
+
"@mosetta/tenancy": "0.0.44"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/mosetta/mosetta.git",
|
|
28
|
+
"directory": "packages/services"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"typecheck": "tsc --noEmit"
|
|
35
|
+
}
|
|
6
36
|
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { AppError } from '@mosetta/core';
|
|
2
|
+
import type { IAppErrorOptions, TAppErrorExposure } from '@mosetta/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Base error for all domain exceptions raised by `@mosetta/services`.
|
|
6
|
+
* Always carries a stable `appErrorType` tag and boundary exposure metadata.
|
|
7
|
+
*/
|
|
8
|
+
export abstract class ServiceError extends AppError {
|
|
9
|
+
protected constructor(options: IAppErrorOptions) {
|
|
10
|
+
super(options);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Raised when a human service call targets a publisher that is not a trusted
|
|
16
|
+
* same-installation project available over the private bridge.
|
|
17
|
+
*/
|
|
18
|
+
export class ExternalServiceUnavailableError extends ServiceError {
|
|
19
|
+
constructor(parentError?: Error) {
|
|
20
|
+
super({
|
|
21
|
+
appErrorType: 'PRIVATE_SERVICE_UNAVAILABLE',
|
|
22
|
+
message: 'Human service calls require a trusted same-installation publisher.',
|
|
23
|
+
status: 501,
|
|
24
|
+
exposure: 'public',
|
|
25
|
+
parentError,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Options for constructing a `ServiceProtocolError`. */
|
|
31
|
+
export interface IServiceProtocolErrorOptions {
|
|
32
|
+
readonly appErrorType?: string;
|
|
33
|
+
readonly message: string;
|
|
34
|
+
readonly status?: number;
|
|
35
|
+
readonly exposure?: TAppErrorExposure;
|
|
36
|
+
readonly publicMessage?: string;
|
|
37
|
+
readonly retryable?: boolean;
|
|
38
|
+
readonly details?: Readonly<Record<string, unknown>>;
|
|
39
|
+
readonly parentError?: Error;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Raised for service protocol, handshake, or management-adapter invariant failures
|
|
44
|
+
* that are not represented as HTTP refusal responses.
|
|
45
|
+
*/
|
|
46
|
+
export class ServiceProtocolError extends ServiceError {
|
|
47
|
+
constructor(options: IServiceProtocolErrorOptions) {
|
|
48
|
+
super({
|
|
49
|
+
appErrorType: options.appErrorType ?? 'SERVICE_PROTOCOL_ERROR',
|
|
50
|
+
message: options.message,
|
|
51
|
+
status: options.status ?? 500,
|
|
52
|
+
exposure: options.exposure ?? 'internal',
|
|
53
|
+
publicMessage: options.publicMessage,
|
|
54
|
+
retryable: options.retryable,
|
|
55
|
+
details: options.details,
|
|
56
|
+
parentError: options.parentError,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { IdentityError } from '@mosetta/identity';
|
|
2
|
+
import type { AccessPassVerifier } from '@mosetta/identity';
|
|
3
|
+
import type { IHostInvocationIdentity, IRootSourceAdmission, IRootSourcePolicies, IRootSourcePolicyPort } from '@mosetta/host-platform/bridges';
|
|
4
|
+
import { ProjectPermissionCatalogues } from '@mosetta/host-platform/permissions';
|
|
5
|
+
import { providersFor } from '@mosetta/host-platform/platform';
|
|
6
|
+
import { apiOriginOf, subdomainOf, withApiInternalSecret } from '@mosetta/host-platform/host-wiring';
|
|
7
|
+
import type { IPortablePlatformConfig } from '@mosetta/host-platform/wiring';
|
|
8
|
+
import { databaseOf } from '@mosetta/server-action/server';
|
|
9
|
+
import type { IDatabaseRpc } from '@mosetta/server-action/server';
|
|
10
|
+
import { SqlProjectResourceCatalogues, SqlRegistry } from '@mosetta/tenancy';
|
|
11
|
+
import type { IProjectRecord, ISqlDatabase } from '@mosetta/tenancy';
|
|
12
|
+
import { SealedServiceConnections } from './protocol';
|
|
13
|
+
import type { IInstallations, IServiceManagementPort, IServicesHost } from './protocol';
|
|
14
|
+
import type { IServiceHostRuntime } from './serviceHost';
|
|
15
|
+
import { GuardedServiceInstallations } from './serviceInstallationsIo';
|
|
16
|
+
import type { TServiceRun } from './serviceInvocation';
|
|
17
|
+
import { serviceManagementOf } from './serviceManagementIo';
|
|
18
|
+
import { RootServiceTechnical } from './serviceTechnicalIo';
|
|
19
|
+
import type { IServiceTechnicalPort } from './serviceTechnicalIo';
|
|
20
|
+
|
|
21
|
+
/** Options for `portableServiceTechnicalOf`. */
|
|
22
|
+
export interface IPortableServiceTechnicalOptions {
|
|
23
|
+
readonly projectId: string;
|
|
24
|
+
readonly origin: string;
|
|
25
|
+
readonly scheme?: 'http' | 'https';
|
|
26
|
+
readonly platform: () => Pick<IPortablePlatformConfig, 'sessionSecret' | 'projectsDomain'>;
|
|
27
|
+
readonly primary: () => ISqlDatabase | null;
|
|
28
|
+
readonly internal: (projectId: string) => IDatabaseRpc | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Options for `portableServiceManagementOf`. */
|
|
32
|
+
export interface IPortableServiceManagementOptions {
|
|
33
|
+
readonly identity: IHostInvocationIdentity;
|
|
34
|
+
readonly projectId: string;
|
|
35
|
+
readonly host: IServicesHost;
|
|
36
|
+
readonly scheme?: 'http' | 'https';
|
|
37
|
+
readonly platform: () => Pick<IPortablePlatformConfig, 'secrets' | 'storeTemplate' | 'projectsDomain' | 'registry'>;
|
|
38
|
+
readonly database: () => ISqlDatabase | null;
|
|
39
|
+
readonly internal: (projectId: string) => IDatabaseRpc | null;
|
|
40
|
+
readonly verifier: () => AccessPassVerifier;
|
|
41
|
+
readonly ttlMs: () => number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Options for `createPlatformServiceHostRuntime`. */
|
|
45
|
+
export interface IPlatformServiceHostRuntimeOptions {
|
|
46
|
+
readonly platform: IPortablePlatformConfig;
|
|
47
|
+
readonly internalSecret: string | undefined;
|
|
48
|
+
readonly sourcePolicies?: IRootSourcePolicies;
|
|
49
|
+
readonly contentSourcePolicy?: () => IRootSourcePolicyPort | undefined;
|
|
50
|
+
readonly internalDatabase: (projectId: string) => IDatabaseRpc | null;
|
|
51
|
+
readonly scheme?: 'http' | 'https';
|
|
52
|
+
readonly clientIpHeader?: string;
|
|
53
|
+
readonly serveService: (request: Request, publisher: IProjectRecord, admit: (request: Request, run: TServiceRun) => Promise<Response>) => Promise<Response>;
|
|
54
|
+
readonly serveReentry: (request: Request, content?: IRootSourceAdmission) => Promise<Response>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function parseSharedOriginSubdomain(origin: string, projectsDomain: string, scheme: 'http' | 'https'): string | null {
|
|
58
|
+
const url = new URL(origin);
|
|
59
|
+
const suffix = `.${projectsDomain}`;
|
|
60
|
+
if (url.origin !== origin || url.protocol !== `${scheme}:` || url.port || !url.hostname.endsWith(suffix)) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return url.hostname.slice(0, -suffix.length);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isSharedActiveProject(
|
|
67
|
+
actual: IProjectRecord | null,
|
|
68
|
+
expectedOrigin: string,
|
|
69
|
+
domain: { readonly scheme: 'http' | 'https'; readonly projectsDomain: string },
|
|
70
|
+
): actual is IProjectRecord {
|
|
71
|
+
return Boolean(
|
|
72
|
+
actual
|
|
73
|
+
&& actual.mode === 'shared'
|
|
74
|
+
&& actual.status === 'active'
|
|
75
|
+
&& actual.ready === true
|
|
76
|
+
&& `${domain.scheme}://${actual.subdomain}.${domain.projectsDomain}` === expectedOrigin,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Existing rows only; normal technical reads never create or migrate INTERNAL tables. */
|
|
81
|
+
export function portableServiceInstallationsOf(
|
|
82
|
+
openInternal: (projectId: string) => IDatabaseRpc | null,
|
|
83
|
+
projectId: string,
|
|
84
|
+
): IInstallations {
|
|
85
|
+
const read = (): GuardedServiceInstallations => {
|
|
86
|
+
const database = openInternal(projectId);
|
|
87
|
+
if (!database) throw new IdentityError('INVALID_CONFIG');
|
|
88
|
+
return new GuardedServiceInstallations(databaseOf(database), {
|
|
89
|
+
step: () => Promise.reject(new IdentityError('FORBIDDEN')),
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
byId: (id) => read().byId(id),
|
|
94
|
+
list: () => read().list(),
|
|
95
|
+
create: () => Promise.reject(new IdentityError('FORBIDDEN')),
|
|
96
|
+
setStatus: () => Promise.reject(new IdentityError('FORBIDDEN')),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Lazy event-local Root adapter; public SSR neither opens SQL nor reads a technical key. */
|
|
101
|
+
export function portableServiceTechnicalOf(options: IPortableServiceTechnicalOptions): IServiceTechnicalPort {
|
|
102
|
+
let selected: RootServiceTechnical | null = null;
|
|
103
|
+
const scheme = options.scheme ?? 'https';
|
|
104
|
+
const configured = (): RootServiceTechnical => {
|
|
105
|
+
if (selected) return selected;
|
|
106
|
+
const platform = options.platform();
|
|
107
|
+
const primary = options.primary();
|
|
108
|
+
const internal = options.internal(options.projectId);
|
|
109
|
+
if (!primary || !internal) throw new IdentityError('INVALID_CONFIG');
|
|
110
|
+
const registry = new SqlRegistry(primary);
|
|
111
|
+
const catalogues = new SqlProjectResourceCatalogues(primary);
|
|
112
|
+
selected = new RootServiceTechnical({
|
|
113
|
+
primary,
|
|
114
|
+
internal: databaseOf(internal),
|
|
115
|
+
projectId: options.projectId,
|
|
116
|
+
origin: options.origin,
|
|
117
|
+
secret: platform.sessionSecret,
|
|
118
|
+
project: async (asked) => {
|
|
119
|
+
const subdomain = parseSharedOriginSubdomain(asked, platform.projectsDomain, scheme);
|
|
120
|
+
if (subdomain === null) return null;
|
|
121
|
+
const actual = await registry.bySubdomain(subdomain);
|
|
122
|
+
if (!isSharedActiveProject(actual, asked, { scheme, projectsDomain: platform.projectsDomain })) {
|
|
123
|
+
throw new IdentityError('FORBIDDEN');
|
|
124
|
+
}
|
|
125
|
+
const source = await catalogues.source(actual.id);
|
|
126
|
+
if (source.project.status !== 'active' || source.project.ready !== true || !source.sourceKey) {
|
|
127
|
+
throw new IdentityError('FORBIDDEN');
|
|
128
|
+
}
|
|
129
|
+
return { id: actual.id, sourceKey: source.sourceKey, generation: source.sourceGeneration };
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
return selected;
|
|
133
|
+
};
|
|
134
|
+
return {
|
|
135
|
+
outgoing: (input) => configured().outgoing(input),
|
|
136
|
+
incoming: (input) => configured().incoming(input),
|
|
137
|
+
remove: (installation) => configured().remove(installation),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Fresh Root event adapter for service management mutations without implicit migrations. */
|
|
142
|
+
export function portableServiceManagementOf(options: IPortableServiceManagementOptions): IServiceManagementPort {
|
|
143
|
+
let selected: IServiceManagementPort | null = null;
|
|
144
|
+
const scheme = options.scheme ?? 'https';
|
|
145
|
+
const configured = (): IServiceManagementPort => {
|
|
146
|
+
if (selected) return selected;
|
|
147
|
+
const platform = options.platform();
|
|
148
|
+
const database = options.database();
|
|
149
|
+
const internal = options.internal(options.projectId);
|
|
150
|
+
if (!database || !internal || !platform.secrets) throw new IdentityError('INVALID_CONFIG');
|
|
151
|
+
const ttlMs = options.ttlMs();
|
|
152
|
+
selected = serviceManagementOf(options.identity, {
|
|
153
|
+
database,
|
|
154
|
+
internal: databaseOf(internal),
|
|
155
|
+
projectId: options.projectId,
|
|
156
|
+
host: options.host,
|
|
157
|
+
secrets: platform.secrets,
|
|
158
|
+
verifier: options.verifier(),
|
|
159
|
+
ttlMs,
|
|
160
|
+
providers: (project) => providersFor(platform.storeTemplate, project),
|
|
161
|
+
permissions: new ProjectPermissionCatalogues(fetch, Date.now, ttlMs),
|
|
162
|
+
publisher: async (origin) => {
|
|
163
|
+
const subdomain = parseSharedOriginSubdomain(origin, platform.projectsDomain, scheme);
|
|
164
|
+
if (subdomain === null) return null;
|
|
165
|
+
const actual = await platform.registry.bySubdomain(subdomain);
|
|
166
|
+
return isSharedActiveProject(actual, origin, { scheme, projectsDomain: platform.projectsDomain }) ? actual : null;
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
return selected;
|
|
170
|
+
};
|
|
171
|
+
return {
|
|
172
|
+
human: (request) => configured().human(request),
|
|
173
|
+
defaults: (wanted) => configured().defaults(wanted),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Portable builder for IServiceHostRuntime used by ServiceInvocation and ServiceCallback entrypoints. */
|
|
178
|
+
export function createPlatformServiceHostRuntime(options: IPlatformServiceHostRuntimeOptions): IServiceHostRuntime {
|
|
179
|
+
const { platform } = options;
|
|
180
|
+
const scheme = options.scheme ?? 'https';
|
|
181
|
+
const expectedProtocol = `${scheme}:`;
|
|
182
|
+
const origin = (project: IProjectRecord): string => `${scheme}://${project.subdomain}.${platform.projectsDomain}`;
|
|
183
|
+
const api = apiOriginOf(platform, scheme);
|
|
184
|
+
return {
|
|
185
|
+
sourcePolicies: options.sourcePolicies,
|
|
186
|
+
contentSourcePolicy: {
|
|
187
|
+
bind: (target, slot) => options.contentSourcePolicy?.()?.bind(target, slot) ?? Promise.resolve(null),
|
|
188
|
+
},
|
|
189
|
+
registry: platform.registry,
|
|
190
|
+
apiOrigin: api,
|
|
191
|
+
clientIpHeader: options.clientIpHeader,
|
|
192
|
+
project: async (value) => {
|
|
193
|
+
const url = new URL(value);
|
|
194
|
+
if (url.origin !== value || url.protocol !== expectedProtocol || url.port) return null;
|
|
195
|
+
const subdomain = subdomainOf(url.hostname, platform.projectsDomain);
|
|
196
|
+
const project = subdomain ? await platform.registry.bySubdomain(subdomain) : null;
|
|
197
|
+
return project && origin(project) === value ? project : null;
|
|
198
|
+
},
|
|
199
|
+
origin,
|
|
200
|
+
connections: (project) => {
|
|
201
|
+
if (!platform.secrets) throw new IdentityError('INVALID_CONFIG');
|
|
202
|
+
return new SealedServiceConnections({ values: platform.secrets, projectId: project.id });
|
|
203
|
+
},
|
|
204
|
+
installations: (project) => {
|
|
205
|
+
const database = options.internalDatabase(project.id);
|
|
206
|
+
if (!database) throw new IdentityError('INVALID_CONFIG');
|
|
207
|
+
return portableServiceInstallationsOf(options.internalDatabase, project.id);
|
|
208
|
+
},
|
|
209
|
+
publisher: (request, publisher, admit) => options.serveService(request, publisher, admit),
|
|
210
|
+
forward: (request, content) => {
|
|
211
|
+
const url = new URL(request.url);
|
|
212
|
+
if (api && platform.api && url.origin === api) {
|
|
213
|
+
return platform.api.fetch(withApiInternalSecret(request, options.internalSecret));
|
|
214
|
+
}
|
|
215
|
+
if (url.protocol !== expectedProtocol || url.port || subdomainOf(url.hostname, platform.projectsDomain) === null) {
|
|
216
|
+
return Promise.reject(new IdentityError('FORBIDDEN'));
|
|
217
|
+
}
|
|
218
|
+
return options.serveReentry(request, content);
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from './protocolTypes';
|
|
2
|
+
export { ServiceProtocolCodec } from './protocolCodec';
|
|
3
|
+
export { CONNECTION_NAMES_TTL_MS, SealedServiceConnections, SqlServiceInstallations } from './serviceStores';
|
|
4
|
+
export type { ISealedServiceConnectionsOptions } from './serviceStores';
|
|
5
|
+
export { ServiceConnectionClient } from './serviceConnectionClient';
|
|
6
|
+
export { ServiceHandshakeController } from './serviceHandshakeController';
|
|
7
|
+
export { ServiceManagementController } from './serviceManagementController';
|
|
8
|
+
export type { IServiceConnectContext, IServiceManagementAuth } from './serviceManagementController';
|
|
9
|
+
export { ServiceDefaultsCoordinator } from './serviceDefaultsCoordinator';
|
|
10
|
+
export type { IConnectDefaultsOptions } from './serviceDefaultsCoordinator';
|
|
11
|
+
export { ServiceProxyClient } from './serviceProxyClient';
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { workbenchRolesOf } from '@mosetta/content/workbench';
|
|
2
|
+
import type { IServiceConnection } from '@mosetta/host-platform/host';
|
|
3
|
+
import { GRANT_MAX } from './protocolTypes';
|
|
4
|
+
import type {
|
|
5
|
+
IInstallation,
|
|
6
|
+
IServiceActionAddress,
|
|
7
|
+
IServiceAsked,
|
|
8
|
+
IServiceOffer,
|
|
9
|
+
IServicePerson,
|
|
10
|
+
} from './protocolTypes';
|
|
11
|
+
|
|
12
|
+
const ORIGIN_RE = /^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;
|
|
13
|
+
const BRAND_RE = /^[a-z][a-z0-9-]{0,54}$/;
|
|
14
|
+
const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]{1,40})?$/;
|
|
15
|
+
const GRANT_RE = /^(?:@(?:previews|media|code|repositories)|[a-z][a-z0-9-]{0,62}(?:\/[a-z][A-Za-z0-9]{0,63})?)$/;
|
|
16
|
+
const ACTION_RE = /^\/api\/server-action\/(_ns_([a-z0-9-]+)_t_server_n_([A-Za-z0-9]+)_v_[A-Za-z0-9_]+)\/([A-Za-z0-9_]+)$/;
|
|
17
|
+
const MODULE_RE = /^_ns_([a-z0-9-]+)_t_server_n_([A-Za-z0-9]+)_v_/;
|
|
18
|
+
const KEY_ID_RE = /^msi_(ins_[a-f0-9]{32})\.[A-Za-z0-9_-]{32,}$/;
|
|
19
|
+
const BEARER_KEY_RE = /^Bearer\s+(msi_\S+)$/i;
|
|
20
|
+
|
|
21
|
+
export const CONNECTION_SECRET_PREFIX = 'SERVICE_';
|
|
22
|
+
export const DECLINED_SECRET_PREFIX = 'NO_SERVICE_';
|
|
23
|
+
|
|
24
|
+
function toHex(bytes: ArrayBuffer): string {
|
|
25
|
+
return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Pure encoding, parsing, validation, and cryptographic helpers for the
|
|
30
|
+
* cross-site services protocol.
|
|
31
|
+
*/
|
|
32
|
+
export class ServiceProtocolCodec {
|
|
33
|
+
private static parseOfferEntry(service: Record<string, unknown>): IServiceOffer | null {
|
|
34
|
+
const grant = ServiceProtocolCodec.grantOf(service.grant);
|
|
35
|
+
if (
|
|
36
|
+
!ServiceProtocolCodec.isValidBrand(service.brand)
|
|
37
|
+
|| !ServiceProtocolCodec.isValidVersion(service.version)
|
|
38
|
+
|| !grant
|
|
39
|
+
) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const roles = workbenchRolesOf(service.workbench);
|
|
43
|
+
return {
|
|
44
|
+
brand: service.brand,
|
|
45
|
+
version: service.version,
|
|
46
|
+
title: typeof service.title === 'string' ? service.title.slice(0, 200) : service.brand,
|
|
47
|
+
...(typeof service.description === 'string' ? { description: service.description.slice(0, 2000) } : {}),
|
|
48
|
+
grant,
|
|
49
|
+
...(roles ? { workbench: roles } : {}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
static actionOfPath(pathname: string): IServiceActionAddress | null {
|
|
54
|
+
const match = ACTION_RE.exec(pathname);
|
|
55
|
+
return match
|
|
56
|
+
? { fullId: match[1], brand: match[2], tile: match[3], action: match[4] }
|
|
57
|
+
: null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static grantAllows(grant: readonly string[], brand: string, tile: string): boolean {
|
|
61
|
+
return grant.includes(brand) || grant.includes(`${brand}/${tile}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static grantOf(value: unknown): string[] | null {
|
|
65
|
+
if (
|
|
66
|
+
!Array.isArray(value)
|
|
67
|
+
|| value.length > GRANT_MAX
|
|
68
|
+
|| !value.every((entry): entry is string => typeof entry === 'string' && GRANT_RE.test(entry))
|
|
69
|
+
) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return [...new Set(value)];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
static isValidOrigin(value: unknown): value is string {
|
|
76
|
+
return typeof value === 'string' && ORIGIN_RE.test(value);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static isValidBrand(value: unknown): value is string {
|
|
80
|
+
return typeof value === 'string' && BRAND_RE.test(value);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
static isValidVersion(value: unknown): value is string {
|
|
84
|
+
return typeof value === 'string' && VERSION_RE.test(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
static personOf(value: unknown): IServicePerson | null {
|
|
88
|
+
const raw = value as Partial<IServicePerson> | null;
|
|
89
|
+
if (
|
|
90
|
+
!raw
|
|
91
|
+
|| typeof raw !== 'object'
|
|
92
|
+
|| typeof raw.id !== 'string'
|
|
93
|
+
|| !raw.id
|
|
94
|
+
|| typeof raw.via !== 'string'
|
|
95
|
+
|| typeof raw.login !== 'string'
|
|
96
|
+
|| !raw.login
|
|
97
|
+
) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
id: raw.id.slice(0, 100),
|
|
102
|
+
via: raw.via.slice(0, 40),
|
|
103
|
+
login: raw.login.slice(0, 100),
|
|
104
|
+
...(typeof raw.email === 'string' ? { email: raw.email.slice(0, 200) } : {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
static connectionOf(raw: string | null): IServiceConnection | null {
|
|
109
|
+
if (!raw) return null;
|
|
110
|
+
try {
|
|
111
|
+
const parsed = JSON.parse(raw) as Partial<IServiceConnection>;
|
|
112
|
+
const grant = ServiceProtocolCodec.grantOf(parsed.grant);
|
|
113
|
+
if (
|
|
114
|
+
typeof parsed.brand !== 'string'
|
|
115
|
+
|| typeof parsed.publisher !== 'string'
|
|
116
|
+
|| typeof parsed.installation !== 'string'
|
|
117
|
+
|| typeof parsed.key !== 'string'
|
|
118
|
+
|| !grant
|
|
119
|
+
) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
const roles = workbenchRolesOf(parsed.workbench);
|
|
123
|
+
return {
|
|
124
|
+
brand: parsed.brand,
|
|
125
|
+
publisher: parsed.publisher,
|
|
126
|
+
installation: parsed.installation,
|
|
127
|
+
key: parsed.key,
|
|
128
|
+
version: String(parsed.version ?? ''),
|
|
129
|
+
grant,
|
|
130
|
+
at: String(parsed.at ?? ''),
|
|
131
|
+
by: String(parsed.by ?? ''),
|
|
132
|
+
...(roles ? { workbench: roles } : {}),
|
|
133
|
+
};
|
|
134
|
+
} catch {
|
|
135
|
+
// fallback: malformed sealed JSON entry is treated as absent rather than crashing lookup
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
static offersIn(listed: { readonly services?: unknown }): IServiceOffer[] {
|
|
141
|
+
if (!Array.isArray(listed.services)) return [];
|
|
142
|
+
const offers: IServiceOffer[] = [];
|
|
143
|
+
for (const entry of listed.services as Record<string, unknown>[]) {
|
|
144
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
145
|
+
const offer = ServiceProtocolCodec.parseOfferEntry(entry);
|
|
146
|
+
if (offer) offers.push(offer);
|
|
147
|
+
}
|
|
148
|
+
return offers;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
static sameAsked(a: IServiceAsked, b: Partial<IServiceAsked>): boolean {
|
|
152
|
+
return a.publisher === b.publisher
|
|
153
|
+
&& a.brand === b.brand
|
|
154
|
+
&& a.version === b.version
|
|
155
|
+
&& Array.isArray(b.grant)
|
|
156
|
+
&& a.grant.length === b.grant.length
|
|
157
|
+
&& a.grant.every((item, index) => b.grant?.[index] === item);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
static olderThan(a: string, b: string): boolean {
|
|
161
|
+
const [left, right] = [a, b].map((ver) => ver.split(/[-+]/)[0].split('.').map(Number));
|
|
162
|
+
for (let index = 0; index < 3; index += 1) {
|
|
163
|
+
if ((left[index] ?? 0) !== (right[index] ?? 0)) {
|
|
164
|
+
return (left[index] ?? 0) < (right[index] ?? 0);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
static proofAudience(hostname: string): string {
|
|
171
|
+
return `service-proof:${hostname.toLowerCase()}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
static keyOfRequest(request: Request): string | null {
|
|
175
|
+
return BEARER_KEY_RE.exec(request.headers.get('authorization') ?? '')?.[1] ?? null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
static installationIdOfKey(key: string): string | null {
|
|
179
|
+
return KEY_ID_RE.exec(key)?.[1] ?? null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
static async hashKey(key: string): Promise<string> {
|
|
183
|
+
return toHex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key)));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
static randomSecret(): string {
|
|
187
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
188
|
+
return btoa(String.fromCharCode(...bytes))
|
|
189
|
+
.replace(/\+/g, '-')
|
|
190
|
+
.replace(/\//g, '_')
|
|
191
|
+
.replace(/=+$/, '');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
static secondsOf(now: Date): number {
|
|
195
|
+
return Math.floor(now.getTime() / 1000);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
static jsonResponse(status: number, body: unknown): Response {
|
|
199
|
+
return new Response(JSON.stringify(body), {
|
|
200
|
+
status,
|
|
201
|
+
headers: {
|
|
202
|
+
'content-type': 'application/json; charset=utf-8',
|
|
203
|
+
'cache-control': 'no-store',
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
static refusalResponse(status: number, code: string, message?: string): Response {
|
|
209
|
+
return ServiceProtocolCodec.jsonResponse(status, {
|
|
210
|
+
error: { code, ...(message ? { message } : {}) },
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
static shownInstallation(installation: IInstallation): Omit<IInstallation, 'keyHash'> {
|
|
215
|
+
const { keyHash: _hash, ...shown } = installation;
|
|
216
|
+
return shown;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
static brandSecretName(brand: string): string {
|
|
220
|
+
return `${CONNECTION_SECRET_PREFIX}${brand.toUpperCase().replace(/-/g, '_')}`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
static declinedSecretName(brand: string): string {
|
|
224
|
+
return `${DECLINED_SECRET_PREFIX}${brand.toUpperCase().replace(/-/g, '_')}`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
static async grantedListing(response: Response, grant: readonly string[]): Promise<Response> {
|
|
228
|
+
if (!response.ok) return response;
|
|
229
|
+
const listed = await response.json().catch(() => null) as { modules?: { module?: unknown }[] } | null;
|
|
230
|
+
const modules = (listed?.modules ?? []).filter((entry) => {
|
|
231
|
+
const match = typeof entry.module === 'string' ? MODULE_RE.exec(entry.module) : null;
|
|
232
|
+
return match ? ServiceProtocolCodec.grantAllows(grant, match[1], match[2]) : false;
|
|
233
|
+
});
|
|
234
|
+
return ServiceProtocolCodec.jsonResponse(200, { ...listed, modules });
|
|
235
|
+
}
|
|
236
|
+
}
|