@serve.zone/interfaces 32.121.1 → 32.123.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.
Files changed (35) hide show
  1. package/changelog.md +12 -0
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/data/corestoredata.d.ts +87 -0
  4. package/dist_ts/data/corestoredata.js +164 -0
  5. package/dist_ts/data/delegatedadmintoken.d.ts +10 -1
  6. package/dist_ts/data/delegatedadmintoken.js +22 -3
  7. package/dist_ts/data/index.d.ts +3 -0
  8. package/dist_ts/data/index.js +4 -1
  9. package/dist_ts/data/palletworkspace.d.ts +59 -0
  10. package/dist_ts/data/palletworkspace.js +39 -0
  11. package/dist_ts/data/serviceadmintoken.d.ts +101 -0
  12. package/dist_ts/data/serviceadmintoken.js +150 -0
  13. package/dist_ts/data/settings.d.ts +2 -0
  14. package/dist_ts/data/settings.js +3 -1
  15. package/dist_ts/requests/admin.d.ts +39 -0
  16. package/dist_ts/requests/corestore.d.ts +75 -0
  17. package/dist_ts/requests/corestore.js +1 -1
  18. package/dist_ts/requests/runtimesession.d.ts +38 -0
  19. package/dist_ts/runtime.d.ts +1 -0
  20. package/dist_ts/runtime.js +2 -1
  21. package/dist_ts/runtime.serviceadmintoken.d.ts +66 -0
  22. package/dist_ts/runtime.serviceadmintoken.js +293 -0
  23. package/package.json +8 -7
  24. package/ts/00_commitinfo_data.ts +1 -1
  25. package/ts/data/corestoredata.ts +255 -0
  26. package/ts/data/delegatedadmintoken.ts +23 -2
  27. package/ts/data/index.ts +3 -0
  28. package/ts/data/palletworkspace.ts +90 -0
  29. package/ts/data/serviceadmintoken.ts +263 -0
  30. package/ts/data/settings.ts +2 -0
  31. package/ts/requests/admin.ts +42 -0
  32. package/ts/requests/corestore.ts +100 -0
  33. package/ts/requests/runtimesession.ts +53 -0
  34. package/ts/runtime.serviceadmintoken.ts +395 -0
  35. package/ts/runtime.ts +1 -0
@@ -11,6 +11,11 @@ import type {
11
11
  import type {
12
12
  IDelegatedAdminTokenMetadata, IDelegatedAdminTokenMint, IDelegatedAdminTokenMintResult,
13
13
  } from '../data/delegatedadmintoken.js';
14
+ import type {
15
+ IServiceAdminAuthorityStatus,
16
+ IServiceAdminTokenMintRequest,
17
+ IServiceAdminTokenMintResult,
18
+ } from '../data/serviceadmintoken.js';
14
19
 
15
20
  export interface IReq_Admin_GetServiceMachineCredential extends plugins.typedrequestInterfaces.implementsTR<
16
21
  plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_GetServiceMachineCredential
@@ -249,3 +254,40 @@ export interface IReq_Admin_RevokeDelegatedAdminToken extends plugins.typedreque
249
254
  request: { identity: IIdentityCredential; tokenId: string };
250
255
  response: { metadata: IDelegatedAdminTokenMetadata };
251
256
  }
