@serve.zone/interfaces 32.117.0 → 32.119.0

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,209 @@
1
+ import { readDataElements, readExactDataRecord } from '../private/dataproperties.js';
2
+ import { hostedAppRuntimeIdentityKeys } from './hostedapp.js';
3
+
4
+ /** The environment Cloudly requires at startup, as verified by its `qenv.yml`. */
5
+ export const cloudlyHostContractRequiredEnvVars = Object.freeze({
6
+ /**
7
+ * The deployment environment. Production hosts set `production`; any other value turns on
8
+ * development reloading. The value is fixed for the life of a database: Cloudly binds it into
9
+ * the credentials and sessions it stores.
10
+ */
11
+ environment: 'SERVEZONE_ENVIRONMENT',
12
+ /**
13
+ * The origin clients reach Cloudly under: `http` or `https`, with an optional port, and no path,
14
+ * query or fragment. Ingress passes the request's `Host` unchanged, so it equals this origin's
15
+ * `host[:port]`.
16
+ */
17
+ publicOrigin: 'SERVEZONE_PUBLIC_ORIGIN',
18
+ /**
19
+ * `external` (TLS is terminated in front of Cloudly) or `none`. Cloudly terminates no TLS itself.
20
+ */
21
+ sslMode: 'SERVEZONE_SSLMODE',
22
+ /**
23
+ * The path of the secret keyring file. The host delivers it as a private file: a regular file
24
+ * that is not a symlink, has one hard link, is owned by the process user and grants no group or
25
+ * other permission, in a directory owned by that user that neither group nor others may write.
26
+ * This is the host's obligation; the Cloudly server does not check it yet.
27
+ */
28
+ secretKeyringPath: 'SERVEZONE_SECRET_KEYRING_PATH',
29
+ /** The MongoDB connection URL of Cloudly's database. */
30
+ mongoDbUrl: 'MONGODB_URL',
31
+ /** The S3 endpoint of Cloudly's object storage. */
32
+ s3Endpoint: 'S3_ENDPOINT',
33
+ /** The S3 access key. */
34
+ s3AccessKey: 'S3_ACCESSKEY',
35
+ /** The S3 secret key. */
36
+ s3SecretKey: 'S3_SECRETKEY',
37
+ /** The bucket Cloudly keeps its objects in; Cloudly creates it when it does not exist. */
38
+ s3Bucket: 'S3_BUCKET',
39
+ } as const);
40
+
41
+ export const cloudlyHostContractRequiredEnvVarList = Object.freeze(
42
+ Object.values(cloudlyHostContractRequiredEnvVars),
43
+ );
44
+ export type TCloudlyHostRequiredEnvVar = typeof cloudlyHostContractRequiredEnvVarList[number];
45
+
46
+ /**
47
+ * Optional configuration. Both lists exclude `SERVEZONE_ADMINACCOUNT` (deprecated bootstrap)
48
+ * and `SERVEZONE_APP_HOST_TYPE` (display only).
49
+ */
50
+ export const cloudlyHostContractOptionalEnvVars = Object.freeze({
51
+ /** The port the server binds; `cloudlyDefaultListenPort` when unset. */
52
+ listenPort: 'SERVEZONE_LISTENPORT',
53
+ /**
54
+ * The path of the WorkloadInit release approval file, a private file under the same rules as
55
+ * the secret keyring. Unset, the requests that need an approval answer
56
+ * `workloadinit-unconfigured`.
57
+ */
58
+ workloadInitApprovalPath: 'SERVEZONE_WORKLOADINIT_APPROVAL_PATH',
59
+ /** Optional member of the Mongo descriptor (database name). */
60
+ mongoDbName: 'MONGODB_NAME',
61
+ /** Optional member of the Mongo descriptor (user). */
62
+ mongoDbUser: 'MONGODB_USER',
63
+ /** Optional member of the Mongo descriptor (password). */
64
+ mongoDbPass: 'MONGODB_PASS',
65
+ /** The S3 port. This contract states no default. */
66
+ s3Port: 'S3_PORT',
67
+ /** Whether S3 is reached over TLS (`true` or `false`). This contract states no default. */
68
+ s3UseSsl: 'S3_USESSL',
69
+ /**
70
+ * The host channel of a hosted Cloudly, together with `SERVEZONE_APP_CONTROL_TOKEN`
71
+ * (`hostedAppRuntimeIdentityKeys`). Cloudly counts as hosted only while both are set.
72
+ */
73
+ runtimeUrl: hostedAppRuntimeIdentityKeys.runtimeUrl,
74
+ /** The host's machine JWT for the host channel, delivered as a secret. */
75
+ controlToken: hostedAppRuntimeIdentityKeys.controlToken,
76
+ platformOidcIssuer: 'SERVEZONE_PLATFORM_OIDC_ISSUER',
77
+ platformOidcClientId: 'SERVEZONE_PLATFORM_OIDC_CLIENT_ID',
78
+ platformOidcClientSecret: 'SERVEZONE_PLATFORM_OIDC_CLIENT_SECRET',
79
+ platformOidcRedirectUri: 'SERVEZONE_PLATFORM_OIDC_REDIRECT_URI',
80
+ platformOidcAudience: 'SERVEZONE_PLATFORM_OIDC_AUDIENCE',
81
+ /** The schedule of the backup of every service; unset, Cloudly schedules no backup. */
82
+ backupCron: 'CLOUDLY_BACKUP_CRON',
83
+ /** How many backups of a service the retention keeps; `24` when unset. */
84
+ backupKeepLast: 'CLOUDLY_BACKUP_KEEP_LAST',
85
+ /**
86
+ * The interval of the periodic BaseOS image build cleanup in milliseconds; 43,200,000 (12 hours)
87
+ * when unset. A value that is not a positive number turns the periodic cleanup off.
88
+ */
89
+ baseOsImageCleanupIntervalMs: 'CLOUDLY_BASEOS_IMAGE_CLEANUP_INTERVAL_MS',
90
+ /**
91
+ * This controller site's own origin (Linus rulings 69 Q3 and 79 Q1): a canonical `https` origin
92
+ * (`data.validateControllerOrigin`), the `IControllerPeerSet.activeOrigin` this site states while
93
+ * it is active and the origin the witness names it by. While unset, the site counts as
94
+ * `SERVEZONE_PUBLIC_ORIGIN`, but only while the controller row lists no shadow; once it lists one,
95
+ * a start refuses an unset value or one equal to `SERVEZONE_PUBLIC_ORIGIN`. A fact about this one
96
+ * site, never stored in the replicated controller database.
97
+ */
98
+ siteOrigin: 'SERVEZONE_SITE_ORIGIN',
99
+ /**
100
+ * The canonical `https` origin of the witness this site reads (`requests.witness`). Set together
101
+ * with `SERVEZONE_WITNESS_BEARER_PATH` or not at all: a start with only one of them is refused,
102
+ * naming the one that is unset. Required once the controller row lists another site as a shadow.
103
+ */
104
+ witnessOrigin: 'SERVEZONE_WITNESS_ORIGIN',
105
+ /**
106
+ * The path of this site's witness bearer, a private file under the rules of the secret keyring
107
+ * (`SERVEZONE_SECRET_KEYRING_PATH`) holding the 43-character base64url of 32 random bytes
108
+ * (`data.witnessContract.bearerRandomBytes`). The host creates it; Cloudly only reads it and
109
+ * hashes it, never writes or logs it. Set together with `SERVEZONE_WITNESS_ORIGIN` or not at all.
110
+ */
111
+ witnessBearerPath: 'SERVEZONE_WITNESS_BEARER_PATH',
112
+ /**
113
+ * The port of Cloudly's relayed listener (Linus ruling 141 C7), a second port beside
114
+ * `SERVEZONE_LISTENPORT` that the host's relay ingress forwards to, and only to. Relayedness is
115
+ * the accepting listener, so this port serves the human surface only: the UI, human sign-in and
116
+ * human typed requests, never machine endpoints or Destroy. This contract states no default. A
117
+ * host that advertises `relayIngress` (`cloudlyHostExtras`) sets it together with
118
+ * `SERVEZONE_RELAY_INGRESS_ADDRESS`.
119
+ */
120
+ relayedListenPort: 'SERVEZONE_RELAYED_LISTENPORT',
121
+ /**
122
+ * Where Cloudly's cloud access connector dials the host's relay ingress (Linus ruling 141 C6 and
123
+ * C7, amendment 141a point 4): `<host>:<port>`, an IPv6 address in brackets
124
+ * (`[2001:db8::1]:8443`). The relay ingress is the host's second listener, reachable from the
125
+ * Cloudly container, that serves `SERVEZONE_PUBLIC_ORIGIN`'s TLS and forwards only to
126
+ * `SERVEZONE_RELAYED_LISTENPORT`. The connector never dials the public origin by name, whose
127
+ * public DNS points at the relay, nor an address taken from a request. A host that advertises
128
+ * `relayIngress` sets it together with `SERVEZONE_RELAYED_LISTENPORT`.
129
+ */
130
+ relayIngressAddress: 'SERVEZONE_RELAY_INGRESS_ADDRESS',
131
+ } as const);
132
+
133
+ export const cloudlyHostContractOptionalEnvVarList = Object.freeze(
134
+ Object.values(cloudlyHostContractOptionalEnvVars),
135
+ );
136
+ export type TCloudlyHostOptionalEnvVar = typeof cloudlyHostContractOptionalEnvVarList[number];
137
+
138
+ /** Standard optional offers. These are separate from the advertised extras. */
139
+ export const cloudlyHostStandardOffers = Object.freeze([
140
+ 'hosted-runtime-identity',
141
+ 'backups',
142
+ 'local-node',
143
+ 'shadow-pairing',
144
+ ] as const);
145
+
146
+ /** Closed vocabulary for the versioned host advertisement. */
147
+ export const cloudlyHostExtraCapabilities = Object.freeze([
148
+ 'relayIngress',
149
+ ] as const);
150
+ export type TCloudlyHostExtraCapability = typeof cloudlyHostExtraCapabilities[number];
151
+
152
+ export interface ICloudlyHostAdvertisedExtras {
153
+ readonly contractVersion: 1;
154
+ readonly capabilities: readonly TCloudlyHostExtraCapability[];
155
+ }
156
+
157
+ const advertisedExtrasContractVersion = 1;
158
+ const advertisedExtrasKeys = ['contractVersion', 'capabilities'] as const satisfies
159
+ readonly (keyof ICloudlyHostAdvertisedExtras)[];
160
+ const isCloudlyHostExtraCapability = (valueArg: unknown): valueArg is TCloudlyHostExtraCapability =>
161
+ (cloudlyHostExtraCapabilities as readonly unknown[]).includes(valueArg);
162
+
163
+ const readCloudlyHostAdvertisedExtras = (valueArg: unknown): ICloudlyHostAdvertisedExtras | string => {
164
+ const record = readExactDataRecord(valueArg, advertisedExtrasKeys);
165
+ if (record === null) {
166
+ return 'Cloudly host advertised extras must be an object with exactly contractVersion and capabilities';
167
+ }
168
+ if (record.contractVersion !== advertisedExtrasContractVersion) {
169
+ return 'Cloudly host advertised extras contractVersion must be 1';
170
+ }
171
+
172
+ const elements = readDataElements(record.capabilities, cloudlyHostExtraCapabilities.length);
173
+ if (elements === null || new Set(elements).size !== elements.length) {
174
+ return 'Cloudly host advertised extras capabilities must be a dense array of unique capabilities';
175
+ }
176
+ if (!elements.every(isCloudlyHostExtraCapability)) {
177
+ return 'Cloudly host advertised extras contains an unknown capability';
178
+ }
179
+ return { contractVersion: advertisedExtrasContractVersion, capabilities: elements };
180
+ };
181
+
182
+ /** Validate a stated advertisement. Only normalization accepts absence. */
183
+ export const validateCloudlyHostAdvertisedExtras = (valueArg: unknown): string[] => {
184
+ const result = readCloudlyHostAdvertisedExtras(valueArg);
185
+ return typeof result === 'string' ? [result] : [];
186
+ };
187
+
188
+ /** No host channel or advertisement means no extras. A malformed advertisement throws. */
189
+ export const normalizeCloudlyHostAdvertisedExtras = (
190
+ valueArg: unknown,
191
+ ): ICloudlyHostAdvertisedExtras => {
192
+ if (valueArg === undefined || valueArg === null) {
193
+ return { contractVersion: advertisedExtrasContractVersion, capabilities: [] };
194
+ }
195
+ const result = readCloudlyHostAdvertisedExtras(valueArg);
196
+ if (typeof result === 'string') {
197
+ throw new Error(result);
198
+ }
199
+ return result;
200
+ };
201
+
202
+ /** Only a valid advertisement can offer a capability. */
203
+ export const hasCloudlyHostExtraCapability = (
204
+ extrasArg: ICloudlyHostAdvertisedExtras | null | undefined,
205
+ capabilityArg: TCloudlyHostExtraCapability,
206
+ ): boolean => {
207
+ const result = readCloudlyHostAdvertisedExtras(extrasArg);
208
+ return typeof result !== 'string' && result.capabilities.includes(capabilityArg);
209
+ };
@@ -1,4 +1,5 @@
1
1
  import { isCanonicalBase64url32 } from '../private/bearerencoding.js';
