@di-framework/cli-plugin-platform 6.1.2 → 6.3.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 (60) hide show
  1. package/README.md +154 -12
  2. package/dist/args.d.ts +8 -0
  3. package/dist/args.js +73 -28
  4. package/dist/assets/http-adapter.js +4 -1
  5. package/dist/assets/platform/README.md +68 -19
  6. package/dist/assets/platform/index.ts.tmpl +1 -1
  7. package/dist/assets/platform/tsconfig.json +2 -2
  8. package/dist/assets/sqlite/BUILD-INFO.txt +1 -1
  9. package/dist/build.d.ts +27 -4
  10. package/dist/build.js +159 -18
  11. package/dist/bundle.d.ts +85 -0
  12. package/dist/bundle.js +608 -0
  13. package/dist/command.js +85 -3
  14. package/dist/console/catalog.js +2 -1
  15. package/dist/console/cluster.d.ts +4 -2
  16. package/dist/console/cluster.js +38 -40
  17. package/dist/control/auth.js +14 -2
  18. package/dist/controller/client.d.ts +47 -0
  19. package/dist/controller/client.js +157 -0
  20. package/dist/controller/commands.d.ts +48 -0
  21. package/dist/controller/commands.js +584 -0
  22. package/dist/controller/credentials.d.ts +63 -0
  23. package/dist/controller/credentials.js +156 -0
  24. package/dist/controller/index.d.ts +6 -0
  25. package/dist/controller/index.js +6 -0
  26. package/dist/controller/oidc.d.ts +54 -0
  27. package/dist/controller/oidc.js +121 -0
  28. package/dist/controller/registry.d.ts +15 -0
  29. package/dist/controller/registry.js +47 -0
  30. package/dist/controller/schema.d.ts +157 -0
  31. package/dist/controller/schema.js +1 -0
  32. package/dist/controller/sse.d.ts +12 -0
  33. package/dist/controller/sse.js +61 -0
  34. package/dist/controller/trust.d.ts +14 -0
  35. package/dist/controller/trust.js +39 -0
  36. package/dist/deploy.d.ts +14 -7
  37. package/dist/deploy.js +96 -5
  38. package/dist/deps.d.ts +4 -0
  39. package/dist/destroy.js +26 -2
  40. package/dist/environment-names.d.ts +6 -0
  41. package/dist/environment-names.js +10 -0
  42. package/dist/index.d.ts +5 -3
  43. package/dist/index.js +5 -3
  44. package/dist/manifest.d.ts +45 -1
  45. package/dist/manifest.js +197 -4
  46. package/dist/pglite-encryption.d.ts +79 -0
  47. package/dist/pglite-encryption.js +196 -0
  48. package/dist/pglite.d.ts +61 -4
  49. package/dist/pglite.js +124 -40
  50. package/dist/project.d.ts +7 -0
  51. package/dist/project.js +35 -0
  52. package/dist/publish.d.ts +7 -1
  53. package/dist/publish.js +33 -1
  54. package/dist/service.d.ts +34 -0
  55. package/dist/service.js +156 -145
  56. package/dist/target.d.ts +7 -1
  57. package/dist/target.js +19 -0
  58. package/dist/workload.d.ts +50 -12
  59. package/dist/workload.js +239 -44
  60. package/package.json +1 -1
