@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 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.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.10",
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.10",
16
+ "@mosetta/content": "0.0.45",
17
+ "@mosetta/host-platform": "0.0.10",
18
+ "@mosetta/core": "0.0.45",
19
+ "@mosetta/identity": "0.0.45",
20
+ "@mosetta/media": "0.0.10",
21
+ "@mosetta/server": "0.0.45",
22
+ "@mosetta/tenancy": "0.0.45",
23
+ "@mosetta/server-action": "0.0.45"
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
  }
@@ -0,0 +1,71 @@
1
+ // Pure-JS synchronous SHA-256 and collision-free secret key suffix derivation for npm package brands.
2
+ const K = [
3
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
4
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
5
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
6
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
7
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
8
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
9
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
10
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
11
+ ];
12
+ const H0 = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
13
+ const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
14
+ const SIMPLE_BRAND_RE = /^[a-z0-9-]{1,53}$/;
15
+ const encoder = new TextEncoder();
16
+ const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));
17
+
18
+ function sha256(input: Uint8Array): Uint8Array {
19
+ const paddedLen = Math.ceil((input.length + 9) / 64) * 64;
20
+ const padded = new Uint8Array(paddedLen);
21
+ padded.set(input);
22
+ padded[input.length] = 0x80;
23
+ const view = new DataView(padded.buffer);
24
+ view.setUint32(paddedLen - 8, Math.floor(input.length / 0x20000000), false);
25
+ view.setUint32(paddedLen - 4, (input.length * 8) >>> 0, false);
26
+ const h = [...H0];
27
+ const w = new Int32Array(64);
28
+ for (let offset = 0; offset < paddedLen; offset += 64) {
29
+ for (let i = 0; i < 16; i += 1) w[i] = view.getInt32(offset + i * 4, false);
30
+ for (let i = 16; i < 64; i += 1) {
31
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
32
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
33
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
34
+ }
35
+ let [a, b, c, d, e, f, g, hh] = h;
36
+ for (let i = 0; i < 64; i += 1) {
37
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
38
+ const ch = (e & f) ^ (~e & g);
39
+ const t1 = (hh + S1 + ch + K[i] + w[i]) | 0;
40
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
41
+ const maj = (a & b) ^ (a & c) ^ (b & c);
42
+ const t2 = (S0 + maj) | 0;
43
+ hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
44
+ }
45
+ const next = [a, b, c, d, e, f, g, hh];
46
+ for (let i = 0; i < 8; i += 1) h[i] = (h[i] + next[i]) | 0;
47
+ }
48
+ const out = new Uint8Array(32);
49
+ const outView = new DataView(out.buffer);
50
+ for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, h[i] >>> 0, false);
51
+ return out;
52
+ }
53
+
54
+ function base32Of20(bytes: Uint8Array): string {
55
+ let out = '';
56
+ for (let i = 0; i < 20; i += 5) {
57
+ const [b0, b1, b2, b3, b4] = [bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3], bytes[i + 4]];
58
+ out += BASE32[b0 >> 3] + BASE32[((b0 & 7) << 2) | (b1 >> 6)] + BASE32[(b1 >> 1) & 31]
59
+ + BASE32[((b1 & 1) << 4) | (b2 >> 4)] + BASE32[((b2 & 15) << 1) | (b3 >> 7)]
60
+ + BASE32[(b3 >> 2) & 31] + BASE32[((b3 & 3) << 3) | (b4 >> 5)] + BASE32[b4 & 31];
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** Collision-free uppercase secret key suffix (`<= 53` chars) for any valid npm package brand. */
66
+ export function brandSecretSuffix(brand: string): string {
67
+ if (SIMPLE_BRAND_RE.test(brand)) return brand.replace(/-/g, '_').toUpperCase();
68
+ const slug = brand.replace(/^@/, '').replace(/[^a-z0-9]+/gi, '_').replace(/^_+|_+$/g, '').toUpperCase().slice(0, 18);
69
+ const hash = base32Of20(sha256(encoder.encode(brand)));
70
+ return slug ? `_${slug}_${hash}` : `_${hash}`;
71
+ }
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
+ }
@@ -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';