2
+ import { canonicalizeStrictJson } from '../private/canonicaljson.js';
2
3
  import { validateControllerIdentifier } from '../private/controllercontract.js';
3
4
  import { readExactDataRecord } from '../private/dataproperties.js';
4
5
  import { isClusterNodeId } from '../private/nodeidentifier.js';
@@ -11,6 +12,10 @@ export const diskEncryptionContract = Object.freeze({
11
12
  maximumSilenceLimitMs: 86_400_000,
12
13
  challengeTtlMs: 60_000,
13
14
  digestDomain: 'serve.zone/disk-encryption-key-release',
15
+ /** HKDF-SHA256 `info` of a released key's wrap (`TDiskEncryptionKeyReleaseOutcome`). */
16
+ wrapInfo: 'serve.zone/disk-encryption-key-release/aes-256-gcm',
17
+ /** Both algorithms' signatures: `ecdsa-p256` as IEEE P1363 `r || s`, `ed25519` as RFC 8032. */
18
+ signatureBytes: 64,
14
19
  });
15
20
 
16
21
  const machineKinds = ['node', 'dcrouter', 'oneboxHost'] as const;
@@ -157,6 +162,57 @@ const publicKeyOf = (value: unknown): string => {
157
162
  return value;
158
163
  };
159
164
 