@@ -0,0 +1,156 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { discoverAccountControllerUrl } from '../target.js';
5
+ import { createClient } from './client.js';
6
+ import { discover, OidcError, refreshTokens } from './oidc.js';
7
+ import { caPem, trusting } from './trust.js';
8
+ /** True when an identity token is gone or within a minute of expiring, so it must be refreshed. */
9
+ export function needsRefresh(credential, now = Date.now()) {
10
+ if (credential.via !== 'identity' || !credential.refreshToken)
11
+ return false;
12
+ if (!credential.accessToken)
13
+ return true;
14
+ return credential.expiresAt !== undefined && Date.parse(credential.expiresAt) - now <= 60_000;
15
+ }
16
+ export class CliError extends Error {
17
+ exitCode;
18
+ constructor(message, exitCode = 1) {
19
+ super(message);
20
+ this.exitCode = exitCode;
21
+ this.name = 'CliError';
22
+ }
23
+ }
24
+ export const home = (env = process.env) => env.DI_FRAMEWORK_HOME ?? join(homedir(), '.di-framework');
25
+ const credentialsPath = (env) => join(home(env), 'credentials.json');
26
+ export function readStore(env) {
27
+ const path = credentialsPath(env);
28
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
29
+ }
30
+ export function writeStore(store, env) {
31
+ const directory = home(env);
32
+ if (!existsSync(directory))
33
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
34
+ const path = credentialsPath(env);
35
+ writeFileSync(path, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
36
+ chmodSync(path, 0o600);
37
+ }
38
+ /** The bearer a credential presents: the API key, or the identity access token while it lasts. */
39
+ export function bearer(credential) {
40
+ if (credential.apiKey)
41
+ return credential.apiKey;
42
+ if (!credential.accessToken)
43
+ throw new CliError('the credential holds no token; log in again');
44
+ if (credential.expiresAt && Date.parse(credential.expiresAt) <= Date.now()) {
45
+ throw new CliError('the login has expired; run login again');
46
+ }
47
+ return credential.accessToken;
48
+ }
49
+ /**
50
+ * The account a command runs against: `--account`, then `DI_TENANT_ACCOUNT`, then the only
51
+ * credential on disk.
52
+ */
53
+ export function resolveAccount(flag, env, store) {
54
+ const named = flag ?? env.DI_TENANT_ACCOUNT;
55
+ if (named)
56
+ return named;
57
+ const accounts = Object.keys(store);
58
+ if (accounts.length === 1)
59
+ return accounts[0];
60
+ throw new CliError(accounts.length === 0
61
+ ? 'not logged in; run: di-framework platform login --controller <url> --account <tenant>'
62
+ : `--account <tenant> is required; logged in to ${accounts.join(', ')}`);
63
+ }
64
+ export function load(account, env) {
65
+ const credential = readStore(env)[account];
66
+ if (!credential) {
67
+ throw new CliError(`not logged in to ${account}; run: di-framework platform login --account ${account}`);
68
+ }
69
+ return credential;
70
+ }
71
+ export function issuedTokens(tokens, previousRefresh) {
72
+ return {
73
+ accessToken: tokens.access_token,
74
+ refreshToken: tokens.refresh_token ?? previousRefresh,
75
+ expiresAt: new Date(Date.now() + tokens.expires_in * 1000).toISOString(),
76
+ };
77
+ }
78
+ export async function refreshCredential(credential, doFetch) {
79
+ if (!credential.issuer || !credential.clientId || !credential.refreshToken) {
80
+ throw new CliError('the login cannot be refreshed; run login again');
81
+ }
82
+ const metadata = await discover(credential.issuer, doFetch);
83
+ let tokens;
84
+ try {
85
+ tokens = await refreshTokens(metadata, { clientId: credential.clientId, refreshToken: credential.refreshToken }, doFetch);
86
+ }
87
+ catch (error) {
88
+ if (error instanceof OidcError) {
89
+ throw new CliError(`the login has expired (${error.message}); run login again`);
90
+ }
91
+ throw error;
92
+ }
93
+ return { ...credential, ...issuedTokens(tokens, credential.refreshToken) };
94
+ }
95
+ function resolveAccountTargetCredential(target, account, store, env) {
96
+ const resolvedAccount = account ?? target.account;
97
+ const entry = store[resolvedAccount];
98
+ if (!entry) {
99
+ throw new CliError(`not logged in to ${resolvedAccount}; run: di-framework platform login --target ${target.name}`);
100
+ }
101
+ const controllerUrlOverride = target.domain
102
+ ? discoverAccountControllerUrl(resolvedAccount, target.domain, env)
103
+ : entry.controller.url || discoverAccountControllerUrl(resolvedAccount, undefined, env);
104
+ return { stored: entry, controllerUrlOverride };
105
+ }
106
+ export function resolveControllerTargetCredential(target, account, store) {
107
+ const controllerUrl = target.controller.replace(/\/$/, '');
108
+ const accountHint = account ?? target.account;
109
+ if (accountHint !== undefined) {
110
+ const stored = store[accountHint];
111
+ if (!stored) {
112
+ throw new CliError(`not logged in to ${accountHint}; run: di-framework platform login --target ${target.name}`);
113
+ }
114
+ if (stored.controller.url.replace(/\/$/, '') !== controllerUrl) {
115
+ throw new CliError(`credential for ${accountHint} is for ${stored.controller.url}, not ${controllerUrl}; run: di-framework platform login --target ${target.name}`);
116
+ }
117
+ return stored;
118
+ }
119
+ const matched = Object.values(store).find((entry) => entry.controller.url.replace(/\/$/, '') === controllerUrl);
120
+ if (!matched) {
121
+ throw new CliError(`not logged in to ${controllerUrl}; run: di-framework platform login --target ${target.name}`);
122
+ }
123
+ return matched;
124
+ }
125
+ export async function resolveControllerSession(options, deps) {
126
+ const store = readStore(deps.env);
127
+ let stored;
128
+ let controllerUrlOverride;
129
+ if (options.target?.kind === 'account') {
130
+ const resolved = resolveAccountTargetCredential(options.target, options.account, store, deps.env);
131
+ stored = resolved.stored;
132
+ controllerUrlOverride = resolved.controllerUrlOverride;
133
+ }
134
+ else if (options.target?.kind === 'controller') {
135
+ stored = resolveControllerTargetCredential(options.target, options.account, store);
136
+ }
137
+ else {
138
+ const account = resolveAccount(options.account, deps.env, store);
139
+ stored = load(account, deps.env);
140
+ }
141
+ const refreshable = stored.via === 'identity' && stored.refreshToken !== undefined;
142
+ if (needsRefresh(stored) || (options.fresh && refreshable)) {
143
+ stored = await refreshCredential(stored, trusting(deps.fetch, caPem(stored.controller)));
144
+ store[stored.account] = stored;
145
+ writeStore(store, deps.env);
146
+ }
147
+ const credential = controllerUrlOverride === undefined
148
+ ? stored
149
+ : { ...stored, controller: { ...stored.controller, url: controllerUrlOverride } };
150
+ const client = createClient({
151
+ baseUrl: credential.controller.url,
152
+ token: bearer(credential),
153
+ fetch: trusting(deps.fetch, caPem(credential.controller)),
154
+ });
155
+ return { credential, client };
156
+ }
@@ -0,0 +1,6 @@
1
+ export { type AuthInfo, type ClientOptions, type ConfigList, ControllerError, type CreateServiceRequest, createClient, type DeployBundle as ControllerDeployBundle, type Deployment, type DeploymentList, type DeploymentStats, type DeployPlan, type Env, events, type LogEvent, type LogsQuery, type Principal, type Problem, type ProxyRequest, type ProxySession, type RegistryInfo, type RollbackRequest, type SecretList, type Service, type SseEvent, type TenantClient, type VarUnset, } from './client.js';
2
+ export { type AccountCommandOptions, type ConfigAction, type ConfigCommandOptions, type LoginOptions, type LogsCommandOptions, parseAccountCommandArgs, parseConfigArgs, parseLoginArgs, parseLogsArgs, runWasmcloudLogin, runWasmcloudLogout, runWasmcloudLogs, runWasmcloudSecrets, runWasmcloudVars, runWasmcloudWhoami, tlsTrustCode, wrapControllerError, } from './commands.js';
3
+ export { bearer, CliError, type Credential, type CredentialStore, home, issuedTokens, load, needsRefresh, type ResolveControllerSessionOptions, readStore, refreshCredential, resolveAccount, resolveControllerSession, resolveControllerTargetCredential, writeStore, } from './credentials.js';
4
+ export { type AuthorizationRequest, authorizationUrl, base64url, discover, exchangeCode, OidcError, type ProviderMetadata, pkce, randomToken, refreshTokens, revokeToken, type TokenResponse, } from './oidc.js';
5
+ export { type RegistryOrigin, registryOrigin, registryUsername } from './registry.js';
6
+ export { caPem, readCaFile, trusting } from './trust.js';
@@ -0,0 +1,6 @@
1
+ export { ControllerError, createClient, events, } from './client.js';
2
+ export { parseAccountCommandArgs, parseConfigArgs, parseLoginArgs, parseLogsArgs, runWasmcloudLogin, runWasmcloudLogout, runWasmcloudLogs, runWasmcloudSecrets, runWasmcloudVars, runWasmcloudWhoami, tlsTrustCode, wrapControllerError, } from './commands.js';
3
+ export { bearer, CliError, home, issuedTokens, load, needsRefresh, readStore, refreshCredential, resolveAccount, resolveControllerSession, resolveControllerTargetCredential, writeStore, } from './credentials.js';
4
+ export { authorizationUrl, base64url, discover, exchangeCode, OidcError, pkce, randomToken, refreshTokens, revokeToken, } from './oidc.js';
5
+ export { registryOrigin, registryUsername } from './registry.js';
6
+ export { caPem, readCaFile, trusting } from './trust.js';
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The identity-server side of a login, for a public native client (RFC 8252): OpenID discovery,
3
+ * PKCE, the authorization URL, and the code, refresh, and revocation calls, all without a
4
+ * client secret. `client_id` alone identifies the CLI; the code verifier is what protects it.
5
+ */
6
+ export interface ProviderMetadata {
7
+ issuer: string;
8
+ authorization_endpoint: string;
9
+ token_endpoint: string;
10
+ revocation_endpoint?: string;
11
+ }
12
+ export interface TokenResponse {
13
+ access_token: string;
14
+ token_type: string;
15
+ expires_in: number;
16
+ refresh_token?: string;
17
+ id_token?: string;
18
+ scope?: string;
19
+ }
20
+ export declare class OidcError extends Error {
21
+ readonly status?: number | undefined;
22
+ constructor(message: string, status?: number | undefined);
23
+ }
24
+ type Fetch = typeof fetch;
25
+ export declare function base64url(bytes: Uint8Array): string;
26
+ export declare function randomToken(bytes?: number): string;
27
+ export declare function pkce(verifier?: string): Promise<{
28
+ verifier: string;
29
+ challenge: string;
30
+ }>;
31
+ export declare function discover(issuer: string, doFetch?: Fetch): Promise<ProviderMetadata>;
32
+ export interface AuthorizationRequest {
33
+ clientId: string;
34
+ redirectUri: string;
35
+ scope: string;
36
+ state: string;
37
+ nonce: string;
38
+ codeChallenge: string;
39
+ }
40
+ export declare function authorizationUrl(metadata: ProviderMetadata, request: AuthorizationRequest): string;
41
+ export declare function exchangeCode(metadata: ProviderMetadata, exchange: {
42
+ clientId: string;
43
+ redirectUri: string;
44
+ code: string;
45
+ codeVerifier: string;
46
+ }, doFetch?: Fetch): Promise<TokenResponse>;
47
+ /** Rotates the refresh token; identity-server revokes the family if the old one is replayed. */
48
+ export declare function refreshTokens(metadata: ProviderMetadata, exchange: {
49
+ clientId: string;
50
+ refreshToken: string;
51
+ }, doFetch?: Fetch): Promise<TokenResponse>;
52
+ /** RFC 7009; revoking the refresh token ends the whole authorization. Throws if revocation fails. */
53
+ export declare function revokeToken(metadata: ProviderMetadata, clientId: string, token: string, doFetch?: Fetch, expectedIssuer?: string): Promise<void>;
54
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The identity-server side of a login, for a public native client (RFC 8252): OpenID discovery,
3
+ * PKCE, the authorization URL, and the code, refresh, and revocation calls, all without a
4
+ * client secret. `client_id` alone identifies the CLI; the code verifier is what protects it.
5
+ */
6
+ export class OidcError extends Error {
7
+ status;
8
+ constructor(message, status) {
9
+ super(message);
10
+ this.status = status;
11
+ this.name = 'OidcError';
12
+ }
13
+ }
14
+ export function base64url(bytes) {
15
+ return Buffer.from(bytes).toString('base64url');
16
+ }
17
+ export function randomToken(bytes = 32) {
18
+ return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
19
+ }
20
+ export async function pkce(verifier = randomToken(32)) {
21
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
22
+ return { verifier, challenge: base64url(new Uint8Array(digest)) };
23
+ }
24
+ function trimTrailingSlashes(value) {
25
+ let result = value;
26
+ while (result.endsWith('/')) {
27
+ result = result.slice(0, -1);
28
+ }
29
+ return result;
30
+ }
31
+ export async function discover(issuer, doFetch = fetch) {
32
+ const url = `${trimTrailingSlashes(issuer)}/.well-known/openid-configuration`;
33
+ const response = await doFetch(url);
34
+ if (!response.ok)
35
+ throw new OidcError(`discovery at ${issuer} answered ${response.status}`, response.status);
36
+ const metadata = (await response.json());
37
+ for (const field of ['issuer', 'authorization_endpoint', 'token_endpoint']) {
38
+ if (!metadata[field])
39
+ throw new OidcError(`discovery at ${issuer} lacks ${field}`);
40
+ }
41
+ if (trimTrailingSlashes(String(metadata.issuer)) !== trimTrailingSlashes(issuer)) {
42
+ throw new OidcError(`discovery at ${issuer} names a different issuer`);
43
+ }
44
+ const origin = new URL(issuer).origin;
45
+ for (const field of [
46
+ 'authorization_endpoint',
47
+ 'token_endpoint',
48
+ 'revocation_endpoint',
49
+ ]) {
50
+ const endpoint = metadata[field];
51
+ if (endpoint && new URL(endpoint).origin !== origin)
52
+ throw new OidcError(`discovery at ${issuer}: ${field} is not under the issuer`);
53
+ }
54
+ return metadata;
55
+ }
56
+ export function authorizationUrl(metadata, request) {
57
+ const url = new URL(metadata.authorization_endpoint);
58
+ url.search = new URLSearchParams({
59
+ response_type: 'code',
60
+ client_id: request.clientId,
61
+ redirect_uri: request.redirectUri,
62
+ scope: request.scope,
63
+ state: request.state,
64
+ nonce: request.nonce,
65
+ code_challenge: request.codeChallenge,
66
+ code_challenge_method: 'S256',
67
+ }).toString();
68
+ return url.toString();
69
+ }
70
+ async function tokenRequest(endpoint, form, doFetch) {
71
+ const response = await doFetch(endpoint, {
72
+ method: 'POST',
73
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
74
+ body: new URLSearchParams(form),
75
+ });
76
+ if (!response.ok) {
77
+ let code = `${response.status}`;
78
+ try {
79
+ code = String((await response.json()).error ?? code);
80
+ }
81
+ catch {
82
+ // No OAuth error body; the status is the message.
83
+ }
84
+ throw new OidcError(`token endpoint refused the ${form.grant_type} grant: ${code}`, response.status);
85
+ }
86
+ return (await response.json());
87
+ }
88
+ export function exchangeCode(metadata, exchange, doFetch = fetch) {
89
+ return tokenRequest(metadata.token_endpoint, {
90
+ grant_type: 'authorization_code',
91
+ client_id: exchange.clientId,
92
+ code: exchange.code,
93
+ redirect_uri: exchange.redirectUri,
94
+ code_verifier: exchange.codeVerifier,
95
+ }, doFetch);
96
+ }
97
+ /** Rotates the refresh token; identity-server revokes the family if the old one is replayed. */
98
+ export function refreshTokens(metadata, exchange, doFetch = fetch) {
99
+ return tokenRequest(metadata.token_endpoint, {
100
+ grant_type: 'refresh_token',
101
+ client_id: exchange.clientId,
102
+ refresh_token: exchange.refreshToken,
103
+ }, doFetch);
104
+ }
105
+ /** RFC 7009; revoking the refresh token ends the whole authorization. Throws if revocation fails. */
106
+ export async function revokeToken(metadata, clientId, token, doFetch = fetch, expectedIssuer = metadata.issuer) {
107
+ const issuer = new URL(expectedIssuer);
108
+ const endpoint = new URL(metadata.revocation_endpoint ?? `${metadata.issuer}/oauth2/revoke`);
109
+ if (endpoint.origin !== issuer.origin) {
110
+ throw new OidcError('revocation endpoint is not on the issuer origin');
111
+ }
112
+ const init = {
113
+ method: 'POST',
114
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
115
+ body: new URLSearchParams({ token, client_id: clientId }),
116
+ };
117
+ const response = await doFetch(endpoint.href, init); // NOSONAR: CLI sends its own token to the configured issuer, origin verified above
118
+ if (!response.ok) {
119
+ throw new OidcError(`revocation endpoint returned ${response.status}`);
120
+ }
121
+ }
@@ -0,0 +1,15 @@
1
+ /** A registry origin the CLI may send a credential to, checked by `registryOrigin`. */
2
+ export interface RegistryOrigin {
3
+ /** `scheme://host[:port]`, no path, userinfo, query, or fragment. */
4
+ origin: string;
5
+ /** `host[:port]`, the login server name the tools take. */
6
+ host: string;
7
+ /** True for an `http:` origin, which is only accepted for loopback and in-cluster hosts. */
8
+ plainHttp: boolean;
9
+ }
10
+ /**
11
+ * Checks the registry URL the controller returned before any credential is sent to it.
12
+ */
13
+ export declare function registryOrigin(value: string): RegistryOrigin;
14
+ /** The Basic username the registry ignores; anything else could break `user:password`. */
15
+ export declare function registryUsername(value: string): string;
@@ -0,0 +1,47 @@
1
+ import { CliError } from './credentials.js';
2
+ const LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?';
3
+ const HOSTNAME = new RegExp(String.raw `^${LABEL}(?:\.${LABEL})*$`);
4
+ const IPV6 = /^\[[0-9a-f:.]+\]$/;
5
+ function isClusterLocal(hostname) {
6
+ if (hostname === 'localhost' || hostname === '[::1]')
7
+ return true;
8
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname))
9
+ return true;
10
+ return hostname.endsWith('.svc') || hostname.endsWith('.svc.cluster.local');
11
+ }
12
+ /**
13
+ * Checks the registry URL the controller returned before any credential is sent to it.
14
+ */
15
+ export function registryOrigin(value) {
16
+ const refuse = (why) => {
17
+ throw new CliError(`the controller returned an unusable registry URL: ${why}`);
18
+ };
19
+ let url;
20
+ try {
21
+ url = new URL(value);
22
+ }
23
+ catch {
24
+ return refuse('not a URL');
25
+ }
26
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
27
+ refuse('the scheme must be https');
28
+ if (url.username || url.password)
29
+ refuse('userinfo is not allowed');
30
+ if (url.pathname !== '/' || url.search || url.hash)
31
+ refuse('path, query, and fragment are not allowed');
32
+ const hostname = url.hostname.toLowerCase();
33
+ if (!HOSTNAME.test(hostname) && !IPV6.test(hostname))
34
+ refuse('the host is not a valid hostname');
35
+ const plainHttp = url.protocol === 'http:';
36
+ if (plainHttp && !isClusterLocal(hostname)) {
37
+ refuse('plain http is only allowed for loopback and in-cluster hosts');
38
+ }
39
+ return { origin: url.origin, host: url.host, plainHttp };
40
+ }
41
+ /** The Basic username the registry ignores; anything else could break `user:password`. */
42
+ export function registryUsername(value) {
43
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(value) || value.startsWith('-')) {
44
+ throw new CliError('the controller returned an unusable registry username');
45
+ }
46
+ return value;
47
+ }
@@ -0,0 +1,157 @@
1
+ export type ControllerPath = '/v1/auth/info' | '/v1/auth/logout' | '/v1/auth/whoami' | '/v1/deploy' | '/v1/deploy/preview' | '/v1/deploy/registry' | '/v1/deployments' | '/v1/deployments/stats' | '/v1/deployments/{service}' | '/v1/deployments/rollback' | '/v1/secrets' | '/v1/secrets/{name}' | '/v1/services' | '/v1/services/{service}' | '/v1/services/{service}/logs' | '/v1/services/{service}/proxy' | '/v1/vars' | '/v1/vars/{name}';
2
+ export type Env = 'prod' | 'staging';
3
+ export type Problem = {
4
+ type?: string;
5
+ title: string;
6
+ status: number;
7
+ detail?: string;
8
+ };
9
+ export type AuthInfo = {
10
+ account: string;
11
+ issuer: string;
12
+ clientId: string;
13
+ };
14
+ export type Principal = {
15
+ user: string;
16
+ account: string;
17
+ role: 'developer' | 'viewer';
18
+ via: 'identity' | 'api-key';
19
+ credentialId?: string;
20
+ };
21
+ export type ComponentReference = {
22
+ reference: string;
23
+ digest: string;
24
+ };
25
+ export type Binding = {
26
+ name: string;
27
+ capability: string;
28
+ serviceName?: string;
29
+ config?: Record<string, string>;
30
+ };
31
+ export type DeployBundle = {
32
+ env: Env;
33
+ service: string;
34
+ component: ComponentReference;
35
+ workload: Record<string, unknown>;
36
+ bindings: Binding[];
37
+ secrets: string[];
38
+ };
39
+ export type RegistryInfo = {
40
+ url: string;
41
+ repositoryPrefix?: string;
42
+ auth: 'basic-identity';
43
+ username: string;
44
+ };
45
+ export type DeployChange = {
46
+ kind: 'create' | 'update' | 'unchanged' | 'delete';
47
+ resource: string;
48
+ name: string;
49
+ detail?: string;
50
+ };
51
+ export type DeployPlan = {
52
+ env: Env;
53
+ service: string;
54
+ changes: DeployChange[];
55
+ };
56
+ export type Deployment = {
57
+ id: string;
58
+ service: string;
59
+ env: Env;
60
+ status: 'pending' | 'rolling' | 'ready' | 'failed' | 'rolled-back';
61
+ component: ComponentReference;
62
+ createdAt: string;
63
+ readyAt?: string;
64
+ rollbackOf?: string;
65
+ };
66
+ export type DeploymentsQuery = {
67
+ env: Env;
68
+ service?: string;
69
+ };
70
+ export type DeploymentList = {
71
+ items: Deployment[];
72
+ };
73
+ export type DeploymentStats = {
74
+ env: Env;
75
+ services: number;
76
+ deployments: number;
77
+ ready: number;
78
+ failed: number;
79
+ lastDeployedAt?: string;
80
+ };
81
+ export type RollbackRequest = {
82
+ env: Env;
83
+ service: string;
84
+ to?: string;
85
+ };
86
+ export type ControllerServiceType = 'keyvalue' | 'messaging' | 'blobstore' | 'postgres' | 'egress';
87
+ export type ServiceParameters = {
88
+ storage?: string;
89
+ memory?: string;
90
+ cpu?: string;
91
+ };
92
+ export type CreateServiceRequest = {
93
+ env: Env;
94
+ type: ControllerServiceType;
95
+ name: string;
96
+ className?: string;
97
+ parameters?: ServiceParameters;
98
+ deletionPolicy?: 'Retain' | 'Delete';
99
+ destinations?: string[];
100
+ };
101
+ export type Service = {
102
+ name: string;
103
+ env: Env;
104
+ type: ControllerServiceType;
105
+ className: string;
106
+ parameters?: ServiceParameters;
107
+ deletionPolicy?: 'Retain' | 'Delete';
108
+ destinations?: string[];
109
+ createdAt: string;
110
+ };
111
+ export type LogEvent = {
112
+ timestamp: string;
113
+ deployment: string;
114
+ instance?: string;
115
+ level?: 'debug' | 'info' | 'warn' | 'error';
116
+ message: string;
117
+ };
118
+ export type LogsQuery = {
119
+ env: Env;
120
+ deployment?: string;
121
+ follow?: boolean;
122
+ since?: string;
123
+ tail?: number;
124
+ };
125
+ export type ConfigEntry = {
126
+ name: string;
127
+ value?: string;
128
+ updatedAt: string;
129
+ };
130
+ export type ConfigList = {
131
+ env: Env;
132
+ items: ConfigEntry[];
133
+ };
134
+ export type SecretEntry = {
135
+ name: string;
136
+ updatedAt: string;
137
+ };
138
+ export type SecretList = {
139
+ env: Env;
140
+ items: SecretEntry[];
141
+ };
142
+ export type VarUnset = {
143
+ warnings: {
144
+ code: 'referenced';
145
+ detail: string;
146
+ deployments: string[];
147
+ }[];
148
+ };
149
+ export type ProxyRequest = {
150
+ env: Env;
151
+ port?: number;
152
+ };
153
+ export type ProxySession = {
154
+ url: string;
155
+ port: number;
156
+ expiresAt: string;
157
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /** One server-sent event, as the `text/event-stream` format frames it. */
2
+ export interface SseEvent {
3
+ event?: string;
4
+ data: string;
5
+ id?: string;
6
+ }
7
+ /**
8
+ * Parses a `text/event-stream` body into events. Comment lines (`:`) are skipped, `data:` lines
9
+ * of one event join with newlines, and a blank line dispatches. The hand-written part of the
10
+ * client: OpenAPI describes the streaming operations but not their framing.
11
+ */
12
+ export declare function events(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Parses a `text/event-stream` body into events. Comment lines (`:`) are skipped, `data:` lines
3
+ * of one event join with newlines, and a blank line dispatches. The hand-written part of the
4
+ * client: OpenAPI describes the streaming operations but not their framing.
5
+ */
6
+ export async function* events(body) {
7
+ const decoder = new TextDecoder();
8
+ let buffer = '';
9
+ let pending = { data: [] };
10
+ const flush = () => {
11
+ if (pending.data.length === 0 && pending.event === undefined)
12
+ return undefined;
13
+ const done = { data: pending.data.join('\n') };
14
+ if (pending.event !== undefined)
15
+ done.event = pending.event;
16
+ if (pending.id !== undefined)
17
+ done.id = pending.id;
18
+ pending = { data: [] };
19
+ return done;
20
+ };
21
+ const take = (line) => {
22
+ if (line === '')
23
+ return flush();
24
+ if (line.startsWith(':'))
25
+ return undefined;
26
+ const colon = line.indexOf(':');
27
+ const field = colon === -1 ? line : line.slice(0, colon);
28
+ let value = colon === -1 ? '' : line.slice(colon + 1);
29
+ if (value.startsWith(' '))
30
+ value = value.slice(1);
31
+ if (field === 'event')
32
+ pending.event = value;
33
+ else if (field === 'data')
34
+ pending.data.push(value);
35
+ else if (field === 'id')
36
+ pending.id = value;
37
+ return undefined;
38
+ };
39
+ const reader = body.getReader();
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ buffer += decoder.decode(value, { stream: true });
45
+ let newline = buffer.indexOf('\n');
46
+ while (newline !== -1) {
47
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
48
+ buffer = buffer.slice(newline + 1);
49
+ const event = take(line);
50
+ if (event)
51
+ yield event;
52
+ newline = buffer.indexOf('\n');
53
+ }
54
+ }
55
+ const tail = take(buffer.replace(/\r$/, ''));
56
+ if (tail)
57
+ yield tail;
58
+ const last = flush();
59
+ if (last)
60
+ yield last;
61
+ }
@@ -0,0 +1,14 @@
1
+ import { type Credential } from './credentials.js';
2
+ /**
3
+ * Reads `--ca-file`: one or more PEM certificates, such as the tenant's `tenant-controller-ca`.
4
+ * Returns them base64-encoded, the form `controller.certificateAuthorityData` takes in the
5
+ * credential store.
6
+ */
7
+ export declare function readCaFile(path: string): string;
8
+ /** The PEM of the CA stored with the credential, if any. */
9
+ export declare function caPem(controller: Credential['controller']): string | undefined;
10
+ /**
11
+ * A `fetch` that also trusts `pem` (on top of the bundled public roots) for TLS. Without a CA it
12
+ * is the given `fetch` unchanged, so `NODE_EXTRA_CA_CERTS` keeps working as before.
13
+ */
14
+ export declare function trusting(base: typeof fetch | undefined, pem: string | undefined): typeof fetch | undefined;