@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.
@@ -0,0 +1,138 @@
1
+ import { IdentityError, ProjectCataloguePolicy } from '@mosetta/identity';
2
+ import { HOST_HELD_SCOPE } from '@mosetta/server/secrets';
3
+ import type { ISecretEntry, ISecretsStore } from '@mosetta/server/secrets';
4
+ import type { IProjectIoOperation, ISqlDatabase, SqlProjectIo } from '@mosetta/tenancy';
5
+
6
+ const SERVICE_SECRET_NAME_RE = /^(?:SERVICE_|NO_SERVICE_)[A-Z0-9_]{1,54}$/;
7
+ const SEALED_VALUE_RE = /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
8
+
9
+ /** Configuration for `GuardedServiceSecrets`. */
10
+ export interface IGuardedServiceSecretsOptions {
11
+ readonly db: ISqlDatabase;
12
+ readonly underlying: ISecretsStore;
13
+ readonly operation: IProjectIoOperation;
14
+ readonly executor: SqlProjectIo;
15
+ readonly handle: object;
16
+ readonly defaults?: ReadonlySet<string>;
17
+ }
18
+
19
+ /** Root-only sealed entries. This adapter cannot write a module's setting/secret scope. */
20
+ export class GuardedServiceSecrets implements ISecretsStore {
21
+ private readonly observed = new Map<string, string | null>();
22
+
23
+ private readonly db: ISqlDatabase;
24
+
25
+ private readonly underlying: ISecretsStore;
26
+
27
+ private readonly operation: IProjectIoOperation;
28
+
29
+ private readonly executor: SqlProjectIo;
30
+
31
+ private readonly handle: object;
32
+
33
+ private readonly defaults?: ReadonlySet<string>;
34
+
35
+ constructor(options: IGuardedServiceSecretsOptions) {
36
+ this.db = options.db;
37
+ this.underlying = options.underlying;
38
+ this.operation = options.operation;
39
+ this.executor = options.executor;
40
+ this.handle = options.handle;
41
+ this.defaults = options.defaults;
42
+ }
43
+
44
+ private assertSelected(projectId: string, scope: string, name: string): void {
45
+ if (projectId !== this.operation.target.projectId || scope !== HOST_HELD_SCOPE || !SERVICE_SECRET_NAME_RE.test(name)) {
46
+ throw new IdentityError('FORBIDDEN');
47
+ }
48
+ }
49
+
50
+ private remember(entries: readonly ISecretEntry[]): void {
51
+ for (const entry of entries) {
52
+ if (entry.scope === HOST_HELD_SCOPE) this.observed.set(entry.name, entry.value);
53
+ }
54
+ }
55
+
56
+ async list(projectId: string): Promise<ISecretEntry[]> {
57
+ if (projectId !== this.operation.target.projectId) throw new IdentityError('FORBIDDEN');
58
+ const found = await this.underlying.list(projectId);
59
+ this.remember(found);
60
+ return found;
61
+ }
62
+
63
+ async lookup(projectId: string, name: string, scopes: readonly string[]): Promise<ISecretEntry[]> {
64
+ this.assertSelected(projectId, HOST_HELD_SCOPE, name);
65
+ if (scopes.some((one) => one !== HOST_HELD_SCOPE)) throw new IdentityError('FORBIDDEN');
66
+ const found = await this.underlying.lookup(projectId, name, scopes);
67
+ this.remember(found);
68
+ if (!found.length) this.observed.set(name, null);
69
+ return found;
70
+ }
71
+
72
+ private async expected(projectId: string, name: string): Promise<string | null> {
73
+ if (!this.observed.has(name)) {
74
+ const row = await this.db
75
+ .prepare('SELECT value FROM project_secrets WHERE project_id=? AND scope=? AND name=?')
76
+ .bind(projectId, HOST_HELD_SCOPE, name)
77
+ .first<{ value: string }>();
78
+ this.observed.set(name, row?.value ?? null);
79
+ }
80
+ return this.observed.get(name)!;
81
+ }
82
+
83
+ async put(projectId: string, entry: ISecretEntry): Promise<void> {
84
+ this.assertSelected(projectId, entry.scope, entry.name);
85
+ if (this.defaults && !this.defaults.has(entry.name)) throw new IdentityError('FORBIDDEN');
86
+ if (!entry.secret || !SEALED_VALUE_RE.test(entry.value)) throw new IdentityError('INVALID_REQUEST');
87
+ const expected = await this.expected(projectId, entry.name);
88
+ const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.secret.put', projectId, entry, expected]));
89
+ await this.executor.commit(this.handle, crypto.randomUUID(), digest, () => [
90
+ this.db.prepare(
91
+ 'INSERT INTO project_secrets(project_id,scope,name,value,is_secret,key_version,updated_at,updated_by) '
92
+ + 'SELECT ?,?,?,?,?,?,?,? WHERE (?=0 OR NOT EXISTS(SELECT 1 FROM project_secrets declined WHERE declined.project_id=? AND declined.scope=? AND declined.name=?)) AND ((? IS NULL AND NOT EXISTS(SELECT 1 FROM project_secrets WHERE project_id=? AND scope=? AND name=?)) '
93
+ + 'OR EXISTS(SELECT 1 FROM project_secrets WHERE project_id=? AND scope=? AND name=? AND value=?)) '
94
+ + 'ON CONFLICT(project_id,scope,name) DO UPDATE SET value=excluded.value,is_secret=excluded.is_secret,key_version=excluded.key_version,updated_at=excluded.updated_at,updated_by=excluded.updated_by WHERE project_secrets.value IS ?',
95
+ ).bind(
96
+ projectId,
97
+ entry.scope,
98
+ entry.name,
99
+ entry.value,
100
+ 1,
101
+ entry.keyVersion,
102
+ entry.updatedAt,
103
+ entry.updatedBy,
104
+ this.defaults ? 1 : 0,
105
+ projectId,
106
+ HOST_HELD_SCOPE,
107
+ `NO_${entry.name}`,
108
+ expected,
109
+ projectId,
110
+ entry.scope,
111
+ entry.name,
112
+ projectId,
113
+ entry.scope,
114
+ entry.name,
115
+ expected,
116
+ expected,
117
+ ),
118
+ this.db.prepare('INSERT INTO project_io_assert(required) SELECT NULL WHERE changes()<>1'),
119
+ ]);
120
+ this.observed.set(entry.name, entry.value);
121
+ }
122
+
123
+ async remove(projectId: string, scope: string, name: string): Promise<boolean> {
124
+ this.assertSelected(projectId, scope, name);
125
+ if (this.defaults) throw new IdentityError('FORBIDDEN');
126
+ const expected = await this.expected(projectId, name);
127
+ const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.secret.remove', projectId, name, expected]));
128
+ await this.executor.commit(this.handle, crypto.randomUUID(), digest, () => [
129
+ this.db.prepare('DELETE FROM project_secrets WHERE project_id=? AND scope=? AND name=? AND value IS ?')
130
+ .bind(projectId, scope, name, expected),
131
+ this.db.prepare(
132
+ 'INSERT INTO project_io_assert(required) SELECT NULL WHERE (? IS NOT NULL AND changes()<>1) OR (? IS NULL AND EXISTS(SELECT 1 FROM project_secrets WHERE project_id=? AND scope=? AND name=?))',
133
+ ).bind(expected, expected, projectId, scope, name),
134
+ ]);
135
+ this.observed.set(name, null);
136
+ return expected !== null;
137
+ }
138
+ }
@@ -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,8 @@
1
+ export * from './protocolEntry';
2
+ export * from './serviceCompositionIo';
3
+ export * from './serviceInstallationsIo';
4
+ export * from './serviceSecretsIo';
5
+ export * from './serviceTechnicalIo';
6
+ export * from './serviceManagementIo';
7
+ export * from './serviceHost';
8
+ 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.