165
+ /** The members of a key release proof its signature covers, with the challenge's nonce. */
166
+ export interface IDiskEncryptionKeyReleaseSignedFields {
167
+ challengeId: string;
168
+ nonceBase64Url: string;
169
+ machineId: string;
170
+ ephemeralPublicKeyPem: string;
171
+ }
172
+
173
+ /**
174
+ * The exact bytes a machine signs to release its disk key, and Cloudly verifies: the UTF-8 strict
175
+ * canonical JSON (keys in UTF-16 code unit order) of `{ domain, challengeId, nonceBase64Url,
176
+ * machineId, ephemeralPublicKeyPem }`, with `domain` = `diskEncryptionContract.digestDomain`. The
177
+ * ephemeral public key is the PEM string exactly as the proof carries it, never re-encoded, so a
178
+ * `\r\n` PEM signs other bytes than a `\n` one.
179
+ *
180
+ * The proof digest is the SHA-256 of these bytes (`computeDiskEncryptionKeyReleaseDigest`). Both
181
+ * algorithms sign that 32-byte digest and encode a `signatureBytes` signature as unpadded base64url:
182
+ * `ecdsa-p256` is ECDSA over the digest as a prehashed SHA-256 value (a TPM2_Sign of the digest,
183
+ * which verifies as ECDSA-SHA256 over these bytes), `r || s` (IEEE P1363); `ed25519` is PureEdDSA
184
+ * with the 32-byte digest as its message.
185
+ *
186
+ * A released key is wrapped to the proof's ephemeral P-256 key: the raw ECDH shared secret of a
187
+ * fresh controller P-256 key pair (`controllerPublicKeyPem`), HKDF-SHA256 with salt = proof digest,
188
+ * info = `diskEncryptionContract.wrapInfo` and 32 output bytes, then AES-256-GCM with the 96-bit IV
189
+ * and the proof digest as additional authenticated data.
190
+ */
191
+ export const createDiskEncryptionKeyReleaseMessage = (fieldsArg: IDiskEncryptionKeyReleaseSignedFields): Uint8Array => {
192
+ const fields = exact(fieldsArg, ['challengeId', 'nonceBase64Url', 'machineId', 'ephemeralPublicKeyPem']);
193
+ const { nonceBase64Url } = fields;
194
+ if (typeof nonceBase64Url !== 'string' || nonceBase64Url.length !== 43 || !isCanonicalBase64url32(nonceBase64Url)) {
195
+ return invalid();
196
+ }
197
+ return new TextEncoder().encode(canonicalizeStrictJson({
198
+ domain: diskEncryptionContract.digestDomain,
199
+ challengeId: identifier(fields.challengeId),
200
+ nonceBase64Url,
201
+ machineId: machineIdOf(fields.machineId),
202
+ ephemeralPublicKeyPem: publicKeyOf(fields.ephemeralPublicKeyPem),
203
+ }, invalid, 'disk encryption key release'));
204
+ };
205
+
206
+ /** The 32-byte proof digest: SHA-256 of `createDiskEncryptionKeyReleaseMessage`, through Web Crypto. */
207
+ export const computeDiskEncryptionKeyReleaseDigest = async (
208
+ fieldsArg: IDiskEncryptionKeyReleaseSignedFields,
209
+ ): Promise<Uint8Array> => {
210
+ const message = createDiskEncryptionKeyReleaseMessage(fieldsArg);
211
+ const subtle = globalThis.crypto?.subtle;
212
+ if (!subtle) throw new Error('Web Crypto SHA-256 is unavailable in this runtime.');
213
+ return new Uint8Array(await subtle.digest('SHA-256', new Uint8Array(message)));
214
+ };
215
+
160
216
  export const snapshotDiskEncryptionRefusal = (value: unknown): TDiskEncryptionRefusal => choice(value, diskEncryptionRefusals);
