@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,203 @@
1
+ import type { IServiceConnection } from '@mosetta/host-platform/host';
2
+ import type { ISession } from '@mosetta/host-platform/tokens';
3
+ import { ServiceProtocolCodec } from './protocolCodec';
4
+ import {
5
+ GRANT_MAX,
6
+ INSTALLATIONS_PATH,
7
+ LISTING_PATH,
8
+ REVOKED_STATUS,
9
+ } from './protocolTypes';
10
+ import type { IServicesHost } from './protocolTypes';
11
+ import { ServiceConnectionClient } from './serviceConnectionClient';
12
+
13
+ export type { IServiceConnectContext } from './serviceConnectionClient';
14
+
15
+ /** Caller authorization context for `ServiceManagementController.handleServices`. */
16
+ export interface IServiceManagementAuth {
17
+ readonly session: ISession;
18
+ readonly owner: boolean;
19
+ }
20
+
21
+ interface IConnectBody {
22
+ readonly publisher?: unknown;
23
+ readonly brand?: unknown;
24
+ readonly version?: unknown;
25
+ readonly grant?: unknown;
26
+ }
27
+
28
+ /**
29
+ * Handles `/__mosetta__/services` consumer & publisher management operations
30
+ * (listing, publisher offer discovery, connecting, disconnecting, and revoking).
31
+ */
32
+ export class ServiceManagementController {
33
+ constructor(private readonly host: IServicesHost) {}
34
+
35
+ async handleServices(request: Request, auth: IServiceManagementAuth): Promise<Response> {
36
+ const url = new URL(request.url);
37
+ if (url.searchParams.has('installations') || url.searchParams.has('installation')) {
38
+ return this.handleOwnInstallations(request, url, auth.owner);
39
+ }
40
+ if (!this.host.connections) {
41
+ return ServiceProtocolCodec.refusalResponse(501, 'NO_SERVICES', 'this host keeps no services');
42
+ }
43
+ if (request.method === 'GET') {
44
+ const asked = url.searchParams.get('publisher');
45
+ return asked !== null ? this.offeredBy(asked) : this.listServices(url, auth.owner);
46
+ }
47
+ if (!auth.owner) {
48
+ return ServiceProtocolCodec.refusalResponse(403, 'OWNER_ONLY', 'the site\'s owner connects and ends services');
49
+ }
50
+ if (request.method === 'DELETE') return this.disconnectService(url, auth.session);
51
+ if (request.method !== 'POST') return ServiceProtocolCodec.refusalResponse(405, 'METHOD');
52
+ return this.connectRequestedService(request, url, auth.session);
53
+ }
54
+
55
+ private async handleOwnInstallations(request: Request, url: URL, owner: boolean): Promise<Response> {
56
+ const installations = this.host.installations;
57
+ if (request.method === 'GET') {
58
+ const rows = installations ? (await installations.list()).map((item) => ServiceProtocolCodec.shownInstallation(item)) : [];
59
+ return ServiceProtocolCodec.jsonResponse(200, { installations: rows, mayChange: owner });
60
+ }
61
+ if (!owner) {
62
+ return ServiceProtocolCodec.refusalResponse(403, 'OWNER_ONLY', 'the site\'s owner stops and resumes serving a site');
63
+ }
64
+ if (!installations) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_INSTALLATION');
65
+ const found = await installations.byId(url.searchParams.get('installation') ?? '');
66
+ if (!found) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_INSTALLATION');
67
+ if (request.method === 'DELETE') {
68
+ if (found.status === 'active') await installations.setStatus(found.id, REVOKED_STATUS);
69
+ const nextStatus = found.status === 'active' ? REVOKED_STATUS : found.status;
70
+ return ServiceProtocolCodec.jsonResponse(200, {
71
+ ok: true,
72
+ installation: ServiceProtocolCodec.shownInstallation({ ...found, status: nextStatus }),
73
+ });
74
+ }
75
+ if (request.method === 'PUT') {
76
+ if (found.status !== REVOKED_STATUS) {
77
+ return ServiceProtocolCodec.refusalResponse(409, 'NOT_STOPPED', `the installation is ${found.status}`);
78
+ }
79
+ await installations.setStatus(found.id, 'active');
80
+ return ServiceProtocolCodec.jsonResponse(200, {
81
+ ok: true,
82
+ installation: ServiceProtocolCodec.shownInstallation({ ...found, status: 'active' }),
83
+ });
84
+ }
85
+ return ServiceProtocolCodec.refusalResponse(405, 'METHOD');
86
+ }
87
+
88
+ private async offeredBy(publisher: string): Promise<Response> {
89
+ if (!ServiceProtocolCodec.isValidOrigin(publisher)) {
90
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'publisher: a site\'s origin, https://host');
91
+ }
92
+ let listed: { services?: unknown } | null;
93
+ try {
94
+ const res = await this.host.fetch(`${publisher}${LISTING_PATH}`, { headers: { accept: 'application/json' } });
95
+ listed = res.ok ? await res.json() as { services?: unknown } : null;
96
+ } catch {
97
+ // fallback: network failure maps to a 502 PUBLISHER_UNREACHABLE response below
98
+ listed = null;
99
+ }
100
+ if (!listed) {
101
+ return ServiceProtocolCodec.refusalResponse(502, 'PUBLISHER_UNREACHABLE', `${publisher} did not say what it offers`);
102
+ }
103
+ return ServiceProtocolCodec.jsonResponse(200, { publisher, offered: ServiceProtocolCodec.offersIn(listed) });
104
+ }
105
+
106
+ private async stateAtPublisher(connection: IServiceConnection): Promise<string> {
107
+ try {
108
+ const res = await this.host.fetch(`${connection.publisher}${INSTALLATIONS_PATH}`, {
109
+ redirect: 'manual',
110
+ headers: { accept: 'application/json', authorization: `Bearer ${connection.key}` },
111
+ });
112
+ if (res.status === 401) {
113
+ await res.body?.cancel();
114
+ return 'unknown';
115
+ }
116
+ const said = res.ok ? await res.json().catch(() => null) as { status?: unknown } | null : null;
117
+ if (!res.ok) await res.body?.cancel();
118
+ return typeof said?.status === 'string' ? said.status.slice(0, 40) : 'unreachable';
119
+ } catch {
120
+ // fallback: unreachable publisher reports literal 'unreachable' status in health check
121
+ return 'unreachable';
122
+ }
123
+ }
124
+
125
+ private async listServices(url: URL, owner: boolean): Promise<Response> {
126
+ const connections = this.host.connections!;
127
+ const [list, declined] = await Promise.all([connections.list(), connections.declined()]);
128
+ const states = url.searchParams.has('check')
129
+ ? await Promise.all(list.map((connection) => this.stateAtPublisher(connection)))
130
+ : null;
131
+ const defaults = this.host.defaults ?? [];
132
+ return ServiceProtocolCodec.jsonResponse(200, {
133
+ services: list.map(({ key: _key, ...shown }, index) => ({
134
+ ...shown,
135
+ ...(states ? { state: states[index] } : {}),
136
+ ...(defaults.some((item) => item.brand === shown.brand && item.publisher === shown.publisher) ? { byDefault: true } : {}),
137
+ })),
138
+ defaults: defaults.filter((item) => item.publisher !== url.origin).map((item) => ({
139
+ publisher: item.publisher,
140
+ brand: item.brand,
141
+ connected: list.some((conn) => conn.brand === item.brand && conn.publisher === item.publisher),
142
+ declined: declined.has(item.brand),
143
+ })),
144
+ mayChange: owner,
145
+ });
146
+ }
147
+
148
+ private async disconnectService(url: URL, session: ISession): Promise<Response> {
149
+ const connections = this.host.connections!;
150
+ const brand = url.searchParams.get('brand') ?? '';
151
+ const connection = await connections.get(brand);
152
+ if (!connection) return ServiceProtocolCodec.refusalResponse(404, 'NO_SUCH_SERVICE');
153
+ await this.host.fetch(`${connection.publisher}${INSTALLATIONS_PATH}`, {
154
+ method: 'DELETE',
155
+ redirect: 'manual',
156
+ headers: { authorization: `Bearer ${connection.key}` },
157
+ })
158
+ .then((res) => res.body?.cancel())
159
+ .catch((error: unknown) => console.warn(`services: ${connection.publisher} was not told ${brand} ended`, error));
160
+ await connections.remove(brand);
161
+ if ((this.host.defaults ?? []).some((item) => item.brand === brand)) {
162
+ await connections.decline(brand, session.login);
163
+ }
164
+ await this.host.composition?.detach(brand)
165
+ .catch((error: unknown) => console.warn(`services: ${brand} stayed in the site's composition`, error));
166
+ return ServiceProtocolCodec.jsonResponse(200, { ok: true, brand });
167
+ }
168
+
169
+ private async connectRequestedService(request: Request, url: URL, session: ISession): Promise<Response> {
170
+ if (!this.host.secret) return ServiceProtocolCodec.refusalResponse(501, 'NO_SESSION_KEY');
171
+ let body: IConnectBody;
172
+ try {
173
+ body = await request.json() as IConnectBody;
174
+ } catch {
175
+ // fallback: malformed JSON payload produces a 400 refusal
176
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'a JSON body: {publisher, brand, version, grant}');
177
+ }
178
+ const grant = ServiceProtocolCodec.grantOf(body.grant ?? []);
179
+ if (!ServiceProtocolCodec.isValidOrigin(body.publisher)) {
180
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'publisher: the publishing site\'s origin, https://host');
181
+ }
182
+ if (!ServiceProtocolCodec.isValidBrand(body.brand)) {
183
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'brand: the palette\'s brand');
184
+ }
185
+ if (!ServiceProtocolCodec.isValidVersion(body.version)) {
186
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'version: the palette\'s released version, X.Y.Z');
187
+ }
188
+ if (!grant) {
189
+ return ServiceProtocolCodec.refusalResponse(
190
+ 400,
191
+ 'BAD_REQUEST',
192
+ `grant: up to ${GRANT_MAX} palettes or palette/tile of this site the service may call`,
193
+ );
194
+ }
195
+ if (body.publisher === url.origin) {
196
+ return ServiceProtocolCodec.refusalResponse(400, 'BAD_REQUEST', 'a site takes its own palettes as code, not as a service');
197
+ }
198
+ return new ServiceConnectionClient(this.host).connectService(
199
+ { publisher: body.publisher, brand: body.brand, version: body.version, grant },
200
+ { url, session },
201
+ );
202
+ }
203
+ }
@@ -0,0 +1,166 @@
1
+ import { FixedCredentialProjectAuthority, rootResourceRuntime } from '@mosetta/host-platform/authorities';
2
+ import type { IRootResourceRuntimeConfig } from '@mosetta/host-platform/authorities';
3
+ import type { IHostInvocationIdentity } from '@mosetta/host-platform/bridges';
4
+ import { IdentityError, IdentitySecrets, ProjectCataloguePolicy } from '@mosetta/identity';
5
+ import type { ProjectSecrets } from '@mosetta/server/secrets';
6
+ import { SqlProjectIo } from '@mosetta/tenancy';
7
+ import type { IProjectIoOperation, IProjectIoTarget, IProjectRecord, ISqlDatabase } from '@mosetta/tenancy';
8
+ import { SealedServiceConnections, ServiceProtocolCodec } from './protocol';
9
+ import type {
10
+ IDefaultService,
11
+ IServiceConnections,
12
+ IServiceManagementPort,
13
+ IServiceMutationSession,
14
+ IServicesHost,
15
+ } from './protocol';
16
+ import { GuardedServiceComposition } from './serviceCompositionIo';
17
+ import { GuardedServiceInstallations } from './serviceInstallationsIo';
18
+ import { GuardedServiceSecrets } from './serviceSecretsIo';
19
+
20
+ export interface IRootServiceIoConfig extends IRootResourceRuntimeConfig {
21
+ readonly projectId: string;
22
+ readonly secrets: ProjectSecrets;
23
+ readonly internal: ISqlDatabase;
24
+ readonly host: IServicesHost;
25
+ publisher(origin: string): Promise<IProjectRecord | null>;
26
+ }
27
+
28
+ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
29
+ const BODYLESS_STATUSES = new Set([204, 205, 304]);
30
+
31
+ async function sha256Hex(payload: BufferSource): Promise<string> {
32
+ const digest = await crypto.subtle.digest('SHA-256', payload);
33
+ return [...new Uint8Array(digest)].map((one) => one.toString(16).padStart(2, '0')).join('');
34
+ }
35
+
36
+ function buildGuardedConnections(held: IServiceConnections, wanted?: IDefaultService): IServiceConnections {
37
+ if (!wanted) return held;
38
+ return {
39
+ list: () => held.list(),
40
+ get: (brand) => held.get(brand),
41
+ declined: () => held.declined(),
42
+ put: (connection) => {
43
+ if (connection.brand !== wanted.brand || connection.publisher !== wanted.publisher) {
44
+ throw new IdentityError('FORBIDDEN');
45
+ }
46
+ return held.put(connection);
47
+ },
48
+ remove: () => Promise.reject(new IdentityError('FORBIDDEN')),
49
+ decline: () => Promise.reject(new IdentityError('FORBIDDEN')),
50
+ };
51
+ }
52
+
53
+ function buildGuardedFetch(baseFetch: typeof fetch, executor: SqlProjectIo, handle: object): typeof fetch {
54
+ return async (input, init) => {
55
+ const prepared = new Request(input, init);
56
+ if (!MUTATING_METHODS.has(prepared.method)) return baseFetch(prepared);
57
+ const bytes = await prepared.clone().arrayBuffer();
58
+ const bodyHash = [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))];
59
+ const digest = await ProjectCataloguePolicy.hash(
60
+ JSON.stringify([prepared.url, prepared.method, [...prepared.headers], bodyHash]),
61
+ );
62
+ return executor.step(handle, crypto.randomUUID(), digest, async (checkpoint) => {
63
+ checkpoint();
64
+ const response = await baseFetch(prepared);
65
+ const body = await response.arrayBuffer();
66
+ if (response.status >= 500 || (response.status >= 300 && response.status < 400)) {
67
+ throw new IdentityError('IDENTITY_UNAVAILABLE');
68
+ }
69
+ return {
70
+ confirmed: true,
71
+ status: response.status,
72
+ value: new Response(BODYLESS_STATUSES.has(response.status) ? null : body, response),
73
+ };
74
+ });
75
+ };
76
+ }
77
+
78
+ /** Selected pass stays in this event. Root config/defaults cannot come from a public body. */
79
+ export function serviceManagementOf(identity: IHostInvocationIdentity, config: IRootServiceIoConfig): IServiceManagementPort {
80
+ let captured: IProjectIoTarget | null = null;
81
+ const open = async (request: Request | null, wanted?: IDefaultService): Promise<IServiceMutationSession> => {
82
+ if (wanted && !(config.host.defaults ?? []).some((one) => one.brand === wanted.brand && one.publisher === wanted.publisher)) {
83
+ throw new IdentityError('FORBIDDEN');
84
+ }
85
+ const payload = request
86
+ ? new Uint8Array(await request.clone().arrayBuffer())
87
+ : new TextEncoder().encode(JSON.stringify(wanted));
88
+ const payloadDigest = await sha256Hex(payload);
89
+ let mutation: IServiceMutationSession | null = null;
90
+ const port = await identity.bindInvocation(async (selected) => {
91
+ const runtime = await rootResourceRuntime(config, config.projectId, selected.credential);
92
+ if (runtime.source.project.ready !== true) throw new IdentityError('FORBIDDEN');
93
+ const permission = wanted ? 'services.defaults' : 'services.manage';
94
+ const authority = new FixedCredentialProjectAuthority(selected.credential, config.projectId, permission, config.verifier, runtime.current);
95
+ const check = await authority.read(captured ?? undefined);
96
+ const target: IProjectIoTarget = {
97
+ projectId: config.projectId,
98
+ name: 'services',
99
+ sourceKey: check.catalogue.sourceKey,
100
+ sourceGeneration: check.catalogue.sourceGeneration,
101
+ providerGeneration: await ProjectCataloguePolicy.hash(
102
+ JSON.stringify(['root-service-internal-v1', config.projectId, check.catalogue.sourceKey]),
103
+ ),
104
+ };
105
+ if (captured && JSON.stringify(captured) !== JSON.stringify(target)) throw new IdentityError('FORBIDDEN');
106
+ captured = Object.freeze(target);
107
+ const operation: IProjectIoOperation = {
108
+ id: crypto.randomUUID(),
109
+ nonce: crypto.randomUUID(),
110
+ capability: IdentitySecrets.random(),
111
+ target,
112
+ permission,
113
+ payloadDigest,
114
+ credentialKey: await IdentitySecrets.hash(selected.credential),
115
+ originalProof: selected.proof,
116
+ };
117
+ const executor = new SqlProjectIo(config.database, () => authority.read(target));
118
+ const handle = await executor.open(operation);
119
+ const defaults = wanted ? new Set([ServiceProtocolCodec.brandSecretName(wanted.brand)]) : undefined;
120
+ const secrets = config.secrets.withStore(
121
+ (store) => new GuardedServiceSecrets({
122
+ db: config.database,
123
+ underlying: store,
124
+ operation,
125
+ executor,
126
+ handle,
127
+ defaults,
128
+ }),
129
+ );
130
+ const connections = buildGuardedConnections(
131
+ new SealedServiceConnections({ values: secrets, projectId: config.projectId, now: Date.now, cacheMs: 0 }),
132
+ wanted,
133
+ );
134
+ const installations = new GuardedServiceInstallations(config.internal, {
135
+ step: (digest, send) => executor.step(handle, crypto.randomUUID(), digest, async (checkpoint, deadlineMs) => {
136
+ const value = await send({ checkpoint, deadlineMs });
137
+ return { confirmed: true, status: 204, value };
138
+ }),
139
+ });
140
+ const composition = new GuardedServiceComposition({
141
+ db: config.database,
142
+ operation,
143
+ executor,
144
+ handle,
145
+ publisher: config.publisher,
146
+ transitioned: (previous, next) => {
147
+ if (!captured || captured.sourceGeneration !== previous) throw new IdentityError('FORBIDDEN');
148
+ captured = Object.freeze({ ...captured, sourceGeneration: next });
149
+ },
150
+ defaults: wanted ? new Set([`${wanted.brand}\n${wanted.publisher}`]) : undefined,
151
+ });
152
+ const guardedFetch = buildGuardedFetch(config.host.fetch, executor, handle);
153
+ mutation = {
154
+ host: { ...config.host, management: undefined, connections, installations, composition, fetch: guardedFetch },
155
+ finish: () => executor.finish(handle),
156
+ };
157
+ return { fetch: () => Promise.resolve(new Response(null, { status: 204 })) };
158
+ }, wanted ? { allowEditNavigation: true } : undefined);
159
+ if (!port || !mutation) throw new IdentityError('INVALID_PASS');
160
+ return mutation;
161
+ };
162
+ return {
163
+ human: (request) => open(request),
164
+ defaults: (wanted) => open(null, wanted),
165
+ };
166
+ }
@@ -0,0 +1,71 @@
1
+ import { Errors } from '@mosetta/core';
2
+ import type { IServiceConnection } from '@mosetta/host-platform/host';
3
+ import {
4
+ BLOCK_GIVEN_HEADER,
5
+ BLOCK_HEADER,
6
+ BLOCK_ORIGIN_HEADER,
7
+ SERVICE_CALL_HEADER,
8
+ } from '@mosetta/server-action/core';
9
+ import { ServiceProtocolCodec } from './protocolCodec';
10
+ import { SERVICE_BLOCK_MAX } from './protocolTypes';
11
+ import type { IServicesHost } from './protocolTypes';
12
+
13
+ /**
14
+ * Consumer-side proxy client that probes block context and forwards human
15
+ * server-action calls exclusively over the trusted private invocation bridge.
16
+ */
17
+ export class ServiceProxyClient {
18
+ constructor(private readonly host: IServicesHost) {}
19
+
20
+ /**
21
+ * Probes the local runner (`SERVICE_CALL_HEADER`) for the published block context
22
+ * of an incoming action call, or returns `null` when unavailable.
23
+ */
24
+ static async probeServiceBlock(
25
+ request: Request,
26
+ ask: (probe: Request) => Promise<Response>,
27
+ ): Promise<string | null> {
28
+ if (!request.headers.has(BLOCK_ORIGIN_HEADER)) return null;
29
+ const headers = new Headers(request.headers);
30
+ headers.delete(BLOCK_GIVEN_HEADER);
31
+ headers.delete('content-length');
32
+ headers.set(SERVICE_CALL_HEADER, '1');
33
+ try {
34
+ const answer = await ask(new Request(request.url, { method: 'POST', headers }));
35
+ await answer.body?.cancel();
36
+ return answer.headers.has(SERVICE_CALL_HEADER) ? answer.headers.get(BLOCK_HEADER) : null;
37
+ } catch (caught) {
38
+ // fallback: block probe failure degrades to null context rather than blocking the service call
39
+ console.warn('services: the calling block was not read', Errors.toError(caught));
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /** Forwards a human service action call through the private invocation bridge. */
45
+ async forward(
46
+ request: Request,
47
+ connection: IServiceConnection,
48
+ block: string | null = null,
49
+ ): Promise<Response> {
50
+ const action = ServiceProtocolCodec.actionOfPath(new URL(request.url).pathname);
51
+ if (!action || action.brand !== connection.brand) {
52
+ return ServiceProtocolCodec.refusalResponse(403, 'NOT_THIS_PALETTE');
53
+ }
54
+ if (!this.host.invocation) {
55
+ return ServiceProtocolCodec.refusalResponse(
56
+ 501,
57
+ 'PRIVATE_SERVICE_UNAVAILABLE',
58
+ 'Human service calls require a trusted same-installation bridge.',
59
+ );
60
+ }
61
+ const answer = await this.host.invocation.invoke(request, {
62
+ brand: connection.brand,
63
+ installation: connection.installation,
64
+ publisher: connection.publisher,
65
+ block: block && block.length <= SERVICE_BLOCK_MAX ? block : null,
66
+ });
67
+ const back = new Response(answer.body, answer);
68
+ back.headers.delete('set-cookie');
69
+ return back;
70
+ }
71
+ }
@@ -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_[A-Z0-9_]{1,54}|NO_SERVICE_[A-Z0-9_]{1,53})$/;
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
+ }