257
+
258
+ /**
259
+ * Value-free status of Cloudly's Ed25519 Service Admin Token Authority (active `kid`, `issuer`,
260
+ * and public JWKS). Admits administrators or delegated tokens with `serviceAdminTokens`.
261
+ */
262
+ export interface IReq_Admin_GetServiceAdminAuthorityStatus extends plugins.typedrequestInterfaces.implementsTR<
263
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_GetServiceAdminAuthorityStatus
264
+ > {
265
+ method: 'getServiceAdminAuthorityStatus';
266
+ request: { identity: IIdentityCredential };
267
+ response: { authority: IServiceAdminAuthorityStatus };
268
+ }
269
+
270
+ /**
271
+ * Rotates Cloudly's Ed25519 Service Admin Token Authority signing key while retaining the previous
272
+ * public key in JWKS during the token-lifetime overlap window. Requires a fresh human administrator.
273
+ */
274
+ export interface IReq_Admin_RotateServiceAdminAuthorityKey extends plugins.typedrequestInterfaces.implementsTR<
275
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_RotateServiceAdminAuthorityKey
276
+ > {
277
+ method: 'rotateServiceAdminAuthorityKey';
278
+ request: { identity: IIdentityCredential };
279
+ response: { authority: IServiceAdminAuthorityStatus };
280
+ }
281
+
282
+ /**
283
+ * Mints a short-lived, scope-limited, service-pinned Ed25519 Service Admin Token (`at+jwt`)
284
+ * accepted offline by hosted services that trust `SERVEZONE_SERVICE_ADMIN_JWKS`.
285
+ * Admits a fresh human administrator or a delegated temp token with the `serviceAdminTokens` scope.
286
+ */
287
+ export interface IReq_Admin_MintServiceAdminToken extends plugins.typedrequestInterfaces.implementsTR<
288
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Admin_MintServiceAdminToken
289
+ > {
290
+ method: 'mintServiceAdminToken';
291
+ request: { identity: IIdentityCredential } & IServiceAdminTokenMintRequest;
292
+ response: IServiceAdminTokenMintResult;
293
+ }
@@ -6,6 +6,12 @@ import type {
6
6
  ICorestoreLegacyResourceSelection,
7
7
  TClusterCorestoreLegacyResourceInventory,
8
8
  } from '../data/corestorelegacyadoption.js';
9
+ import type {
10
+ ICorestoreDatabaseInspectRequest,
11
+ ICorestoreObjectStorageInspectRequest,
12
+ ICorestoreObjectStorageInspectResult,
13
+ TCorestoreDatabaseInspectResult,
14
+ } from '../data/corestoredata.js';
9
15
  import type { IPlatformBinding } from '../platform/types.js';
10
16
  import { hasExactKeys } from '../private/dataproperties.js';
11
17
  import { isClusterNodeId } from '../private/nodeidentifier.js';
@@ -374,3 +380,97 @@ extends plugins.typedrequestInterfaces.implementsTR<
374
380
  plan: ICorestoreLegacyResourceAdoptionPlanEntry[];
375
381
  };
376
382
  }
383
+
384
+ /**
385
+ * Cloudly asks a cluster relay to perform a bounded read-only database inspection
386
+ * against one node's Corestore without exposing database credentials.
387
+ */
388
+ export interface IReq_Cloudly_Relay_InspectClusterCorestoreDatabase
389
+ extends plugins.typedrequestInterfaces.implementsTR<
390
+ plugins.typedrequestInterfaces.ITypedRequest,
391
+ IReq_Cloudly_Relay_InspectClusterCorestoreDatabase
392
+ > {
393
+ method: 'inspectClusterCorestoreDatabase';
394
+ request: {
395
+ nodeId: string;
396
+ inspection: ICorestoreDatabaseInspectRequest;
397
+ };
398
+ response: {
399
+ nodeId: string;
400
+ result: TCorestoreDatabaseInspectResult;
401
+ };
402
+ }
403
+
404
+ /**
405
+ * Cloudly asks a cluster relay to perform a bounded read-only object storage
406
+ * listing against one node's Corestore without exposing bucket credentials.
407
+ */
408
+ export interface IReq_Cloudly_Relay_InspectClusterCorestoreObjectStorage
409
+ extends plugins.typedrequestInterfaces.implementsTR<
410
+ plugins.typedrequestInterfaces.ITypedRequest,
411
+ IReq_Cloudly_Relay_InspectClusterCorestoreObjectStorage
412
+ > {
413
+ method: 'inspectClusterCorestoreObjectStorage';
414
+ request: {
415
+ nodeId: string;
416
+ inspection: ICorestoreObjectStorageInspectRequest;
417
+ };
418
+ response: {
419
+ nodeId: string;
420
+ result: ICorestoreObjectStorageInspectResult;
421
+ };
422
+ }
423
+
424
+ /**
425
+ * Operator or `databaseRead` delegated-token read-only inspection of a service's
426
+ * Corestore-managed database (list collections, bounded find, or count).
427
+ */
428
+ export interface IReq_Any_Cloudly_InspectServiceDatabase
429
+ extends plugins.typedrequestInterfaces.implementsTR<
430
+ plugins.typedrequestInterfaces.ITypedRequest,
431
+ IReq_Any_Cloudly_InspectServiceDatabase
432
+ > {
433
+ method: 'inspectServiceDatabase';
434
+ request: {
435
+ identity: IIdentity;
436
+ serviceId: string;
437
+ nodeId?: string;
438
+ operation: ICorestoreDatabaseInspectRequest['operation'];
439
+ collection?: string;
440
+ filter?: Record<string, unknown>;
441
+ projection?: Record<string, 0 | 1>;
442
+ sort?: Record<string, 1 | -1>;
443
+ limit?: number;
444
+ skip?: number;
445
+ };
446
+ response: {
447
+ nodeId: string;
448
+ clusterId: string;
449
+ result: TCorestoreDatabaseInspectResult;
450
+ };
451
+ }
452
+
453
+ /**
454
+ * Operator or `databaseRead` delegated-token read-only listing of objects in a
455
+ * service's Corestore-managed object storage bucket.
456
+ */
457
+ export interface IReq_Any_Cloudly_InspectServiceObjectStorage
458
+ extends plugins.typedrequestInterfaces.implementsTR<
459
+ plugins.typedrequestInterfaces.ITypedRequest,
460
+ IReq_Any_Cloudly_InspectServiceObjectStorage
461
+ > {
462
+ method: 'inspectServiceObjectStorage';
463
+ request: {
464
+ identity: IIdentity;
465
+ serviceId: string;
466
+ nodeId?: string;
467
+ prefix?: string;
468
+ startAfter?: string;
469
+ limit?: number;
470
+ };
471
+ response: {
472
+ nodeId: string;
473
+ clusterId: string;
474
+ result: ICorestoreObjectStorageInspectResult;
475
+ };
476
+ }
@@ -13,6 +13,7 @@ import type * as localStorage from '../data/runtimelocalstorageclaim.js';
13
13
  import type * as logs from '../data/runtimeassignmentlogs.js';
