@mosetta/services 0.0.0-stage → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +33 -3
- package/src/errors.ts +59 -0
- package/src/platformServices.ts +221 -0
- package/src/protocol.ts +11 -0
- package/src/protocolCodec.ts +236 -0
- package/src/protocolEntry.ts +4 -0
- package/src/protocolTypes.ts +170 -0
- package/src/publisherServiceInvocation.ts +286 -0
- package/src/serviceCompositionIo.ts +109 -0
- package/src/serviceConnectionClient.ts +184 -0
- package/src/serviceDefaultsCoordinator.ts +184 -0
- package/src/serviceHandshakeController.ts +257 -0
- package/src/serviceHost.ts +234 -0
- package/src/serviceHostCall.ts +239 -0
- package/src/serviceInstallationsIo.ts +126 -0
- package/src/serviceInvocation.ts +169 -0
- package/src/serviceManagementController.ts +203 -0
- package/src/serviceManagementIo.ts +166 -0
- package/src/serviceProxyClient.ts +71 -0
- package/src/serviceSecretsIo.ts +138 -0
- package/src/serviceStores.ts +214 -0
- package/src/serviceTechnicalIo.ts +272 -0
- package/src/services.ts +8 -0
- package/README.md +0 -3
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type { TWorkbenchRoles } from '@mosetta/content/workbench';
|
|
2
|
+
import { INSTALLATIONS_PATH, REPOSITORIES_GRANT, SERVICES_PATH } from '@mosetta/host-platform/host';
|
|
3
|
+
import type { IDefaultService, IServiceConnection, IServicesComposition } from '@mosetta/host-platform/host';
|
|
4
|
+
import type { ISession } from '@mosetta/host-platform/tokens';
|
|
5
|
+
import type { IServiceInvocationPort } from './serviceInvocation';
|
|
6
|
+
import type { IServiceTechnicalPort } from './serviceTechnicalIo';
|
|
7
|
+
|
|
8
|
+
export { INSTALLATIONS_PATH, REPOSITORIES_GRANT, SERVICES_PATH };
|
|
9
|
+
export type { IDefaultService, IServiceConnection, IServicesComposition, TWorkbenchRoles };
|
|
10
|
+
|
|
11
|
+
/** A connection's key, as the publisher gave it: `msi_<installation>.<secret>`. */
|
|
12
|
+
export const INSTALLATION_KEY_PREFIX = 'msi_';
|
|
13
|
+
|
|
14
|
+
/** Reserved legacy HTTP word: stripped at admission, never a human identity source. */
|
|
15
|
+
export const SERVICE_PERSON_HEADER = 'x-mosetta-service-person';
|
|
16
|
+
|
|
17
|
+
/** Reserved legacy credential-bearing site word; not accepted by private invocation. */
|
|
18
|
+
export const SERVICE_SITE_HEADER = 'x-mosetta-service-site';
|
|
19
|
+
|
|
20
|
+
/** The block the call comes from, as the consumer's runner read it off the consumer's page. */
|
|
21
|
+
export const SERVICE_BLOCK_HEADER = 'x-mosetta-service-block';
|
|
22
|
+
|
|
23
|
+
/** Maximum serialized size of a forwarded block context. */
|
|
24
|
+
export const SERVICE_BLOCK_MAX = 48 * 1024;
|
|
25
|
+
|
|
26
|
+
/** The server tile a palette offers itself as a service by, and the action that decides who connects. */
|
|
27
|
+
export const SERVICE_TILE = 'service';
|
|
28
|
+
export const INSTALL_ACTION = 'install';
|
|
29
|
+
|
|
30
|
+
/** Host-door grants a service may request beside the site's palettes. */
|
|
31
|
+
export const PREVIEWS_GRANT = '@previews';
|
|
32
|
+
export const MEDIA_GRANT = '@media';
|
|
33
|
+
|
|
34
|
+
/** The connection permits code callbacks; the child's code.edit/code.release still gate every API call. */
|
|
35
|
+
export const CODE_GRANT = '@code';
|
|
36
|
+
|
|
37
|
+
/** Reserved legacy code-key word; private invocation carries only safe code routing metadata. */
|
|
38
|
+
export const SERVICE_CODE_HEADER = 'x-mosetta-service-code';
|
|
39
|
+
|
|
40
|
+
export const PROOF_PREFIX = 'msp_';
|
|
41
|
+
export const PROOF_TTL_SECONDS = 5 * 60;
|
|
42
|
+
export const GRANT_MAX = 32;
|
|
43
|
+
export const LISTING_PATH = '/api/server-action/';
|
|
44
|
+
export const REVOKED_STATUS = 'revoked';
|
|
45
|
+
|
|
46
|
+
/** Parsed address of a server-action HTTP path. */
|
|
47
|
+
export interface IServiceActionAddress {
|
|
48
|
+
readonly fullId: string;
|
|
49
|
+
readonly brand: string;
|
|
50
|
+
readonly tile: string;
|
|
51
|
+
readonly action: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Unverified contact metadata on an installation record; never an identity or permission source. */
|
|
55
|
+
export interface IServicePerson {
|
|
56
|
+
/** Contact identifier supplied by the consumer; never used to authorize human operations. */
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly via: string;
|
|
59
|
+
readonly login: string;
|
|
60
|
+
readonly email?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The parts a service plays in a workbench (`@mosetta/content/workbench`), each `<tile>.<action>`. */
|
|
64
|
+
export interface IWorkbenchRoles {
|
|
65
|
+
readonly assistant?: string;
|
|
66
|
+
readonly transcribe?: string;
|
|
67
|
+
readonly translate?: string;
|
|
68
|
+
readonly tools?: string;
|
|
69
|
+
readonly icon?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The consumer's connections, kept where no code of the site reads them. */
|
|
73
|
+
export interface IServiceConnections {
|
|
74
|
+
list(): Promise<IServiceConnection[]>;
|
|
75
|
+
get(brand: string): Promise<IServiceConnection | null>;
|
|
76
|
+
put(connection: IServiceConnection): Promise<void>;
|
|
77
|
+
remove(brand: string): Promise<boolean>;
|
|
78
|
+
/** The owner ended a service the host gives every site: it stays ended — the host connects it no more. */
|
|
79
|
+
decline(brand: string, by: string): Promise<void>;
|
|
80
|
+
/** The brands the owner ended so — a connection made again takes the word back. */
|
|
81
|
+
declined(): Promise<Set<string>>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** An installation of one of this site's palettes at another site, as the publisher keeps it. */
|
|
85
|
+
export interface IInstallation {
|
|
86
|
+
readonly id: string;
|
|
87
|
+
readonly keyHash: string;
|
|
88
|
+
readonly consumer: string;
|
|
89
|
+
readonly brand: string;
|
|
90
|
+
readonly version: string;
|
|
91
|
+
readonly grant: readonly string[];
|
|
92
|
+
readonly person: IServicePerson | null;
|
|
93
|
+
/** `active`; `removed` — the consumer ended it; anything else (e.g. `revoked`) — refused. */
|
|
94
|
+
readonly status: string;
|
|
95
|
+
readonly createdAt: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The publisher's installations repository contract. */
|
|
99
|
+
export interface IInstallations {
|
|
100
|
+
create(installation: IInstallation): Promise<void>;
|
|
101
|
+
byId(id: string): Promise<IInstallation | null>;
|
|
102
|
+
/** Every installation, the newest first — who uses the site's services. */
|
|
103
|
+
list(): Promise<IInstallation[]>;
|
|
104
|
+
setStatus(id: string, status: string): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Scoped mutation session opened by the host's private service management port. */
|
|
108
|
+
export interface IServiceMutationSession {
|
|
109
|
+
readonly host: IServicesHost;
|
|
110
|
+
finish(): Promise<void>;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Trusted event-only factories; these ports are never application env or HTTP authority. */
|
|
114
|
+
export interface IServiceManagementPort {
|
|
115
|
+
human(request: Request): Promise<IServiceMutationSession>;
|
|
116
|
+
defaults(wanted: IDefaultService): Promise<IServiceMutationSession>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Host dependencies required to serve cross-site service handshakes and management. */
|
|
120
|
+
export interface IServicesHost {
|
|
121
|
+
/** Root-only one-use technical proof and local SQL fence. No human identity authority. */
|
|
122
|
+
readonly technical?: IServiceTechnicalPort | null;
|
|
123
|
+
readonly management?: IServiceManagementPort | null;
|
|
124
|
+
/** A request-local trusted same-installation bridge; absent means human handoff is unavailable. */
|
|
125
|
+
readonly invocation?: IServiceInvocationPort | null;
|
|
126
|
+
/** The site's composition — none: a service's actions are forwarded, its blocks are the site's own business. */
|
|
127
|
+
readonly composition?: IServicesComposition | null;
|
|
128
|
+
/** Only the technical connection-confirmation proof uses this host secret. */
|
|
129
|
+
readonly secret: string | null;
|
|
130
|
+
/** This site's connections — the consumer's side; none: it takes no services. */
|
|
131
|
+
readonly connections: IServiceConnections | null;
|
|
132
|
+
/** This site's installations — the publisher's side; none: it offers no services. */
|
|
133
|
+
readonly installations: IInstallations | null;
|
|
134
|
+
/** Outbound transport to another site. */
|
|
135
|
+
readonly fetch: typeof fetch;
|
|
136
|
+
/** An action of this site's own run as the host asks (the publisher's `install`). */
|
|
137
|
+
readonly runAction: ((request: Request) => Promise<Response>) | null;
|
|
138
|
+
/** The services the host gives every site of its own (e.g. the platform's assistant). */
|
|
139
|
+
readonly defaults?: readonly IDefaultService[];
|
|
140
|
+
readonly now?: () => Date;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Where a host keeps what only it may read — the site's secrets, in the host's own scope. */
|
|
144
|
+
export interface IHeldValues {
|
|
145
|
+
hold(projectId: string, name: string, value: string, by: string | null): Promise<void>;
|
|
146
|
+
held(projectId: string, name: string): Promise<string | null>;
|
|
147
|
+
heldNames(projectId: string): Promise<string[]>;
|
|
148
|
+
release(projectId: string, name: string): Promise<boolean>;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Parameters a consumer asks to connect and signs in its confirmation proof. */
|
|
152
|
+
export interface IServiceAsked {
|
|
153
|
+
readonly publisher: string;
|
|
154
|
+
readonly brand: string;
|
|
155
|
+
readonly version: string;
|
|
156
|
+
readonly grant: readonly string[];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Normalized description of a service offered by a publishing site. */
|
|
160
|
+
export interface IServiceOffer {
|
|
161
|
+
readonly brand: string;
|
|
162
|
+
readonly version: string;
|
|
163
|
+
readonly title: string;
|
|
164
|
+
readonly description?: string;
|
|
165
|
+
readonly grant: readonly string[];
|
|
166
|
+
readonly workbench?: TWorkbenchRoles;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Minimal session fields carried into handshake requests and default connections. */
|
|
170
|
+
export type TServiceSessionIdentity = Pick<ISession, 'sub' | 'via' | 'login'> & Partial<Pick<ISession, 'exp'>>;
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { CONTENT_COMMAND_PATH, PROJECT_MEMORY_PATH } from '@mosetta/content';
|
|
2
|
+
import { IdentityError } from '@mosetta/identity';
|
|
3
|
+
import type { IIdentityRequestCaller } from '@mosetta/identity';
|
|
4
|
+
import { hostMediaPath } from '@mosetta/media/host';
|
|
5
|
+
import { AccessPolicy, ProjectAccess, ProjectAllowances } from '@mosetta/server-action/access';
|
|
6
|
+
import {
|
|
7
|
+
BLOCK_GIVEN_HEADER,
|
|
8
|
+
fullServerTileId,
|
|
9
|
+
HostContextCodec,
|
|
10
|
+
IDENTITY_HEADER,
|
|
11
|
+
SITE_HEADER,
|
|
12
|
+
} from '@mosetta/server-action/core';
|
|
13
|
+
import type { ICallerFetch, ISiteCode } from '@mosetta/server-action/core';
|
|
14
|
+
import {
|
|
15
|
+
CODE_GRANT,
|
|
16
|
+
MEDIA_GRANT,
|
|
17
|
+
PREVIEWS_GRANT,
|
|
18
|
+
REPOSITORIES_GRANT,
|
|
19
|
+
SERVICE_BLOCK_MAX,
|
|
20
|
+
ServiceProtocolCodec,
|
|
21
|
+
} from './protocol';
|
|
22
|
+
import type { IServiceActionAddress } from './protocol';
|
|
23
|
+
import { assertValidServiceOrigin, stripServiceRequestHeaders } from './serviceInvocation';
|
|
24
|
+
import type { IServiceInvocationPlan, IServicePublisherPorts, TServiceRun } from './serviceInvocation';
|
|
25
|
+
|
|
26
|
+
interface IFreshService {
|
|
27
|
+
readonly caller: IIdentityRequestCaller;
|
|
28
|
+
readonly grants: readonly (readonly string[])[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const BRAND_RE = /^[a-z][a-z0-9-]{0,54}$/;
|
|
32
|
+
const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]{1,40})?$/;
|
|
33
|
+
const PALETTE_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
34
|
+
const PERSONAL_MEMORY_ACTIONS = new Set([
|
|
35
|
+
'listConversations',
|
|
36
|
+
'readConversation',
|
|
37
|
+
'keepConversation',
|
|
38
|
+
'removeConversation',
|
|
39
|
+
'takeTask',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
function validatePlan(plan: IServiceInvocationPlan): IServiceInvocationPlan {
|
|
43
|
+
assertValidServiceOrigin(plan.consumerOrigin);
|
|
44
|
+
assertValidServiceOrigin(plan.publisherOrigin);
|
|
45
|
+
const grant = ServiceProtocolCodec.grantOf(plan.grant);
|
|
46
|
+
if (
|
|
47
|
+
!ProjectAllowances.isId(plan.consumerProjectId)
|
|
48
|
+
|| !ProjectAllowances.isId(plan.installation)
|
|
49
|
+
|| !BRAND_RE.test(plan.brand)
|
|
50
|
+
|| !VERSION_RE.test(plan.version)
|
|
51
|
+
|| !grant
|
|
52
|
+
|| (plan.block !== null && (typeof plan.block !== 'string' || plan.block.length > SERVICE_BLOCK_MAX))
|
|
53
|
+
) {
|
|
54
|
+
throw new IdentityError('INVALID_CONFIG');
|
|
55
|
+
}
|
|
56
|
+
return { ...plan, grant };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function validateDelegatedCaller(caller: IIdentityRequestCaller, consumerProjectId: string): void {
|
|
60
|
+
const { proof, person, current } = caller;
|
|
61
|
+
if (proof.expiresAt * 1000 <= Date.now()) throw new IdentityError('INVALID_PASS');
|
|
62
|
+
if (!Number.isSafeInteger(current.expiresAtMs) || (current.cacheable && current.expiresAtMs <= Date.now())) {
|
|
63
|
+
throw new IdentityError('IDENTITY_UNAVAILABLE');
|
|
64
|
+
}
|
|
65
|
+
const matchesIds = person.id === proof.personId
|
|
66
|
+
&& current.personId === proof.personId
|
|
67
|
+
&& current.sessionId === proof.sessionId
|
|
68
|
+
&& current.tokenId === proof.tokenId
|
|
69
|
+
&& current.projectId === consumerProjectId;
|
|
70
|
+
const allowancesValid = current.may.length > 0
|
|
71
|
+
&& current.may.every((allowance) => allowance.permission !== '*' && allowance.projectId === current.projectId);
|
|
72
|
+
if (proof.kind !== 'delegated' || current.kind !== 'delegated' || !matchesIds || !allowancesValid) {
|
|
73
|
+
throw new IdentityError('FORBIDDEN');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function escapeNonAscii(value: string): string {
|
|
78
|
+
return value.replace(/[\u007f-\uffff]/g, (letter) => `\\u${letter.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Pure per-event admission logic used inside the Root-owned private publisher entrypoint. */
|
|
82
|
+
export class PublisherServiceInvocation {
|
|
83
|
+
readonly plan: IServiceInvocationPlan;
|
|
84
|
+
|
|
85
|
+
constructor(plan: IServiceInvocationPlan, private readonly ports: IServicePublisherPorts) {
|
|
86
|
+
this.plan = validatePlan(plan);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private async fresh(): Promise<IFreshService> {
|
|
90
|
+
const [installation, connection, caller] = await Promise.all([
|
|
91
|
+
this.ports.installations.byId(this.plan.installation),
|
|
92
|
+
this.ports.connection(),
|
|
93
|
+
this.ports.caller(),
|
|
94
|
+
]);
|
|
95
|
+
const validInstallation = Boolean(
|
|
96
|
+
installation
|
|
97
|
+
&& installation.status === 'active'
|
|
98
|
+
&& installation.id === this.plan.installation
|
|
99
|
+
&& installation.consumer === this.plan.consumerOrigin
|
|
100
|
+
&& installation.brand === this.plan.brand
|
|
101
|
+
&& installation.version === this.plan.version,
|
|
102
|
+
);
|
|
103
|
+
const validConnection = Boolean(
|
|
104
|
+
connection
|
|
105
|
+
&& connection.installation === this.plan.installation
|
|
106
|
+
&& connection.brand === this.plan.brand
|
|
107
|
+
&& connection.publisher === this.plan.publisherOrigin
|
|
108
|
+
&& connection.version === this.plan.version,
|
|
109
|
+
);
|
|
110
|
+
if (!validInstallation || !validConnection) throw new IdentityError('FORBIDDEN');
|
|
111
|
+
validateDelegatedCaller(caller, this.plan.consumerProjectId);
|
|
112
|
+
return { caller, grants: [this.plan.grant, connection!.grant, installation!.grant] };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** An uncacheable answer is usable only for its fresh call, never carried over an awaited operation. */
|
|
116
|
+
private async beforeUse(fresh: IFreshService): Promise<IFreshService> {
|
|
117
|
+
if (!fresh.caller.current.cacheable) return this.fresh();
|
|
118
|
+
if (fresh.caller.proof.expiresAt * 1000 <= Date.now()) throw new IdentityError('INVALID_PASS');
|
|
119
|
+
if (fresh.caller.current.expiresAtMs <= Date.now()) throw new IdentityError('IDENTITY_UNAVAILABLE');
|
|
120
|
+
return fresh;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private async code(fresh: IFreshService): Promise<ISiteCode | null> {
|
|
124
|
+
if (!fresh.grants.every((grant) => grant.includes(CODE_GRANT)) || !this.ports.code) return null;
|
|
125
|
+
const code = await this.ports.code();
|
|
126
|
+
if (!code) return null;
|
|
127
|
+
if (code.projectId !== this.plan.consumerProjectId || !PALETTE_RE.test(code.palette)) {
|
|
128
|
+
throw new IdentityError('FORBIDDEN');
|
|
129
|
+
}
|
|
130
|
+
assertValidServiceOrigin(code.api);
|
|
131
|
+
return { api: code.api, palette: code.palette };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private module(request: Request): IServiceActionAddress {
|
|
135
|
+
const url = new URL(request.url);
|
|
136
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
137
|
+
if (
|
|
138
|
+
url.origin !== this.plan.publisherOrigin
|
|
139
|
+
|| !action
|
|
140
|
+
|| action.brand !== this.plan.brand
|
|
141
|
+
|| action.fullId !== fullServerTileId({ namespace: this.plan.brand, name: action.tile, version: this.plan.version })
|
|
142
|
+
) {
|
|
143
|
+
throw new IdentityError('FORBIDDEN');
|
|
144
|
+
}
|
|
145
|
+
return action;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async admit(request: Request, run: TServiceRun): Promise<Response> {
|
|
149
|
+
this.module(request);
|
|
150
|
+
await this.fresh();
|
|
151
|
+
const admitted = stripServiceRequestHeaders(request);
|
|
152
|
+
if (this.plan.block !== null) admitted.headers.set(BLOCK_GIVEN_HEADER, this.plan.block);
|
|
153
|
+
return run(admitted, async (selected, target) => {
|
|
154
|
+
const action = this.module(selected);
|
|
155
|
+
if (target.moduleId !== action.fullId || target.endpoint) throw new IdentityError('FORBIDDEN');
|
|
156
|
+
let fresh = await this.fresh();
|
|
157
|
+
const code = await this.code(fresh);
|
|
158
|
+
const resources = this.ports.resources ? await this.ports.resources(target) : {};
|
|
159
|
+
const callerOutbound = await this.ports.callback(target);
|
|
160
|
+
fresh = await this.beforeUse(fresh);
|
|
161
|
+
const { proof, person, current } = fresh.caller;
|
|
162
|
+
const access = { projectId: current.projectId, scopeIds: current.scopeIds };
|
|
163
|
+
const safe = { ...person, kind: proof.kind, sessionId: proof.sessionId, tokenId: proof.tokenId, through: [...proof.via], may: current.may, access };
|
|
164
|
+
const inward = stripServiceRequestHeaders(selected);
|
|
165
|
+
const headers = new Headers(inward.headers);
|
|
166
|
+
headers.set(IDENTITY_HEADER, escapeNonAscii(JSON.stringify({
|
|
167
|
+
via: 'service',
|
|
168
|
+
installation: this.plan.installation,
|
|
169
|
+
site: this.plan.consumerOrigin,
|
|
170
|
+
kind: proof.kind,
|
|
171
|
+
sessionId: proof.sessionId,
|
|
172
|
+
tokenId: proof.tokenId,
|
|
173
|
+
through: [...proof.via],
|
|
174
|
+
person: safe,
|
|
175
|
+
})));
|
|
176
|
+
headers.set(SITE_HEADER, HostContextCodec.encodeSite({
|
|
177
|
+
origin: this.plan.consumerOrigin,
|
|
178
|
+
...(code && fresh.grants.every((grant) => grant.includes(CODE_GRANT)) ? { code } : {}),
|
|
179
|
+
}));
|
|
180
|
+
return { ...resources, request: ProjectAccess.withContext(new Request(inward, { headers }), access), callerOutbound };
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private authorizeCodeCallback(request: Request, url: URL, context: { readonly fresh: IFreshService; readonly code: ISiteCode }): void {
|
|
185
|
+
const { fresh, code } = context;
|
|
186
|
+
if (!fresh.grants.every((set) => set.includes(CODE_GRANT))) throw new IdentityError('FORBIDDEN');
|
|
187
|
+
const source = new RegExp(`^/v1/palettes/${code.palette}/(sources|check|draft|release)$`).exec(url.pathname);
|
|
188
|
+
const built = new RegExp(`^/v1/code/palettes/${code.palette}/(plan|push|draft|drafts)$`).exec(url.pathname);
|
|
189
|
+
const build = url.pathname === `/v1/builds/palettes/${code.palette}`;
|
|
190
|
+
const readSources = source?.[1] === 'sources' && request.method === 'GET';
|
|
191
|
+
if ((!source && !built && !build) || (!readSources && request.method !== 'POST')) {
|
|
192
|
+
throw new IdentityError('FORBIDDEN');
|
|
193
|
+
}
|
|
194
|
+
const operation = source?.[1] === 'release' || (built && ['plan', 'push'].includes(built[1]))
|
|
195
|
+
? 'code.release'
|
|
196
|
+
: 'code.edit';
|
|
197
|
+
const policy = new AccessPolicy(fresh.caller.current.projectId, fresh.caller.current.scopeIds);
|
|
198
|
+
if (!policy.can(fresh.caller.current, operation, '*')) throw new IdentityError('FORBIDDEN');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private authorizeDoorCallback(request: Request, url: URL, fresh: IFreshService): void {
|
|
202
|
+
const door = url.pathname === '/__mosetta__/preview/share'
|
|
203
|
+
? PREVIEWS_GRANT
|
|
204
|
+
: hostMediaPath(url.pathname)
|
|
205
|
+
? MEDIA_GRANT
|
|
206
|
+
: url.pathname === '/__mosetta__/repositories'
|
|
207
|
+
? REPOSITORIES_GRANT
|
|
208
|
+
: null;
|
|
209
|
+
if (door === MEDIA_GRANT && !this.ports.contentAllowed?.()) throw new IdentityError('FORBIDDEN');
|
|
210
|
+
const methodOk = door === REPOSITORIES_GRANT
|
|
211
|
+
? request.method === 'GET'
|
|
212
|
+
: door === MEDIA_GRANT && url.pathname.startsWith('/__mosetta__/media/resource/')
|
|
213
|
+
? ['GET', 'HEAD'].includes(request.method)
|
|
214
|
+
: request.method === 'POST';
|
|
215
|
+
if (!door || !fresh.grants.every((set) => set.includes(door)) || !methodOk) {
|
|
216
|
+
throw new IdentityError('FORBIDDEN');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private async dispatchReadCallback(
|
|
221
|
+
request: Request,
|
|
222
|
+
url: URL,
|
|
223
|
+
context: { readonly fresh: IFreshService; readonly send: ICallerFetch },
|
|
224
|
+
): Promise<Response | null> {
|
|
225
|
+
if (request.method !== 'GET') return null;
|
|
226
|
+
const { fresh, send } = context;
|
|
227
|
+
if (url.pathname === '/__mosetta__/project') {
|
|
228
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
229
|
+
}
|
|
230
|
+
if (url.pathname === '/__mosetta__/scopes' && fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, 'mosetta-editor', 'content'))) {
|
|
231
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
232
|
+
}
|
|
233
|
+
if (url.pathname === '/api/server-action/') {
|
|
234
|
+
let answer = await send.fetch(stripServiceRequestHeaders(request));
|
|
235
|
+
for (const grant of fresh.grants) answer = await ServiceProtocolCodec.grantedListing(answer, grant);
|
|
236
|
+
return answer;
|
|
237
|
+
}
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async dispatchConsumerCallback(request: Request, url: URL, context: { readonly fresh: IFreshService; readonly send: ICallerFetch }): Promise<Response> {
|
|
242
|
+
const { fresh, send } = context;
|
|
243
|
+
if (url.pathname === PROJECT_MEMORY_PATH || url.pathname === CONTENT_COMMAND_PATH) {
|
|
244
|
+
const tile = url.pathname === PROJECT_MEMORY_PATH ? 'memory' : 'content';
|
|
245
|
+
const allowed = fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, 'mosetta-editor', tile));
|
|
246
|
+
if (request.method !== 'POST' || !this.ports.contentAllowed?.() || !allowed) {
|
|
247
|
+
throw new IdentityError('FORBIDDEN');
|
|
248
|
+
}
|
|
249
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
250
|
+
}
|
|
251
|
+
const readHandled = await this.dispatchReadCallback(request, url, context);
|
|
252
|
+
if (readHandled) return readHandled;
|
|
253
|
+
const action = ServiceProtocolCodec.actionOfPath(url.pathname);
|
|
254
|
+
if (action) {
|
|
255
|
+
const allowed = fresh.grants.every((grant) => ServiceProtocolCodec.grantAllows(grant, action.brand, action.tile));
|
|
256
|
+
if (
|
|
257
|
+
request.method !== 'POST'
|
|
258
|
+
|| (action.tile === 'memory' && PERSONAL_MEMORY_ACTIONS.has(action.action))
|
|
259
|
+
|| !allowed
|
|
260
|
+
) {
|
|
261
|
+
throw new IdentityError('FORBIDDEN');
|
|
262
|
+
}
|
|
263
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
264
|
+
}
|
|
265
|
+
this.authorizeDoorCallback(request, url, fresh);
|
|
266
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Install this guard inside the Root-owned callback WorkerEntrypoint; never serialize this class as a port. */
|
|
270
|
+
async callback(request: Request, send: ICallerFetch): Promise<Response> {
|
|
271
|
+
let fresh = await this.fresh();
|
|
272
|
+
if (request.headers.has('authorization') || request.headers.has('cookie')) {
|
|
273
|
+
throw new IdentityError('FORBIDDEN');
|
|
274
|
+
}
|
|
275
|
+
const url = new URL(request.url);
|
|
276
|
+
if (url.username || url.password || url.hash) throw new IdentityError('FORBIDDEN');
|
|
277
|
+
const code = await this.code(fresh);
|
|
278
|
+
fresh = await this.beforeUse(fresh);
|
|
279
|
+
if (code && url.origin === code.api) {
|
|
280
|
+
this.authorizeCodeCallback(request, url, { fresh, code });
|
|
281
|
+
return send.fetch(stripServiceRequestHeaders(request));
|
|
282
|
+
}
|
|
283
|
+
if (url.origin !== this.plan.consumerOrigin) throw new IdentityError('FORBIDDEN');
|
|
284
|
+
return this.dispatchConsumerCallback(request, url, { fresh, send });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { IdentityError, ProjectCataloguePolicy } from '@mosetta/identity';
|
|
2
|
+
import type { IProjectIoOperation, IProjectRecord, ISqlDatabase, SqlProjectIo } from '@mosetta/tenancy';
|
|
3
|
+
import type { IServiceConnection, IServicesComposition } from './protocol';
|
|
4
|
+
|
|
5
|
+
/** Configuration for `GuardedServiceComposition`. */
|
|
6
|
+
export interface IGuardedServiceCompositionOptions {
|
|
7
|
+
readonly db: ISqlDatabase;
|
|
8
|
+
readonly operation: IProjectIoOperation;
|
|
9
|
+
readonly executor: SqlProjectIo;
|
|
10
|
+
readonly handle: object;
|
|
11
|
+
readonly publisher: (origin: string) => Promise<IProjectRecord | null>;
|
|
12
|
+
readonly transitioned: (previous: number, next: number) => void;
|
|
13
|
+
readonly defaults?: ReadonlySet<string>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Actual affected-project configuration mutation; no application SQL or HTTP metadata enters it. */
|
|
17
|
+
export class GuardedServiceComposition implements IServicesComposition {
|
|
18
|
+
private readonly db: ISqlDatabase;
|
|
19
|
+
|
|
20
|
+
private readonly operation: IProjectIoOperation;
|
|
21
|
+
|
|
22
|
+
private readonly executor: SqlProjectIo;
|
|
23
|
+
|
|
24
|
+
private readonly handle: object;
|
|
25
|
+
|
|
26
|
+
private readonly publisher: (origin: string) => Promise<IProjectRecord | null>;
|
|
27
|
+
|
|
28
|
+
private readonly transitioned: (previous: number, next: number) => void;
|
|
29
|
+
|
|
30
|
+
private readonly defaults?: ReadonlySet<string>;
|
|
31
|
+
|
|
32
|
+
constructor(options: IGuardedServiceCompositionOptions) {
|
|
33
|
+
this.db = options.db;
|
|
34
|
+
this.operation = options.operation;
|
|
35
|
+
this.executor = options.executor;
|
|
36
|
+
this.handle = options.handle;
|
|
37
|
+
this.publisher = options.publisher;
|
|
38
|
+
this.transitioned = options.transitioned;
|
|
39
|
+
this.defaults = options.defaults;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async attach(connection: IServiceConnection): Promise<boolean> {
|
|
43
|
+
if (this.defaults && !this.defaults.has(`${connection.brand}\n${connection.publisher}`)) {
|
|
44
|
+
throw new IdentityError('FORBIDDEN');
|
|
45
|
+
}
|
|
46
|
+
const publisher = await this.publisher(connection.publisher);
|
|
47
|
+
if (!publisher || publisher.status !== 'active' || publisher.ready !== true) {
|
|
48
|
+
throw new IdentityError('FORBIDDEN');
|
|
49
|
+
}
|
|
50
|
+
const digest = await ProjectCataloguePolicy.hash(
|
|
51
|
+
JSON.stringify(['service.attach', connection.brand, connection.publisher, publisher.id]),
|
|
52
|
+
);
|
|
53
|
+
const step = crypto.randomUUID();
|
|
54
|
+
await this.executor.commit(this.handle, step, digest, () => [
|
|
55
|
+
this.db.prepare(
|
|
56
|
+
'INSERT INTO palette_attachments(project_id,brand,attached_at,served_by) SELECT ?,t.brand,?,? FROM tile_palettes t JOIN projects publisher ON publisher.id=t.project_id '
|
|
57
|
+
+ 'WHERE t.brand=? AND t.project_id=? AND t.project_id<>? AND publisher.status=\'active\' AND publisher.ready=1 '
|
|
58
|
+
+ 'ON CONFLICT(project_id,brand) DO UPDATE SET served_by=excluded.served_by WHERE palette_attachments.served_by IS NOT excluded.served_by',
|
|
59
|
+
).bind(
|
|
60
|
+
this.operation.target.projectId,
|
|
61
|
+
connection.at,
|
|
62
|
+
connection.publisher,
|
|
63
|
+
connection.brand,
|
|
64
|
+
publisher.id,
|
|
65
|
+
this.operation.target.projectId,
|
|
66
|
+
),
|
|
67
|
+
this.db.prepare(
|
|
68
|
+
'INSERT INTO project_io_assert(required) SELECT NULL WHERE changes()<>1 AND NOT EXISTS(SELECT 1 FROM palette_attachments WHERE project_id=? AND brand=? AND served_by=?)',
|
|
69
|
+
).bind(this.operation.target.projectId, connection.brand, connection.publisher),
|
|
70
|
+
...this.receipt(step),
|
|
71
|
+
]);
|
|
72
|
+
await this.record(step);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async detach(brand: string): Promise<void> {
|
|
77
|
+
if (this.defaults) throw new IdentityError('FORBIDDEN');
|
|
78
|
+
const digest = await ProjectCataloguePolicy.hash(JSON.stringify(['service.detach', brand]));
|
|
79
|
+
const step = crypto.randomUUID();
|
|
80
|
+
await this.executor.commit(this.handle, step, digest, () => [
|
|
81
|
+
this.db.prepare('DELETE FROM palette_attachments WHERE project_id=? AND brand=? AND served_by IS NOT NULL')
|
|
82
|
+
.bind(this.operation.target.projectId, brand),
|
|
83
|
+
...this.receipt(step),
|
|
84
|
+
]);
|
|
85
|
+
await this.record(step);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private receipt(step: string): ReturnType<ISqlDatabase['prepare']>[] {
|
|
89
|
+
const { projectId, sourceKey, sourceGeneration } = this.operation.target;
|
|
90
|
+
return [
|
|
91
|
+
this.db.prepare(
|
|
92
|
+
'INSERT INTO project_io_configuration_steps(operation_id,step_id,previous_generation,next_generation) '
|
|
93
|
+
+ 'SELECT ?,?,?,source_generation FROM project_resource_catalogues WHERE project_id=? AND source_key=? AND source_generation IN(?,?+1)',
|
|
94
|
+
).bind(this.operation.id, step, sourceGeneration, projectId, sourceKey, sourceGeneration, sourceGeneration),
|
|
95
|
+
this.db.prepare('INSERT INTO project_io_assert(required) SELECT NULL WHERE changes()<>1'),
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private async record(step: string): Promise<void> {
|
|
100
|
+
const row = await this.db
|
|
101
|
+
.prepare('SELECT previous_generation,next_generation FROM project_io_configuration_steps WHERE operation_id=? AND step_id=?')
|
|
102
|
+
.bind(this.operation.id, step)
|
|
103
|
+
.first<{ previous_generation: number; next_generation: number }>();
|
|
104
|
+
if (!row || row.previous_generation !== this.operation.target.sourceGeneration) {
|
|
105
|
+
throw new IdentityError('FORBIDDEN');
|
|
106
|
+
}
|
|
107
|
+
this.transitioned(row.previous_generation, row.next_generation);
|
|
108
|
+
}
|
|
109
|
+
}
|