@serve.zone/interfaces 32.121.0 → 32.122.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,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;