14
14
  import type * as stats from '../data/runtimeassignmentstats.js';
15
15
  import type * as exec from '../data/runtimeassignmentexec.js';
16
+ import type * as palletWorkspace from '../data/palletworkspace.js';
16
17
  import type * as volumeArchive from '../data/runtimelocalvolumearchive.js';
17
18
 
18
19
  /** Current-peer, exact-projection authorization; response contains secret keys. */
@@ -297,6 +298,58 @@ export interface IReq_Onebox_Pallet_CloseRuntimeAssignmentExec extends plugins.t
297
298
  response: exec.ICloseRuntimeAssignmentExecResponse;
298
299
  }
299
300
 
301
+ /**
302
+ * A controller runs one bounded non-interactive command inside a running Pallet
303
+ * assignment container via containerd CRI `ExecSync`.
304
+ */
305
+ export interface IReq_Controller_Pallet_RunRuntimeAssignmentExec extends plugins.typedrequestInterfaces.implementsTR<
306
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Controller_Pallet_RunRuntimeAssignmentExec
307
+ > {
308
+ method: 'runRuntimeAssignmentExec';
309
+ request: palletWorkspace.IRunRuntimeAssignmentExecRequest;
310
+ response: palletWorkspace.IRunRuntimeAssignmentExecResponse;
311
+ }
312
+
313
+ /**
314
+ * A controller starts an interactive shell session inside a running Pallet
315
+ * assignment container. Output chunks travel back to the controller via
316
+ * `pushRuntimeAssignmentShellOutput`.
317
+ */
318
+ export interface IReq_Controller_Pallet_StartRuntimeAssignmentShell extends plugins.typedrequestInterfaces.implementsTR<
319
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Controller_Pallet_StartRuntimeAssignmentShell
320
+ > {
321
+ method: 'startRuntimeAssignmentShell';
322
+ request: palletWorkspace.IStartRuntimeAssignmentShellRequest;
323
+ response: palletWorkspace.IStartRuntimeAssignmentShellResponse;
324
+ }
325
+
326
+ /** A controller sends stdin bytes to an open Pallet interactive shell session. */
327
+ export interface IReq_Controller_Pallet_WriteRuntimeAssignmentShell extends plugins.typedrequestInterfaces.implementsTR<
328
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Controller_Pallet_WriteRuntimeAssignmentShell
329
+ > {
330
+ method: 'writeRuntimeAssignmentShell';
331
+ request: palletWorkspace.IWriteRuntimeAssignmentShellRequest;
332
+ response: Record<string, never>;
333
+ }
334
+
335
+ /** A controller terminates an open Pallet interactive shell session. */
336
+ export interface IReq_Controller_Pallet_KillRuntimeAssignmentShell extends plugins.typedrequestInterfaces.implementsTR<
337
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Controller_Pallet_KillRuntimeAssignmentShell
338
+ > {
339
+ method: 'killRuntimeAssignmentShell';
340
+ request: palletWorkspace.IKillRuntimeAssignmentShellRequest;
341
+ response: Record<string, never>;
342
+ }
343
+
344
+ /** Pallet pushes stdout/stderr/exit notifications for an active interactive shell back to Cloudly. */
345
+ export interface IReq_Pallet_Controller_PushRuntimeAssignmentShellOutput extends plugins.typedrequestInterfaces.implementsTR<
346
+ plugins.typedrequestInterfaces.ITypedRequest, IReq_Pallet_Controller_PushRuntimeAssignmentShellOutput
347
+ > {
348
+ method: 'pushRuntimeAssignmentShellOutput';
349
+ request: palletWorkspace.IPushRuntimeAssignmentShellOutputRequest;
350
+ response: Record<string, never>;
351
+ }
352
+
300
353
  /**
301
354
  * A local controller reads one node-local volume as a pax archive
302
355
  * (`runtimeLocalVolumeArchiveContract`). The archive arrives on `archive`, which outlives this
@@ -0,0 +1,395 @@
1
+ import * as plugins from './plugins.runtime.js';
2
+ import {
3
+ buildServiceAdminAudience,
4
+ isServiceAdminAuthorityKeyId,
5
+ isServiceAdminTokenJti,
6
+ isServiceAdminTokenLifetime,
7
+ isServiceAdminTokenScope,
8
+ isServiceAdminTokenServiceId,
9
+ serviceAdminTokenContract,
10
+ serviceAdminTokenEnvironmentNames,
11
+ serviceAdminTokenScopesSatisfy,
12
+ snapshotServiceAdminAuthorityJwks,
13
+ type IServiceAdminAuthorityJwk,
14
+ type IServiceAdminAuthorityJwks,
15
+ type IServiceAdminTokenClaims,
16
+ } from './data/serviceadmintoken.js';
17
+
18
+ export interface IGeneratedServiceAdminAuthorityKeyPair {
19
+ privateKeyPemBytes: Uint8Array;
20
+ jwk: IServiceAdminAuthorityJwk;
21
+ kid: string;
22
+ }
23
+
24
+ export type TServiceAdminTokenVerificationCode =
25
+ | 'malformed'
26
+ | 'unsupported_header'
27
+ | 'unknown_key'
28
+ | 'invalid_signature'
29
+ | 'invalid_claims'
30
+ | 'expired'
31
+ | 'not_yet_valid'
32
+ | 'audience_mismatch'
33
+ | 'issuer_mismatch'
34
+ | 'insufficient_scope'
35
+ | 'authority_unconfigured';
36
+
37
+ export type TServiceAdminTokenVerificationResult =
38
+ | { valid: true; claims: IServiceAdminTokenClaims; keyId: string }
39
+ | { valid: false; code: TServiceAdminTokenVerificationCode; message: string };
40
+
41
+ const toBase64Url = (dataArg: Uint8Array | string): string => (
42
+ Buffer.from(dataArg).toString('base64url')
43
+ );
44
+
45
+ const fromBase64Url = (valueArg: string): Buffer | null => {
46
+ if (!/^[A-Za-z0-9_-]+$/.test(valueArg)) return null;
47
+ const decoded = Buffer.from(valueArg, 'base64url');
48
+ if (decoded.toString('base64url') !== valueArg) return null;
49
+ return decoded;
50
+ };
51
+
52
+ const deriveKidAndJwk = (publicKeyArg: plugins.crypto.KeyObject): {
53
+ jwk: IServiceAdminAuthorityJwk;
54
+ kid: string;
55
+ } => {
56
+ const spki = publicKeyArg.export({ type: 'spki', format: 'der' });
57
+ const spkiBuf = Buffer.isBuffer(spki) ? spki : Buffer.from(spki);
58
+ const kid = `${serviceAdminTokenContract.kidPrefix}${plugins.crypto.createHash('sha256').update(spkiBuf).digest('hex').slice(0, 16)}`;
59
+ const rawJwk = publicKeyArg.export({ format: 'jwk' }) as { kty?: string; crv?: string; x?: string };
60
+ if (rawJwk.kty !== 'OKP' || rawJwk.crv !== 'Ed25519' || typeof rawJwk.x !== 'string') {
61
+ throw new Error('Service admin authority key is not an Ed25519 key.');
62
+ }
63
+ return {
64
+ kid,
65
+ jwk: {
66
+ kty: 'OKP',
67
+ crv: 'Ed25519',
68
+ alg: 'EdDSA',
69
+ use: 'sig',
70
+ kid,
71
+ x: rawJwk.x,
72
+ },
73
+ };
74
+ };
75
+
76
+ /** Generates a fresh Ed25519 signing key pair for Cloudly's Service Admin Token Authority. */
77
+ export const generateServiceAdminAuthorityKeyPair = (): IGeneratedServiceAdminAuthorityKeyPair => {
78
+ const { publicKey, privateKey } = plugins.crypto.generateKeyPairSync('ed25519');
79
+ const { jwk, kid } = deriveKidAndJwk(publicKey);
80
+ const pem = privateKey.export({ type: 'pkcs8', format: 'pem' });
81
+ const privateKeyPemBytes = new Uint8Array(Buffer.from(String(pem), 'utf8'));
82
+ return { privateKeyPemBytes, jwk, kid };
83
+ };
84
+
85
+ /** Derives canonical JWK + kid from a stored PKCS#8 Ed25519 private key PEM. */
86
+ export const deriveServiceAdminAuthorityJwkFromPrivatePem = (
87
+ privateKeyPemBytesArg: Uint8Array,
88
+ ): { jwk: IServiceAdminAuthorityJwk; kid: string } => {
89
+ const privateKey = plugins.crypto.createPrivateKey({
90
+ key: Buffer.from(privateKeyPemBytesArg),
91
+ format: 'pem',
92
+ });
93
+ if (privateKey.asymmetricKeyType !== 'ed25519') {
94
+ throw new Error('Stored service admin authority private key is not Ed25519.');
95
+ }
96
+ return deriveKidAndJwk(plugins.crypto.createPublicKey(privateKey));
97
+ };
98
+
99
+ /** Signs a short-lived Ed25519 Service Admin Token compact JWS (`at+jwt`). */
100
+ export const signServiceAdminToken = (argsArg: {
101
+ privateKeyPemBytes: Uint8Array;
102
+ kid?: string;
103
+ issuer: string;
104
+ serviceId: string;
105
+ subject: string;
106
+ scopes: readonly string[];
107
+ lifetimeMs?: number;
108
+ reason?: string;
109
+ jti?: string;
110
+ nowMs?: number;
111
+ }): { token: string; claims: IServiceAdminTokenClaims; keyId: string; issuedAt: number; expiresAt: number } => {
112
+ const issuer = argsArg.issuer.trim();
113
+ if (!issuer || /\s/.test(issuer)) {
114
+ throw new Error('Service admin token issuer must be a non-empty whitespace-free string.');
115
+ }
116
+ if (!isServiceAdminTokenServiceId(argsArg.serviceId)) {
117
+ throw new Error('Service admin token serviceId is invalid.');
118
+ }
119
+ const subject = argsArg.subject.trim();
120
+ if (!subject || subject.length > 256 || /[\u0000-\u001f\u007f]/.test(subject)) {
121
+ throw new Error('Service admin token subject is invalid.');
122
+ }
123
+ const uniqueScopes = [...new Set(argsArg.scopes)].sort();
124
+ if (
125
+ uniqueScopes.length === 0
126
+ || uniqueScopes.length > serviceAdminTokenContract.maximumScopes
127
+ || uniqueScopes.some((scopeArg) => !isServiceAdminTokenScope(scopeArg))
128
+ ) {
129
+ throw new Error('Service admin token scopes must be 1 to 32 valid scopes.');
130
+ }
131
+ const lifetimeMs = argsArg.lifetimeMs ?? serviceAdminTokenContract.defaultLifetimeMs;
132
+ if (!isServiceAdminTokenLifetime(lifetimeMs)) {
133
+ throw new Error('Service admin token lifetimeMs is out of bounds.');
134
+ }
135
+ if (argsArg.reason !== undefined) {
136
+ if (
137
+ typeof argsArg.reason !== 'string'
138
+ || argsArg.reason.length === 0
139
+ || argsArg.reason.length > serviceAdminTokenContract.maximumReasonLength
140
+ || argsArg.reason !== argsArg.reason.trim()
141
+ || /[\u0000-\u001f\u007f]/.test(argsArg.reason)
142
+ ) {
143
+ throw new Error('Service admin token reason is invalid.');
144
+ }
145
+ }
146
+
147
+ const privateKey = plugins.crypto.createPrivateKey({
148
+ key: Buffer.from(argsArg.privateKeyPemBytes),
149
+ format: 'pem',
150
+ });
151
+ if (privateKey.asymmetricKeyType !== 'ed25519') {
152
+ throw new Error('Service admin token signing key must be Ed25519.');
153
+ }
154
+ const derived = deriveKidAndJwk(plugins.crypto.createPublicKey(privateKey));
155
+ const keyId = argsArg.kid ?? derived.kid;
156
+ if (keyId !== derived.kid || !isServiceAdminAuthorityKeyId(keyId)) {
157
+ throw new Error('Service admin token kid does not match signing key.');
158
+ }
159
+
160
+ const nowMs = argsArg.nowMs ?? Date.now();
161
+ const iat = Math.floor(nowMs / 1000);
162
+ const exp = iat + Math.floor(lifetimeMs / 1000);
163
+ const jti = argsArg.jti ?? `${serviceAdminTokenContract.jtiPrefix}${plugins.crypto.randomBytes(24).toString('hex')}`;
164
+ if (!isServiceAdminTokenJti(jti)) {
165
+ throw new Error('Service admin token jti is invalid.');
166
+ }
167
+
168
+ const claims: IServiceAdminTokenClaims = {
169
+ iss: issuer,
170
+ aud: buildServiceAdminAudience(argsArg.serviceId),
171
+ sub: subject,
172
+ serviceId: argsArg.serviceId,
173
+ scopes: uniqueScopes,
174
+ jti,
175
+ iat,
176
+ exp,
177
+ ...(argsArg.reason !== undefined ? { reason: argsArg.reason } : {}),
178
+ };
179
+
180
+ const headerSegment = toBase64Url(JSON.stringify({
181
+ alg: serviceAdminTokenContract.algorithm,
182
+ typ: serviceAdminTokenContract.jwtType,
183
+ kid: keyId,
184
+ }));
185
+ const payloadSegment = toBase64Url(JSON.stringify(claims));
186
+ const signingInput = `${headerSegment}.${payloadSegment}`;
187
+ const signature = plugins.crypto.sign(null, Buffer.from(signingInput, 'ascii'), privateKey);
188
+ const token = `${signingInput}.${signature.toString('base64url')}`;
189
+
190
+ return {
191
+ token,
192
+ claims,
193
+ keyId,
194
+ issuedAt: iat * 1000,
195
+ expiresAt: exp * 1000,
196
+ };
197
+ };
198
+
199
+ /**
200
+ * Verifies a Cloudly-brokered Service Admin Token completely offline against Cloudly's
201
+ * injected public Ed25519 JWKS (`SERVEZONE_SERVICE_ADMIN_JWKS`), pinned to `expectedServiceId`.
202
+ */
203
+ export const verifyServiceAdminToken = (argsArg: {
204
+ token: string;
205
+ jwks: IServiceAdminAuthorityJwks | string;
206
+ expectedServiceId: string;
207
+ expectedIssuer?: string;
208
+ requiredScopes?: readonly string[];
209
+ nowMs?: number;
210
+ }): TServiceAdminTokenVerificationResult => {
211
+ if (typeof argsArg.token !== 'string' || argsArg.token.length === 0 || argsArg.token.length > 8_192) {
212
+ return { valid: false, code: 'malformed', message: 'Service admin token is empty or oversized.' };
213
+ }
214
+ if (!isServiceAdminTokenServiceId(argsArg.expectedServiceId)) {
215
+ return { valid: false, code: 'authority_unconfigured', message: 'Expected serviceId is not configured.' };
216
+ }
217
+
218
+ let jwks: IServiceAdminAuthorityJwks;
219
+ try {
220
+ const raw = typeof argsArg.jwks === 'string' ? JSON.parse(argsArg.jwks) : argsArg.jwks;
221
+ jwks = snapshotServiceAdminAuthorityJwks(raw);
222
+ } catch {
223
+ return { valid: false, code: 'authority_unconfigured', message: 'Service admin authority JWKS is invalid.' };
224
+ }
225
+
226
+ const parts = argsArg.token.split('.');
227
+ if (parts.length !== 3) {
228
+ return { valid: false, code: 'malformed', message: 'Service admin token must have three JWS segments.' };
229
+ }
230
+ const [headerSeg, payloadSeg, signatureSeg] = parts;
231
+ const headerBytes = fromBase64Url(headerSeg);
232
+ const payloadBytes = fromBase64Url(payloadSeg);
233
+ const signatureBytes = fromBase64Url(signatureSeg);
234
+ if (!headerBytes || !payloadBytes || !signatureBytes || signatureBytes.length !== 64) {
235
+ return { valid: false, code: 'malformed', message: 'Service admin token segments are not canonical base64url.' };
236
+ }
237
+
238
+ let header: Record<string, unknown>;
239
+ try {
240
+ const parsed = JSON.parse(headerBytes.toString('utf8'));
241
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
242
+ return { valid: false, code: 'malformed', message: 'Service admin token header must be a JSON object.' };
243
+ }
244
+ header = parsed as Record<string, unknown>;
245
+ } catch {
246
+ return { valid: false, code: 'malformed', message: 'Service admin token header is not valid JSON.' };
247
+ }
248
+
249
+ if (
250
+ header.alg !== serviceAdminTokenContract.algorithm
251
+ || header.typ !== serviceAdminTokenContract.jwtType
252
+ || !isServiceAdminAuthorityKeyId(header.kid)
253
+ ) {
254
+ return { valid: false, code: 'unsupported_header', message: 'Service admin token header alg, typ, or kid is unsupported.' };
255
+ }
256
+
257
+ const keyId = header.kid;
258
+ const matchingJwk = jwks.keys.find((candidateArg) => candidateArg.kid === keyId);
259
+ if (!matchingJwk) {
260
+ return { valid: false, code: 'unknown_key', message: `Service admin authority key ${keyId} is not trusted.` };
261
+ }
262
+
263
+ let verified = false;
264
+ try {
265
+ const publicKey = plugins.crypto.createPublicKey({
266
+ key: { kty: 'OKP', crv: 'Ed25519', x: matchingJwk.x },
267
+ format: 'jwk',
268
+ });
269
+ verified = plugins.crypto.verify(
270
+ null,
271
+ Buffer.from(`${headerSeg}.${payloadSeg}`, 'ascii'),
272
+ publicKey,
273
+ signatureBytes,
274
+ );
275
+ } catch {
276
+ verified = false;
277
+ }
278
+ if (!verified) {
279
+ return { valid: false, code: 'invalid_signature', message: 'Service admin token signature verification failed.' };
280
+ }
281
+
282
+ let payload: Record<string, unknown>;
283
+ try {
284
+ const parsed = JSON.parse(payloadBytes.toString('utf8'));
285
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
286
+ return { valid: false, code: 'invalid_claims', message: 'Service admin token payload must be a JSON object.' };
287
+ }
288
+ payload = parsed as Record<string, unknown>;
289
+ } catch {
290
+ return { valid: false, code: 'invalid_claims', message: 'Service admin token payload is not valid JSON.' };
291
+ }
292
+
293
+ if (
294
+ typeof payload.iss !== 'string' || !payload.iss.trim()
295
+ || typeof payload.aud !== 'string'
296
+ || typeof payload.sub !== 'string' || !payload.sub.trim()
297
+ || !isServiceAdminTokenServiceId(payload.serviceId)
298
+ || !isServiceAdminTokenJti(payload.jti)
299
+ || typeof payload.iat !== 'number' || !Number.isSafeInteger(payload.iat)
300
+ || typeof payload.exp !== 'number' || !Number.isSafeInteger(payload.exp)
301
+ || !Array.isArray(payload.scopes)
302
+ || payload.scopes.length === 0
303
+ || payload.scopes.length > serviceAdminTokenContract.maximumScopes
304
+ || payload.scopes.some((scopeArg) => !isServiceAdminTokenScope(scopeArg))
305
+ ) {
306
+ return { valid: false, code: 'invalid_claims', message: 'Service admin token claims are malformed.' };
307
+ }
308
+
309
+ const maxLifetimeSeconds = Math.floor(serviceAdminTokenContract.maximumLifetimeMs / 1000);
310
+ if (payload.exp <= payload.iat || payload.exp - payload.iat > maxLifetimeSeconds) {
311
+ return { valid: false, code: 'invalid_claims', message: 'Service admin token lifetime exceeds contract maximum.' };
312
+ }
313
+
314
+ const nowSeconds = Math.floor((argsArg.nowMs ?? Date.now()) / 1000);
315
+ const skew = serviceAdminTokenContract.clockSkewToleranceSeconds;
316
+ if (payload.exp + skew <= nowSeconds) {
317
+ return { valid: false, code: 'expired', message: 'Service admin token has expired.' };
318
+ }
319
+ if (payload.iat - skew > nowSeconds) {
320
+ return { valid: false, code: 'not_yet_valid', message: 'Service admin token iat is in the future.' };
321
+ }
322
+
323
+ const expectedAud = buildServiceAdminAudience(argsArg.expectedServiceId);
324
+ if (payload.aud !== expectedAud || payload.serviceId !== argsArg.expectedServiceId) {
325
+ return { valid: false, code: 'audience_mismatch', message: 'Service admin token is not scoped to this service.' };
326
+ }
327
+
328
+ if (argsArg.expectedIssuer !== undefined && payload.iss !== argsArg.expectedIssuer) {
329
+ return { valid: false, code: 'issuer_mismatch', message: 'Service admin token issuer does not match.' };
330
+ }
331
+
332
+ const scopes = payload.scopes as string[];
333
+ if (argsArg.requiredScopes && argsArg.requiredScopes.length > 0) {
334
+ if (!serviceAdminTokenScopesSatisfy(scopes, argsArg.requiredScopes)) {
335
+ return { valid: false, code: 'insufficient_scope', message: 'Service admin token lacks required scope.' };
336
+ }
337
+ }
338
+
339
+ const claims: IServiceAdminTokenClaims = {
340
+ iss: payload.iss,
341
+ aud: payload.aud,
342
+ sub: payload.sub,
343
+ serviceId: payload.serviceId,
344
+ scopes,
345
+ jti: payload.jti,
346
+ iat: payload.iat,
347
+ exp: payload.exp,
348
+ ...(typeof payload.reason === 'string' ? { reason: payload.reason } : {}),
349
+ };
350
+
351
+ return { valid: true, claims, keyId };
352
+ };
353
+
354
+ /**
355
+ * Convenience verifier for workloads running under Cloudly: reads
356
+ * `SERVEZONE_SERVICE_ADMIN_JWKS`, `SERVEZONE_SERVICE_ADMIN_ISSUER`, and
357
+ * `SERVEZONE_WORKLOAD_SERVICE_ID` from `envArg` (default `process.env`).
358
+ */
359
+ export const verifyServiceAdminBearerFromEnvironment = (argsArg: {
360
+ authorizationHeader?: string | null;
361
+ token?: string | null;
362
+ requiredScopes?: readonly string[];
363
+ env?: Readonly<Record<string, string | undefined>>;
364
+ nowMs?: number;
365
+ }): TServiceAdminTokenVerificationResult => {
366
+ const env = argsArg.env ?? process.env;
367
+ const jwks = env[serviceAdminTokenEnvironmentNames.jwks]?.trim();
368
+ const expectedServiceId = env[serviceAdminTokenEnvironmentNames.serviceId]?.trim();
369
+ const expectedIssuer = env[serviceAdminTokenEnvironmentNames.issuer]?.trim();
370
+ if (!jwks || !expectedServiceId) {
371
+ return {
372
+ valid: false,
373
+ code: 'authority_unconfigured',
374
+ message: 'Cloudly service admin token authority is not injected into this workload.',
375
+ };
376
+ }
377
+ let token = argsArg.token?.trim() || '';
378
+ if (!token && argsArg.authorizationHeader) {
379
+ const header = argsArg.authorizationHeader.trim();
380
+ if (/^Bearer\s+/i.test(header)) {
381
+ token = header.replace(/^Bearer\s+/i, '').trim();
382
+ }
383
+ }
384
+ if (!token) {
385
+ return { valid: false, code: 'malformed', message: 'Missing Bearer service admin token.' };
386
+ }
387
+ return verifyServiceAdminToken({
388
+ token,
389
+ jwks,
390
+ expectedServiceId,
391
+ ...(expectedIssuer ? { expectedIssuer } : {}),
392
+ requiredScopes: argsArg.requiredScopes,
393
+ nowMs: argsArg.nowMs,
394
+ });
395
+ };
package/ts/runtime.ts CHANGED
@@ -49,6 +49,7 @@ export * from './runtime.corestore.relay.js';
49
49
  export * from './runtime.corestore.objectstoragebackup.js';
50
50
  export * from './runtime.assignmentsecret.js';
51
51
  export * from './runtime.appstorecatalog.js';
52
+ export * from './runtime.serviceadmintoken.js';
52
53
 
53
54
  export interface ISealedResolvedSecretMaterialEntry {
54
55
  secretVersionId: string;