@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.
@@ -0,0 +1,214 @@
1
+ import type { IServiceConnection } from '@mosetta/host-platform/host';
2
+ import type { IDatabaseRpc } from '@mosetta/server-action/server';
3
+ import {
4
+ CONNECTION_SECRET_PREFIX,
5
+ DECLINED_SECRET_PREFIX,
6
+ ServiceProtocolCodec,
7
+ } from './protocolCodec';
8
+ import type { IHeldValues, IInstallation, IInstallations, IServiceConnections } from './protocolTypes';
9
+
10
+ /** How long an isolate believes which services a site takes — every action call asks. */
11
+ export const CONNECTION_NAMES_TTL_MS = 15_000;
12
+
13
+ const namesKept = new Map<string, { at: number; names: Set<string> }>();
14
+
15
+ const INSTALLATIONS_TABLE = `CREATE TABLE IF NOT EXISTS mosetta_installations (
16
+ id TEXT PRIMARY KEY,
17
+ key_hash TEXT NOT NULL,
18
+ consumer TEXT NOT NULL,
19
+ brand TEXT NOT NULL,
20
+ version TEXT NOT NULL,
21
+ grant_list TEXT NOT NULL,
22
+ person TEXT,
23
+ status TEXT NOT NULL,
24
+ created_at TEXT NOT NULL
25
+ )`;
26
+
27
+ const INSTALLATION_COLUMNS = 'id, key_hash, consumer, brand, version, grant_list, person, status, created_at';
28
+ const INSTALLATIONS_LISTED = 500;
29
+
30
+ /** Configuration for `SealedServiceConnections`. */
31
+ export interface ISealedServiceConnectionsOptions {
32
+ readonly values: IHeldValues;
33
+ readonly projectId: string;
34
+ readonly now?: () => number;
35
+ readonly cacheMs?: number;
36
+ }
37
+
38
+ function parseDeclinedBrand(raw: string | null): string[] {
39
+ try {
40
+ const brand = (JSON.parse(raw ?? 'null') as { brand?: unknown } | null)?.brand;
41
+ return typeof brand === 'string' ? [brand] : [];
42
+ } catch {
43
+ // fallback: corrupted declined-brand JSON entry is ignored so listing stays available
44
+ return [];
45
+ }
46
+ }
47
+
48
+ function parseJsonColumn(value: unknown): unknown {
49
+ try {
50
+ return typeof value === 'string' ? JSON.parse(value) : null;
51
+ } catch {
52
+ // fallback: malformed JSON column degrades to null so row decoding does not fail
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function installationOfRow(columns: readonly string[], row: readonly unknown[]): IInstallation {
58
+ const at = (name: string): unknown => row[columns.indexOf(name)];
59
+ return {
60
+ id: String(at('id')),
61
+ keyHash: String(at('key_hash')),
62
+ consumer: String(at('consumer')),
63
+ brand: String(at('brand')),
64
+ version: String(at('version')),
65
+ grant: ServiceProtocolCodec.grantOf(parseJsonColumn(at('grant_list'))) ?? [],
66
+ person: ServiceProtocolCodec.personOf(parseJsonColumn(at('person'))),
67
+ status: String(at('status')),
68
+ createdAt: String(at('created_at')),
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Consumer-side service connections stored as host-held sealed values
74
+ * (`SERVICE_<BRAND>` / `NO_SERVICE_<BRAND>`) with short-lived name caching.
75
+ */
76
+ export class SealedServiceConnections implements IServiceConnections {
77
+ private readonly values: IHeldValues;
78
+
79
+ private readonly projectId: string;
80
+
81
+ private readonly now: () => number;
82
+
83
+ private readonly cacheMs: number;
84
+
85
+ constructor(options: ISealedServiceConnectionsOptions) {
86
+ this.values = options.values;
87
+ this.projectId = options.projectId;
88
+ this.now = options.now ?? (() => Date.now());
89
+ this.cacheMs = options.cacheMs ?? CONNECTION_NAMES_TTL_MS;
90
+ }
91
+
92
+ private async heldNames(): Promise<Set<string>> {
93
+ const kept = namesKept.get(this.projectId);
94
+ if (this.cacheMs > 0 && kept && this.now() - kept.at < this.cacheMs) {
95
+ return kept.names;
96
+ }
97
+ const all = await this.values.heldNames(this.projectId);
98
+ const found = new Set(
99
+ all.filter((name) => name.startsWith(CONNECTION_SECRET_PREFIX) || name.startsWith(DECLINED_SECRET_PREFIX)),
100
+ );
101
+ namesKept.set(this.projectId, { at: this.now(), names: found });
102
+ return found;
103
+ }
104
+
105
+ private async connectionNames(): Promise<Set<string>> {
106
+ const names = await this.heldNames();
107
+ return new Set([...names].filter((name) => name.startsWith(CONNECTION_SECRET_PREFIX)));
108
+ }
109
+
110
+ async get(brand: string): Promise<IServiceConnection | null> {
111
+ const name = ServiceProtocolCodec.brandSecretName(brand);
112
+ if (!(await this.connectionNames()).has(name)) return null;
113
+ const found = ServiceProtocolCodec.connectionOf(await this.values.held(this.projectId, name));
114
+ return found?.brand === brand ? found : null;
115
+ }
116
+
117
+ async list(): Promise<IServiceConnection[]> {
118
+ const names = await this.connectionNames();
119
+ const found = await Promise.all(
120
+ [...names].map((name) => this.values.held(this.projectId, name).then((raw) => ServiceProtocolCodec.connectionOf(raw))),
121
+ );
122
+ return found
123
+ .filter((entry): entry is IServiceConnection => entry !== null)
124
+ .sort((a, b) => a.brand.localeCompare(b.brand));
125
+ }
126
+
127
+ async put(connection: IServiceConnection): Promise<void> {
128
+ const secretName = ServiceProtocolCodec.brandSecretName(connection.brand);
129
+ await this.values.hold(this.projectId, secretName, JSON.stringify(connection), connection.by);
130
+ const declinedName = ServiceProtocolCodec.declinedSecretName(connection.brand);
131
+ if ((await this.heldNames()).has(declinedName)) {
132
+ await this.values.release(this.projectId, declinedName);
133
+ }
134
+ namesKept.delete(this.projectId);
135
+ }
136
+
137
+ async remove(brand: string): Promise<boolean> {
138
+ const removed = await this.values.release(this.projectId, ServiceProtocolCodec.brandSecretName(brand));
139
+ namesKept.delete(this.projectId);
140
+ return removed;
141
+ }
142
+
143
+ async decline(brand: string, by: string): Promise<void> {
144
+ await this.values.hold(this.projectId, ServiceProtocolCodec.declinedSecretName(brand), JSON.stringify({ brand, by }), by);
145
+ namesKept.delete(this.projectId);
146
+ }
147
+
148
+ async declined(): Promise<Set<string>> {
149
+ const names = [...await this.heldNames()].filter((name) => name.startsWith(DECLINED_SECRET_PREFIX));
150
+ const found = await Promise.all(names.map((name) => this.values.held(this.projectId, name)));
151
+ return new Set(found.flatMap(parseDeclinedBrand));
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Publisher-side installation repository backed by `mosetta_installations` in the
157
+ * site's SQL database; stores only the SHA-256 hash of each connection key.
158
+ */
159
+ export class SqlServiceInstallations implements IInstallations {
160
+ private ready: Promise<unknown> | null = null;
161
+
162
+ constructor(private readonly database: () => IDatabaseRpc) {}
163
+
164
+ private async openDb(): Promise<IDatabaseRpc> {
165
+ const stub = this.database();
166
+ this.ready ??= stub.query(INSTALLATIONS_TABLE, []).catch((error: unknown) => {
167
+ this.ready = null;
168
+ throw error;
169
+ });
170
+ await this.ready;
171
+ return stub;
172
+ }
173
+
174
+ async create(installation: IInstallation): Promise<void> {
175
+ const stub = await this.openDb();
176
+ await stub.query(
177
+ 'INSERT INTO mosetta_installations (id, key_hash, consumer, brand, version, grant_list, person, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
178
+ [
179
+ installation.id,
180
+ installation.keyHash,
181
+ installation.consumer,
182
+ installation.brand,
183
+ installation.version,
184
+ JSON.stringify(installation.grant),
185
+ installation.person ? JSON.stringify(installation.person) : null,
186
+ installation.status,
187
+ installation.createdAt,
188
+ ],
189
+ );
190
+ }
191
+
192
+ async byId(id: string): Promise<IInstallation | null> {
193
+ const stub = await this.openDb();
194
+ const { columns, rows } = await stub.query(
195
+ `SELECT ${INSTALLATION_COLUMNS} FROM mosetta_installations WHERE id = ?`,
196
+ [id],
197
+ );
198
+ return rows[0] ? installationOfRow(columns, rows[0]) : null;
199
+ }
200
+
201
+ async list(): Promise<IInstallation[]> {
202
+ const stub = await this.openDb();
203
+ const { columns, rows } = await stub.query(
204
+ `SELECT ${INSTALLATION_COLUMNS} FROM mosetta_installations ORDER BY created_at DESC LIMIT ${INSTALLATIONS_LISTED}`,
205
+ [],
206
+ );
207
+ return rows.map((row) => installationOfRow(columns, row));
208
+ }
209
+
210
+ async setStatus(id: string, status: string): Promise<void> {
211
+ const stub = await this.openDb();
212
+ await stub.query('UPDATE mosetta_installations SET status = ? WHERE id = ?', [status, id]);
213
+ }
214
+ }
@@ -0,0 +1,272 @@
1
+ import { verifyToken } from '@mosetta/host-platform/tokens';
2
+ import { IdentityError, ProjectCataloguePolicy } from '@mosetta/identity';
3
+ import { PROJECT_IO_SQL_NOW, SqlServiceTechnical } from '@mosetta/tenancy';
4
+ import type { IProjectIoLease, IServiceTechnicalAttempt, IServiceTechnicalProject, ISqlDatabase } from '@mosetta/tenancy';
5
+ import type { IInstallation } from './protocol';
6
+ import { GuardedServiceInstallations } from './serviceInstallationsIo';
7
+
8
+ export interface IServiceTechnicalIntent {
9
+ readonly consumer: string;
10
+ readonly publisher: string;
11
+ readonly brand: string;
12
+ readonly version: string;
13
+ readonly grant: readonly string[];
14
+ readonly proof: string;
15
+ readonly expiresAtMs: number;
16
+ }
17
+
18
+ export interface IServiceTechnicalOutgoing {
19
+ finish(): Promise<void>;
20
+ uncertain(): Promise<void>;
21
+ }
22
+
23
+ export interface IServiceTechnicalIncoming {
24
+ create(installation: IInstallation): Promise<void>;
25
+ refuse(): Promise<void>;
26
+ uncertain(): Promise<void>;
27
+ }
28
+
29
+ export interface IServiceTechnicalPort {
30
+ outgoing(input: Omit<IServiceTechnicalIntent, 'expiresAtMs'>): Promise<IServiceTechnicalOutgoing>;
31
+ incoming(input: IServiceTechnicalIntent): Promise<IServiceTechnicalIncoming>;
32
+ remove(installation: IInstallation): Promise<void>;
33
+ }
34
+
35
+ export interface IServiceTechnicalConfig {
36
+ readonly primary: ISqlDatabase;
37
+ readonly internal: ISqlDatabase;
38
+ readonly origin: string;
39
+ readonly projectId: string;
40
+ readonly secret: string | null;
41
+ /** Actual local primary records only. A foreign literal origin returns null. */
42
+ project(origin: string): Promise<IServiceTechnicalProject | null>;
43
+ readonly now?: () => number;
44
+ }
45
+
46
+ export const SERVICE_TECHNICAL_INTERNAL_MIGRATIONS = [{
47
+ name: 'root_service_io_0002',
48
+ sql: `
49
+ CREATE TABLE root_service_technical_receipts(proof_digest TEXT PRIMARY KEY,installation_id TEXT NOT NULL,binding_digest TEXT NOT NULL);
50
+ CREATE TRIGGER root_service_technical_retained BEFORE DELETE ON root_service_technical_receipts BEGIN SELECT RAISE(ABORT,'Technical receipts are retained'); END;
51
+ `,
52
+ }];
53
+
54
+ const MAX_PROOF_LENGTH = 16_384;
55
+ const MAX_PROOF_TTL_MS = 300_000;
56
+ const REMOVE_DEADLINE_MS = 10_000;
57
+
58
+ function intentBinding(
59
+ one: Pick<IServiceTechnicalIntent, 'consumer' | 'publisher' | 'brand' | 'version' | 'grant' | 'expiresAtMs'>,
60
+ ): string {
61
+ return JSON.stringify([one.consumer, one.publisher, one.brand, one.version, one.grant, one.expiresAtMs]);
62
+ }
63
+
64
+ function attemptBinding(one: IServiceTechnicalAttempt): string {
65
+ return intentBinding({
66
+ consumer: one.consumerOrigin,
67
+ publisher: one.publisherOrigin,
68
+ brand: one.brand,
69
+ version: one.version,
70
+ grant: one.grant,
71
+ expiresAtMs: one.expiresAtMs,
72
+ });
73
+ }
74
+
75
+ function assertIntentBounds(input: IServiceTechnicalIntent, nowMs: number): void {
76
+ const validExpiry = Number.isSafeInteger(input.expiresAtMs)
77
+ && input.expiresAtMs > nowMs
78
+ && input.expiresAtMs <= nowMs + MAX_PROOF_TTL_MS;
79
+ const validOrigins = new URL(input.consumer).origin === input.consumer
80
+ && new URL(input.publisher).origin === input.publisher
81
+ && input.consumer !== input.publisher;
82
+ if (!input.proof.startsWith('msp_') || input.proof.length > MAX_PROOF_LENGTH || !validExpiry || !validOrigins) {
83
+ throw new IdentityError('FORBIDDEN');
84
+ }
85
+ }
86
+
87
+ function matchesInstallation(actual: IInstallation | null, expected: IInstallation): boolean {
88
+ if (!actual) return false;
89
+ return JSON.stringify([actual.id, actual.keyHash, actual.consumer, actual.brand, actual.version, actual.grant, actual.status])
90
+ === JSON.stringify([expected.id, expected.keyHash, expected.consumer, expected.brand, expected.version, expected.grant, expected.status]);
91
+ }
92
+
93
+ /** Private Root protocol, independent of human identity and never delivered to a module. */
94
+ export class RootServiceTechnical implements IServiceTechnicalPort {
95
+ private readonly primary: SqlServiceTechnical;
96
+
97
+ private readonly now: () => number;
98
+
99
+ constructor(private readonly config: IServiceTechnicalConfig) {
100
+ this.now = config.now ?? Date.now;
101
+ this.primary = new SqlServiceTechnical(config.primary, this.now);
102
+ }
103
+
104
+ private async record(input: IServiceTechnicalIntent): Promise<IServiceTechnicalAttempt> {
105
+ assertIntentBounds(input, this.now());
106
+ const [consumer, publisher] = await Promise.all([
107
+ this.config.project(input.consumer),
108
+ this.config.project(input.publisher),
109
+ ]);
110
+ if (
111
+ (input.consumer === this.config.origin && consumer?.id !== this.config.projectId)
112
+ || (input.publisher === this.config.origin && publisher?.id !== this.config.projectId)
113
+ ) {
114
+ throw new IdentityError('FORBIDDEN');
115
+ }
116
+ return {
117
+ proofDigest: await ProjectCataloguePolicy.hash(input.proof),
118
+ consumer,
119
+ publisher,
120
+ consumerOrigin: input.consumer,
121
+ publisherOrigin: input.publisher,
122
+ brand: input.brand,
123
+ version: input.version,
124
+ grant: [...input.grant],
125
+ expiresAtMs: input.expiresAtMs,
126
+ };
127
+ }
128
+
129
+ async outgoing(input: Omit<IServiceTechnicalIntent, 'expiresAtMs'>): Promise<IServiceTechnicalOutgoing> {
130
+ if (input.consumer !== this.config.origin || !this.config.secret || !input.proof.startsWith('msp_')) {
131
+ throw new IdentityError('FORBIDDEN');
132
+ }
133
+ const proof = await verifyToken(input.proof.slice(4), this.config.secret);
134
+ const validProof = Boolean(
135
+ proof
136
+ && proof.aud === `service-proof:${new URL(input.consumer).hostname.toLowerCase()}`
137
+ && typeof proof.exp === 'number'
138
+ && proof.publisher === input.publisher
139
+ && proof.brand === input.brand
140
+ && proof.version === input.version
141
+ && JSON.stringify(proof.grant) === JSON.stringify(input.grant),
142
+ );
143
+ if (!validProof) throw new IdentityError('FORBIDDEN');
144
+ const intent = await this.record({ ...input, expiresAtMs: (proof!.exp as number) * 1000 });
145
+ if (!intent.consumer) throw new IdentityError('FORBIDDEN');
146
+ await this.primary.begin(intent);
147
+ return {
148
+ finish: () => this.primary.finish(intent),
149
+ uncertain: () => this.primary.uncertain(intent),
150
+ };
151
+ }
152
+
153
+ private async resolveIncomingAttempt(input: IServiceTechnicalIntent): Promise<IServiceTechnicalAttempt> {
154
+ if (input.publisher !== this.config.origin) throw new IdentityError('FORBIDDEN');
155
+ const candidate = await this.record(input);
156
+ if (!candidate.publisher) throw new IdentityError('FORBIDDEN');
157
+ const existing = await this.primary.find(candidate.proofDigest);
158
+ if (existing) {
159
+ const sameActors = JSON.stringify(existing.consumer) === JSON.stringify(candidate.consumer)
160
+ && JSON.stringify(existing.publisher) === JSON.stringify(candidate.publisher);
161
+ if (attemptBinding(existing) !== intentBinding(input) || !sameActors || existing.publisher?.id !== this.config.projectId) {
162
+ throw new IdentityError('FORBIDDEN');
163
+ }
164
+ return existing;
165
+ }
166
+ if (candidate.consumer) throw new IdentityError('FORBIDDEN');
167
+ await this.primary.begin(candidate);
168
+ return candidate;
169
+ }
170
+
171
+ private async commitIncomingCreate(selected: IServiceTechnicalAttempt, installation: IInstallation): Promise<void> {
172
+ try {
173
+ if (
174
+ installation.consumer !== selected.consumerOrigin
175
+ || installation.brand !== selected.brand
176
+ || installation.version !== selected.version
177
+ || JSON.stringify(installation.grant) !== JSON.stringify(selected.grant)
178
+ || installation.status !== 'active'
179
+ ) {
180
+ throw new IdentityError('FORBIDDEN');
181
+ }
182
+ const digest = await ProjectCataloguePolicy.hash(
183
+ JSON.stringify([attemptBinding(selected), installation.id, installation.keyHash]),
184
+ );
185
+ let activeLease: IProjectIoLease | null = null;
186
+ const internal: ISqlDatabase = {
187
+ prepare: (sql) => this.config.internal.prepare(sql),
188
+ batch: (statements) => {
189
+ const lease = activeLease;
190
+ if (!lease) throw new IdentityError('FORBIDDEN');
191
+ lease.checkpoint();
192
+ return this.config.internal.batch([
193
+ this.config.internal.prepare(
194
+ `INSERT INTO root_service_technical_receipts(proof_digest,installation_id,binding_digest) SELECT ?,?,? WHERE ?>${PROJECT_IO_SQL_NOW}`,
195
+ ).bind(selected.proofDigest, installation.id, digest, lease.deadlineMs),
196
+ this.config.internal.prepare('INSERT INTO root_service_io_assert(required) SELECT NULL WHERE changes()<>1'),
197
+ ...statements,
198
+ ]);
199
+ },
200
+ };
201
+ const installations = new GuardedServiceInstallations(internal, {
202
+ step: async (_digest, send) => {
203
+ activeLease = await this.primary.lease(selected);
204
+ return send(activeLease);
205
+ },
206
+ });
207
+ await installations.create(installation);
208
+ await this.primary.publisherDone(selected, installation.id);
209
+ if (!selected.consumer) await this.primary.finish(selected);
210
+ } catch (error) {
211
+ await this.primary.uncertain(selected);
212
+ throw error instanceof IdentityError ? error : new IdentityError('IDENTITY_UNAVAILABLE');
213
+ }
214
+ }
215
+
216
+ async incoming(input: IServiceTechnicalIntent): Promise<IServiceTechnicalIncoming> {
217
+ const selected = await this.resolveIncomingAttempt(input);
218
+ await this.primary.claim(selected);
219
+ let used = false;
220
+ const consume = (): void => {
221
+ if (used) throw new IdentityError('FORBIDDEN');
222
+ used = true;
223
+ };
224
+ return {
225
+ uncertain: () => this.primary.uncertain(selected),
226
+ refuse: async () => {
227
+ consume();
228
+ await this.primary.publisherDone(selected, null);
229
+ if (!selected.consumer) await this.primary.finish(selected);
230
+ },
231
+ create: async (installation) => {
232
+ consume();
233
+ await this.commitIncomingCreate(selected, installation);
234
+ },
235
+ };
236
+ }
237
+
238
+ async remove(installation: IInstallation): Promise<void> {
239
+ const deadline = this.now() + REMOVE_DEADLINE_MS;
240
+ const publisher = await this.config.project(this.config.origin);
241
+ if (!publisher || publisher.id !== this.config.projectId) throw new IdentityError('FORBIDDEN');
242
+ const proofDigest = await ProjectCataloguePolicy.hash(
243
+ JSON.stringify(['remove', publisher, installation.id, installation.keyHash, installation.status, crypto.randomUUID()]),
244
+ );
245
+ const intent: IServiceTechnicalAttempt = {
246
+ proofDigest,
247
+ consumer: null,
248
+ publisher,
249
+ consumerOrigin: installation.consumer,
250
+ publisherOrigin: this.config.origin,
251
+ brand: installation.brand,
252
+ version: installation.version,
253
+ grant: installation.grant,
254
+ expiresAtMs: deadline,
255
+ };
256
+ await this.primary.begin(intent);
257
+ await this.primary.claim(intent);
258
+ const repository = new GuardedServiceInstallations(this.config.internal, {
259
+ step: async (_digest, send) => send(await this.primary.lease(intent)),
260
+ });
261
+ try {
262
+ const actual = await repository.byId(installation.id);
263
+ if (!matchesInstallation(actual, installation)) throw new IdentityError('FORBIDDEN');
264
+ await repository.setStatus(installation.id, 'removed');
265
+ await this.primary.publisherDone(intent, installation.id);
266
+ await this.primary.finish(intent);
267
+ } catch (error) {
268
+ await this.primary.uncertain(intent);
269
+ throw error instanceof IdentityError ? error : new IdentityError('IDENTITY_UNAVAILABLE');
270
+ }
271
+ }
272
+ }
@@ -0,0 +1,15 @@
1
+ // Architectural invariants for @mosetta/services:
2
+ // - All service palette calls MUST route through the consumer host (never browser direct to
3
+ // publisher): avoids cross-origin CORS exposure and guarantees the connection key never leaves
4
+ // the consumer host.
5
+ // - Consumer host strips incoming credentials/internal headers and mints a short-lived delegation
6
+ // bound to the calling human before dispatching to the publisher over private transport.
7
+ // - Tile server-action code stays 100% identical between code mode and service mode.
8
+ export * from './protocolEntry';
9
+ export * from './serviceCompositionIo';
10
+ export * from './serviceInstallationsIo';
11
+ export * from './serviceSecretsIo';
12
+ export * from './serviceTechnicalIo';
13
+ export * from './serviceManagementIo';
14
+ export * from './serviceHost';
15
+ export * from './platformServices';
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.