161
217
 
162
218
  export const snapshotDiskEncryptionSilenceLimitMs = (value: unknown): number =>
@@ -1,3 +1,5 @@
1
+ import type { ICloudlyHostAdvertisedExtras } from './cloudlyhostcontract.js';
2
+
1
3
  /**
2
4
  * The kind of host running a hosted app (`onebox`, `cloudly`, or another host's name), for display
3
5
  * only: never branch on it. A host's capabilities reach an app only through the extras the host
@@ -438,6 +440,8 @@ export interface IHostedAppLifecycleState extends IHostedAppLifecycleReport {
438
440
  * nothing, and so does a list the validator refuses.
439
441
  */
440
442
  hostExtras?: string[];
443
+ /** Optional host-owned advertisement in the Cloudly host contract's closed format. */
444
+ advertisedExtras?: ICloudlyHostAdvertisedExtras;
441
445
  }
442
446
 
443
447
  type THostedAppBootstrapActionServerFields =
@@ -471,7 +475,7 @@ const hostedAppLifecycleReportKeys: ReadonlySet<string> = new Set<
471
475
 
472
476
  const hostedAppLifecycleHostOwnedKeys: ReadonlySet<string> = new Set<
473
477
  Exclude<keyof IHostedAppLifecycleState, keyof IHostedAppLifecycleReport>
474
- >(['appInstanceId', 'hostType', 'reportedAt', 'bootstrapAction', 'upgradeState', 'hostExtras']);
478
+ >(['appInstanceId', 'hostType', 'reportedAt', 'bootstrapAction', 'upgradeState', 'hostExtras', 'advertisedExtras']);
475
479
 
476
480
  const hostedAppCapabilityRegex = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,99}$/;
477
481
  const hostedAppNameListMaximumLength = 64;
package/ts/data/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './cloudaccess.js';
2
2
  export * from './cloudlyconfig.js';
3
+ export * from './cloudlyhostcontract.js';
3
4
  export * from './cluster.js';
4
5
  export * from './clusterruntime.js';
5
6
  export * from './clustervpn.js';