mayura 1.2.2 → 1.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.
- package/README.md +2 -4
- package/docs/README.md +7 -2
- package/docs/guides/authentication.md +3 -1
- package/docs/guides/browsers.md +1 -0
- package/docs/guides/choosing-a-starter.md +4 -1
- package/docs/guides/copy-in-ui.md +36 -4
- package/docs/guides/framework-starters.md +2 -1
- package/docs/guides/hono.md +1 -1
- package/docs/guides/nextjs.md +1 -1
- package/docs/guides/nuxt.md +1 -1
- package/docs/guides/rag-deployment.md +2 -1
- package/docs/guides/rag-modal-pinecone-starter.md +5 -3
- package/docs/guides/react-router.md +1 -1
- package/docs/guides/release-readiness.md +24 -2
- package/docs/guides/sandboxes.md +1 -1
- package/docs/guides/server-and-client.md +8 -3
- package/docs/guides/sveltekit.md +1 -1
- package/docs/guides/tanstack-start.md +1 -1
- package/docs/integrations/browser-stagehand.md +5 -1
- package/docs/integrations/sandbox-codesandbox.md +4 -0
- package/docs/integrations/ui.md +82 -0
- package/docs/project/changelog.md +48 -0
- package/docs/project/whats-new.md +19 -10
- package/docs/reference/integrations.md +11 -3
- package/lib/adapter-code-docker/image/Dockerfile +1 -1
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/ag-ui/package.json +1 -1
- package/lib/artifacts/package.json +1 -1
- package/lib/auth/dist/identity.d.ts +2 -5
- package/lib/auth/dist/identity.d.ts.map +1 -1
- package/lib/auth/dist/identity.js.map +1 -1
- package/lib/auth/package.json +1 -1
- package/lib/auth/src/identity.ts +3 -3
- package/lib/authz/package.json +1 -1
- package/lib/browser/package.json +1 -1
- package/lib/cli/dist/deploy-targets.js +1 -1
- package/lib/cli/dist/deploy-targets.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/deploy-targets.ts +1 -1
- package/lib/cli/starters/support-agent/src/dev-request.ts +18 -0
- package/lib/cli/starters/support-agent/src/dev.ts +7 -4
- package/lib/cli/starters/support-agent/test/dev-request.test.ts +19 -0
- package/lib/client/dist/index.js +2 -2
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/index.ts +2 -2
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/package.json +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/files/dist/store.d.ts.map +1 -1
- package/lib/files/dist/store.js +15 -2
- package/lib/files/dist/store.js.map +1 -1
- package/lib/files/package.json +1 -1
- package/lib/files/src/store.ts +15 -2
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/keys/dist/manager.d.ts +1 -4
- package/lib/keys/dist/manager.d.ts.map +1 -1
- package/lib/keys/dist/manager.js +6 -4
- package/lib/keys/dist/manager.js.map +1 -1
- package/lib/keys/dist/verifier.d.ts +2 -1
- package/lib/keys/dist/verifier.d.ts.map +1 -1
- package/lib/keys/dist/verifier.js +2 -2
- package/lib/keys/dist/verifier.js.map +1 -1
- package/lib/keys/package.json +1 -1
- package/lib/keys/src/manager.ts +8 -6
- package/lib/keys/src/verifier.ts +4 -4
- package/lib/memory/package.json +1 -1
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/rag/package.json +1 -1
- package/lib/runtime/package.json +1 -1
- package/lib/sandbox/package.json +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/server/dist/index.d.ts +2 -1
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +29 -24
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +26 -20
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/package.json +1 -1
- package/lib/skills/package.json +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/terminal/package.json +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/threads/package.json +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/voice/package.json +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workstream/package.json +1 -1
- package/llms-full.txt +267 -37
- package/llms.txt +8 -3
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerIdentity } from '../../server/dist/index.js';
|
|
1
|
+
import type { AgentServerOptions, ServerIdentity } from '../../server/dist/index.js';
|
|
2
2
|
import { type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';
|
|
3
3
|
/** A permission Mayura's server knows. */
|
|
4
4
|
export type ServerCapability = ServerIdentity['capabilities'][number];
|
|
@@ -14,10 +14,7 @@ export interface IdentityGrant {
|
|
|
14
14
|
}
|
|
15
15
|
/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */
|
|
16
16
|
export interface Authenticator {
|
|
17
|
-
(request:
|
|
18
|
-
readonly token: string;
|
|
19
|
-
readonly signal: AbortSignal;
|
|
20
|
-
}): Promise<ServerIdentity | null>;
|
|
17
|
+
(request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;
|
|
21
18
|
/** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */
|
|
22
19
|
readonly accepts: (token: string) => boolean;
|
|
23
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACzE,OAAO,EAAc,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AAExF,0CAA0C;AAC1C,MAAM,MAAM,gBAAgB,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC;AACtE,6EAA6E;AAC7E,eAAO,MAAM,kBAAkB,EAAE,SAAS,gBAAgB,EACwD,CAAC;AAEnH,2HAA2H;AAC3H,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,QAAQ,CAAC,YAAY,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACnD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,0FAA0F;AAC1F,MAAM,WAAW,aAAa;IAC5B,CAAC,OAAO,EAAE,UAAU,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAC7F,0HAA0H;IAC1H,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,MA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,MAAM,CAAC,GAAG,GAAG,KAAK,EAAE,aAAa,CAAC,CAAC;IACtH,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAG,cAAwC;IAC7E,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,EAAE,CAAC;QACjI,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,yDAAyD,CAAC,CAAC;IACrG,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC;IACjC,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1E,MAAM,YAAY,GAAG,KAAK,EAAE,OAAiE,EAAkC,EAAE;QAC/H,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9D,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport { sha256, toBase64Url } from '@mayura/core/host';\nimport type { ServerIdentity } from '@mayura/server';\nimport { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';\n\n/** A permission Mayura's server knows. */\nexport type ServerCapability = ServerIdentity['capabilities'][number];\n/** Every permission Mayura's server knows, for mapping tables and checks. */\nexport const serverCapabilities: readonly ServerCapability[] = Object.freeze(['runs:read', 'runs:submit', 'runs:cancel', 'runs:approve', 'runs:resume', 'threads:read', 'threads:write', 'threads:delete', 'threads:compact', 'threads:import', 'operations:read',\n 'humans:read', 'humans:respond', 'workflows:read', 'workflows:control', 'workflows:fleet', 'workflows:migrate']);\n\n/** What a verified caller may do, as an identity mapping returns it; `expiresAtMs` defaults to the credential's expiry. */\nexport interface IdentityGrant {\n readonly principalId: string;\n readonly projectId: string;\n readonly agentIds: readonly string[];\n readonly capabilities: readonly ServerCapability[];\n readonly expiresAtMs?: number;\n}\n\n/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */\nexport interface Authenticator {\n (request: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null>;\n /** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */\n readonly accepts: (token: string) => boolean;\n}\n\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/u;\nconst namespacePattern = /^[a-z0-9][a-z0-9.-]{0,31}$/u;\n\n/**\n * A principal id for a subject of an identity provider, as Mayura's server accepts one: `<namespace>/<subject>`. A\n * subject with characters the server does not accept (such as Auth0's `auth0|123`), or too long, becomes `_` and the\n * base64url of its SHA-256: stable, and never equal to a subject kept as it is.\n */\nexport function principalId(namespace: string, subject: string): string {\n if (typeof namespace !== 'string' || !namespacePattern.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'principalId(): namespace is 1-32 lowercase letters, digits, \".\" or \"-\".');\n if (typeof subject !== 'string' || subject === '') throw new MayuraError('INVALID_INPUT', 'principalId(): subject is a non-empty string.');\n const id = `${namespace}/${subject}`;\n if (!subject.startsWith('_') && identifier.test(id)) return id;\n return `${namespace}/_${toBase64Url(sha256(subject))}`;\n}\n\n/**\n * Mayura capabilities for an identity provider's permissions or roles, through an explicit table: each listed value\n * grants its capabilities, and anything not in the table grants nothing.\n */\nexport function mapCapabilities(values: unknown, table: Readonly<Record<string, readonly ServerCapability[]>>): ServerCapability[] {\n if (!table || typeof table !== 'object') throw new MayuraError('INVALID_CONFIG', 'mapCapabilities(): table maps permission names to capabilities.');\n for (const [name, granted] of Object.entries(table)) {\n if (!Array.isArray(granted) || granted.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', `mapCapabilities(): ${name} maps to capabilities Mayura's server knows.`);\n }\n const list = typeof values === 'string' ? values.split(' ') : Array.isArray(values) ? values : [];\n const found = new Set<ServerCapability>();\n for (const value of list) if (typeof value === 'string' && Object.hasOwn(table, value)) for (const capability of table[value]!) found.add(capability);\n return serverCapabilities.filter(capability => found.has(capability));\n}\n\n/** @internal An identity the server accepts, from a grant; null when the grant is unusable or already expired. */\nexport function identityFrom(grant: IdentityGrant | null | undefined, credentialExpiresAtMs: number, maxIdentityMs: number): ServerIdentity | null {\n if (!grant) return null;\n const { principalId: principal, projectId, agentIds, capabilities } = grant;\n if (typeof principal !== 'string' || !identifier.test(principal) || typeof projectId !== 'string' || !identifier.test(projectId)) {\n throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned a principalId or projectId Mayura cannot use: 1-128 letters, digits, \".\", \"_\", \"/\" or \"-\", starting with a letter or digit.');\n }\n if (!Array.isArray(agentIds) || agentIds.length > 256 || agentIds.some(id => typeof id !== 'string' || !identifier.test(id))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned agentIds Mayura cannot use.');\n if (!Array.isArray(capabilities) || capabilities.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned capabilities Mayura\\'s server does not know.');\n const now = Date.now();\n const requested = grant.expiresAtMs ?? credentialExpiresAtMs;\n if (!Number.isSafeInteger(requested)) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned an expiresAtMs that is not a whole number of milliseconds.');\n // Never past the credential, and never longer than maxIdentityMs: the caller presents the credential again.\n const expiresAtMs = Math.min(requested, credentialExpiresAtMs, now + maxIdentityMs);\n if (expiresAtMs <= now) return null;\n return Object.freeze({\n scope: Object.freeze({ principalId: principal, projectId }), agentIds: Object.freeze([...new Set(agentIds)]),\n capabilities: Object.freeze(serverCapabilities.filter(capability => capabilities.includes(capability))), expiresAtMs,\n });\n}\n\n/**\n * The identity Mayura's server takes, from what a verified credential may do: checked against what the server accepts,\n * and lasting no longer than the credential nor `maxIdentityMs` (60 s by default). Null for no grant, or one already\n * over. For authenticators of your own; the ones here use it.\n */\nexport function serverIdentity(grant: IdentityGrant | null | undefined, options: { readonly credentialExpiresAtMs: number; readonly maxIdentityMs?: number }): ServerIdentity | null {\n if (!options || typeof options.credentialExpiresAtMs !== 'number' || Number.isNaN(options.credentialExpiresAtMs)) throw new MayuraError('INVALID_CONFIG', 'serverIdentity(): credentialExpiresAtMs is when the credential expires.');\n return identityFrom(grant, options.credentialExpiresAtMs, checkMaxIdentityMs(options.maxIdentityMs, 'serverIdentity()'));\n}\n\nexport interface JwtAuthenticatorOptions {\n readonly verifier: JwtVerifier;\n /**\n * What a verified token's holder may do, or null to refuse. Grant only what your application decides: a valid token\n * proves who someone is, not what they may do here.\n */\n readonly identity: (claims: JwtClaims, header: JwtHeader) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** The longest an identity lasts before the token is checked again; 60 s by default (1 s to 1 hour). */\n readonly maxIdentityMs?: number;\n}\n\n/** @internal */\nexport function checkMaxIdentityMs(value: number | undefined, owner: string): number {\n const result = value ?? 60_000;\n if (!Number.isSafeInteger(result) || result < 1_000 || result > 3_600_000) throw new MayuraError('INVALID_CONFIG', `${owner}: maxIdentityMs is 1,000 to 3,600,000.`);\n return result;\n}\n\n/**\n * A server `authenticate` for JWTs from one issuer: the verifier checks the token, then `identity` decides what its\n * holder may do. It accepts only tokens naming the verifier's issuer, so several can be chained.\n */\nexport function jwtAuthenticator(options: JwtAuthenticatorOptions): Authenticator {\n if (!options?.verifier || typeof options.verifier.verify !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): verifier is jwtVerifier(...).');\n if (typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): identity decides what a verified caller may do.');\n const maxIdentityMs = checkMaxIdentityMs(options.maxIdentityMs, 'jwtAuthenticator()');\n const issuers = options.verifier.issuers;\n const accepts = (token: string) => { const iss = peekIssuer(token); return iss !== undefined && issuers.includes(iss); };\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n if (!accepts(token)) return null;\n const result = await options.verifier.verify(token, { signal });\n if (!result.ok) return null;\n return identityFrom(await options.identity(result.claims, result.header), result.claims.exp * 1_000, maxIdentityMs);\n };\n return Object.assign(authenticate, { accepts });\n}\n\n/**\n * One server `authenticate` from several: a token goes to the first authenticator that accepts it (by issuer or key\n * prefix), and nothing else sees it. A token none accepts is refused.\n */\nexport function chainAuthenticators(...authenticators: readonly Authenticator[]): Authenticator {\n if (authenticators.length === 0 || authenticators.some(item => typeof item !== 'function' || typeof item.accepts !== 'function')) {\n throw new MayuraError('INVALID_CONFIG', 'chainAuthenticators() takes one or more authenticators.');\n }\n const list = [...authenticators];\n const accepts = (token: string) => list.some(item => item.accepts(token));\n const authenticate = async (request: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n const chosen = list.find(item => item.accepts(request.token));\n return chosen ? chosen(request) : null;\n };\n return Object.assign(authenticate, { accepts });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,UAAU,EAAoD,MAAM,UAAU,CAAC;AAIxF,6EAA6E;AAC7E,MAAM,CAAC,MAAM,kBAAkB,GAAgC,MAAM,CAA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C,EAAE,CAAC;QACjI,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,yDAAyD,CAAC,CAAC;IACrG,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC;IACjC,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1E,MAAM,YAAY,GAAG,KAAK,EAAE,OAAqC,EAAkC,EAAE;QACnG,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9D,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport { sha256, toBase64Url } from '@mayura/core/host';\nimport type { AgentServerOptions, ServerIdentity } from '@mayura/server';\nimport { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';\n\n/** A permission Mayura's server knows. */\nexport type ServerCapability = ServerIdentity['capabilities'][number];\n/** Every permission Mayura's server knows, for mapping tables and checks. */\nexport const serverCapabilities: readonly ServerCapability[] = Object.freeze(['runs:read', 'runs:submit', 'runs:cancel', 'runs:approve', 'runs:resume', 'threads:read', 'threads:write', 'threads:delete', 'threads:compact', 'threads:import', 'operations:read',\n 'humans:read', 'humans:respond', 'workflows:read', 'workflows:control', 'workflows:fleet', 'workflows:migrate']);\n\n/** What a verified caller may do, as an identity mapping returns it; `expiresAtMs` defaults to the credential's expiry. */\nexport interface IdentityGrant {\n readonly principalId: string;\n readonly projectId: string;\n readonly agentIds: readonly string[];\n readonly capabilities: readonly ServerCapability[];\n readonly expiresAtMs?: number;\n}\n\n/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */\nexport interface Authenticator {\n (request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;\n /** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */\n readonly accepts: (token: string) => boolean;\n}\n\nconst identifier = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/u;\nconst namespacePattern = /^[a-z0-9][a-z0-9.-]{0,31}$/u;\n\n/**\n * A principal id for a subject of an identity provider, as Mayura's server accepts one: `<namespace>/<subject>`. A\n * subject with characters the server does not accept (such as Auth0's `auth0|123`), or too long, becomes `_` and the\n * base64url of its SHA-256: stable, and never equal to a subject kept as it is.\n */\nexport function principalId(namespace: string, subject: string): string {\n if (typeof namespace !== 'string' || !namespacePattern.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'principalId(): namespace is 1-32 lowercase letters, digits, \".\" or \"-\".');\n if (typeof subject !== 'string' || subject === '') throw new MayuraError('INVALID_INPUT', 'principalId(): subject is a non-empty string.');\n const id = `${namespace}/${subject}`;\n if (!subject.startsWith('_') && identifier.test(id)) return id;\n return `${namespace}/_${toBase64Url(sha256(subject))}`;\n}\n\n/**\n * Mayura capabilities for an identity provider's permissions or roles, through an explicit table: each listed value\n * grants its capabilities, and anything not in the table grants nothing.\n */\nexport function mapCapabilities(values: unknown, table: Readonly<Record<string, readonly ServerCapability[]>>): ServerCapability[] {\n if (!table || typeof table !== 'object') throw new MayuraError('INVALID_CONFIG', 'mapCapabilities(): table maps permission names to capabilities.');\n for (const [name, granted] of Object.entries(table)) {\n if (!Array.isArray(granted) || granted.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', `mapCapabilities(): ${name} maps to capabilities Mayura's server knows.`);\n }\n const list = typeof values === 'string' ? values.split(' ') : Array.isArray(values) ? values : [];\n const found = new Set<ServerCapability>();\n for (const value of list) if (typeof value === 'string' && Object.hasOwn(table, value)) for (const capability of table[value]!) found.add(capability);\n return serverCapabilities.filter(capability => found.has(capability));\n}\n\n/** @internal An identity the server accepts, from a grant; null when the grant is unusable or already expired. */\nexport function identityFrom(grant: IdentityGrant | null | undefined, credentialExpiresAtMs: number, maxIdentityMs: number): ServerIdentity | null {\n if (!grant) return null;\n const { principalId: principal, projectId, agentIds, capabilities } = grant;\n if (typeof principal !== 'string' || !identifier.test(principal) || typeof projectId !== 'string' || !identifier.test(projectId)) {\n throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned a principalId or projectId Mayura cannot use: 1-128 letters, digits, \".\", \"_\", \"/\" or \"-\", starting with a letter or digit.');\n }\n if (!Array.isArray(agentIds) || agentIds.length > 256 || agentIds.some(id => typeof id !== 'string' || !identifier.test(id))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned agentIds Mayura cannot use.');\n if (!Array.isArray(capabilities) || capabilities.some(capability => !serverCapabilities.includes(capability))) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned capabilities Mayura\\'s server does not know.');\n const now = Date.now();\n const requested = grant.expiresAtMs ?? credentialExpiresAtMs;\n if (!Number.isSafeInteger(requested)) throw new MayuraError('INVALID_CONFIG', 'The identity mapping returned an expiresAtMs that is not a whole number of milliseconds.');\n // Never past the credential, and never longer than maxIdentityMs: the caller presents the credential again.\n const expiresAtMs = Math.min(requested, credentialExpiresAtMs, now + maxIdentityMs);\n if (expiresAtMs <= now) return null;\n return Object.freeze({\n scope: Object.freeze({ principalId: principal, projectId }), agentIds: Object.freeze([...new Set(agentIds)]),\n capabilities: Object.freeze(serverCapabilities.filter(capability => capabilities.includes(capability))), expiresAtMs,\n });\n}\n\n/**\n * The identity Mayura's server takes, from what a verified credential may do: checked against what the server accepts,\n * and lasting no longer than the credential nor `maxIdentityMs` (60 s by default). Null for no grant, or one already\n * over. For authenticators of your own; the ones here use it.\n */\nexport function serverIdentity(grant: IdentityGrant | null | undefined, options: { readonly credentialExpiresAtMs: number; readonly maxIdentityMs?: number }): ServerIdentity | null {\n if (!options || typeof options.credentialExpiresAtMs !== 'number' || Number.isNaN(options.credentialExpiresAtMs)) throw new MayuraError('INVALID_CONFIG', 'serverIdentity(): credentialExpiresAtMs is when the credential expires.');\n return identityFrom(grant, options.credentialExpiresAtMs, checkMaxIdentityMs(options.maxIdentityMs, 'serverIdentity()'));\n}\n\nexport interface JwtAuthenticatorOptions {\n readonly verifier: JwtVerifier;\n /**\n * What a verified token's holder may do, or null to refuse. Grant only what your application decides: a valid token\n * proves who someone is, not what they may do here.\n */\n readonly identity: (claims: JwtClaims, header: JwtHeader) => IdentityGrant | null | Promise<IdentityGrant | null>;\n /** The longest an identity lasts before the token is checked again; 60 s by default (1 s to 1 hour). */\n readonly maxIdentityMs?: number;\n}\n\n/** @internal */\nexport function checkMaxIdentityMs(value: number | undefined, owner: string): number {\n const result = value ?? 60_000;\n if (!Number.isSafeInteger(result) || result < 1_000 || result > 3_600_000) throw new MayuraError('INVALID_CONFIG', `${owner}: maxIdentityMs is 1,000 to 3,600,000.`);\n return result;\n}\n\n/**\n * A server `authenticate` for JWTs from one issuer: the verifier checks the token, then `identity` decides what its\n * holder may do. It accepts only tokens naming the verifier's issuer, so several can be chained.\n */\nexport function jwtAuthenticator(options: JwtAuthenticatorOptions): Authenticator {\n if (!options?.verifier || typeof options.verifier.verify !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): verifier is jwtVerifier(...).');\n if (typeof options.identity !== 'function') throw new MayuraError('INVALID_CONFIG', 'jwtAuthenticator(): identity decides what a verified caller may do.');\n const maxIdentityMs = checkMaxIdentityMs(options.maxIdentityMs, 'jwtAuthenticator()');\n const issuers = options.verifier.issuers;\n const accepts = (token: string) => { const iss = peekIssuer(token); return iss !== undefined && issuers.includes(iss); };\n const authenticate = async ({ token, signal }: { readonly token: string; readonly signal: AbortSignal }): Promise<ServerIdentity | null> => {\n if (!accepts(token)) return null;\n const result = await options.verifier.verify(token, { signal });\n if (!result.ok) return null;\n return identityFrom(await options.identity(result.claims, result.header), result.claims.exp * 1_000, maxIdentityMs);\n };\n return Object.assign(authenticate, { accepts });\n}\n\n/**\n * One server `authenticate` from several: a token goes to the first authenticator that accepts it (by issuer or key\n * prefix), and nothing else sees it. A token none accepts is refused.\n */\nexport function chainAuthenticators(...authenticators: readonly Authenticator[]): Authenticator {\n if (authenticators.length === 0 || authenticators.some(item => typeof item !== 'function' || typeof item.accepts !== 'function')) {\n throw new MayuraError('INVALID_CONFIG', 'chainAuthenticators() takes one or more authenticators.');\n }\n const list = [...authenticators];\n const accepts = (token: string) => list.some(item => item.accepts(token));\n const authenticate = async (request: Parameters<Authenticator>[0]): Promise<ServerIdentity | null> => {\n const chosen = list.find(item => item.accepts(request.token));\n return chosen ? chosen(request) : null;\n };\n return Object.assign(authenticate, { accepts });\n}\n"]}
|
package/lib/auth/package.json
CHANGED
package/lib/auth/src/identity.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MayuraError } from '@mayura/core';
|
|
2
2
|
import { sha256, toBase64Url } from '@mayura/core/host';
|
|
3
|
-
import type { ServerIdentity } from '@mayura/server';
|
|
3
|
+
import type { AgentServerOptions, ServerIdentity } from '@mayura/server';
|
|
4
4
|
import { peekIssuer, type JwtClaims, type JwtHeader, type JwtVerifier } from './jwt.js';
|
|
5
5
|
|
|
6
6
|
/** A permission Mayura's server knows. */
|
|
@@ -20,7 +20,7 @@ export interface IdentityGrant {
|
|
|
20
20
|
|
|
21
21
|
/** Mayura's server `authenticate` callback, with a way to tell which tokens it is for. */
|
|
22
22
|
export interface Authenticator {
|
|
23
|
-
(request:
|
|
23
|
+
(request: Parameters<AgentServerOptions['authenticate']>[0]): Promise<ServerIdentity | null>;
|
|
24
24
|
/** Whether this authenticator is for a token of this shape (an issuer, a key prefix), checked before any verification. */
|
|
25
25
|
readonly accepts: (token: string) => boolean;
|
|
26
26
|
}
|
|
@@ -134,7 +134,7 @@ export function chainAuthenticators(...authenticators: readonly Authenticator[])
|
|
|
134
134
|
}
|
|
135
135
|
const list = [...authenticators];
|
|
136
136
|
const accepts = (token: string) => list.some(item => item.accepts(token));
|
|
137
|
-
const authenticate = async (request:
|
|
137
|
+
const authenticate = async (request: Parameters<Authenticator>[0]): Promise<ServerIdentity | null> => {
|
|
138
138
|
const chosen = list.find(item => item.accepts(request.token));
|
|
139
139
|
return chosen ? chosen(request) : null;
|
|
140
140
|
};
|
package/lib/authz/package.json
CHANGED
package/lib/browser/package.json
CHANGED
|
@@ -217,7 +217,7 @@ const manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/k
|
|
|
217
217
|
* `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).
|
|
218
218
|
*/
|
|
219
219
|
export function releaseSlug(tag) {
|
|
220
|
-
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(
|
|
220
|
+
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+/u, '').slice(0, 13).replace(/-+$/u, '');
|
|
221
221
|
return slug || 'release';
|
|
222
222
|
}
|
|
223
223
|
function render(manifest, path, image, slug) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deploy-targets.js","sourceRoot":"","sources":["../src/deploy-targets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAA8E,MAAM,aAAa,CAAC;AAE7H,sHAAsH;AAEtH,MAAM,SAAS,GAAG,6FAA6F,CAAC;AAChH,MAAM,aAAa,GAAG,kFAAkF,CAAC;AACzG,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AAEpD,SAAS,cAAc,CAAC,KAA4B,EAAE,MAAc,EAAE,OAA0B;IAC9F,IAAI,KAAK,K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,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,OAAO,CAAC,IAAI,SAAS,EAAE,OAAO,CAAC,EAAE;SAC3K,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEH,qFAAqF;AACrF,MAAM,CAAC,MAAM,oBAAoB,GAA2C,MAAM,CAAC,MAAM,CAAC;IACxF,MAAM,EAAE,YAAuC,EAAE,OAAO,EAAE,aAAwC,EAAE,UAAU,EAAE,gBAA2C;CAC5J,CAAC,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type JsonValue } from '@mayura/core';\nimport { defineDeployTarget, type DeployProject, type DeployRelease, type DeployStep, type DeployTarget } from './deploy.js';\n\n// The container targets every Mayura app can use without a platform package: an image, Docker Compose and Kubernetes.\n\nconst nodeImage = 'node:24.14.1-alpine@sha256:8510330d3eb72c804231a834b1a8ebb55cb3796c3e4431297a24d246b8add4d5';\nconst postgresImage = 'postgres@sha256:f02121de6f74d30d8a94cd1d9584125e2178d7e6c377d8130112d4e52d867995';\n/** In the Kubernetes manifests: the image and the release, replaced when a release is planned. */\nexport const IMAGE_PLACEHOLDER = 'mayura-app-image';\nexport const RELEASE_PLACEHOLDER = 'mayura-release';\n\nfunction settingsObject(value: JsonValue | undefined, target: string, allowed: readonly string[]): JsonObject {\n if (value === undefined) return {};\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !allowed.includes(key))) {\n throw new MayuraError('INVALID_CONFIG', `targets.${target} allows only ${allowed.length ? allowed.join(', ') : 'no settings'}.`);\n }\n return value;\n}\nfunction needImage(release: DeployRelease, target: string): string {\n if (release.image === undefined) throw new MayuraError('INVALID_CONFIG', `The ${target} target pushes an image: set \"image\" in mayura.deploy.json.`);\n return release.image;\n}\n\n/**\n * The application image: built once, it runs any role. With `entrypoint: false` it has no entry point, and its default\n * command is the full `node …/bin.js serve` line, for platforms whose start commands replace the entry point.\n */\nexport function dockerfile(project: DeployProject, options: { readonly entrypoint?: boolean } = {}): string {\n const cli = 'node_modules/mayura/lib/cli/dist/bin.js';\n const start = options.entrypoint === false\n ? `CMD [\"node\", \"${cli}\", \"serve\", \"--app\", \"${project.app}\"]`\n : `ENTRYPOINT [\"node\", \"${cli}\"]\nCMD [\"serve\", \"--app\", \"${project.app}\"]`;\n return `# One image for every role; the command chooses serve, worker or migrate.\nFROM ${nodeImage} AS build\nWORKDIR /app\nCOPY package.json package-lock.json* ./\nRUN npm install --no-audit --no-fund\nCOPY . .\nRUN npx tsc -p tsconfig.json && npm prune --omit=dev\n\nFROM ${nodeImage}\nWORKDIR /app\nCOPY --from=build --chown=65532:65532 /app/package.json ./\nCOPY --from=build --chown=65532:65532 /app/node_modules ./node_modules\nCOPY --from=build --chown=65532:65532 /app/dist ./dist\nUSER 65532:65532\nENV NODE_ENV=production MAYURA_ENV=production\nEXPOSE ${project.port} ${project.probePort}\n${start}\n`;\n}\nexport const dockerignore = 'node_modules\\ndist\\n.data\\n.env\\n.env.*\\n*.sqlite*\\n.git\\n';\n\n/** Build and push the release's image: the first steps of every target that runs it somewhere else. */\nexport function imageSteps(release: DeployRelease, target: string): DeployStep[] {\n const image = needImage(release, target);\n return [\n { id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--tag', image, '.'] },\n { id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },\n ];\n}\n\nexport const dockerTarget = defineDeployTarget<Record<string, never>>({\n id: 'docker', description: 'Build the application image and push it to its registry.', tools: ['docker'],\n settings: value => { settingsObject(value, 'docker', []); return {}; },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore }),\n plan: ({ release }) => imageSteps(release, 'docker'),\n});\n\nfunction composeFile(project: DeployProject): string {\n const database = `postgres://app:\\${POSTGRES_PASSWORD}@postgres:5432/app`;\n // BusyBox wget is in the Alpine Node image; it exits non-zero unless /readyz answers 2xx.\n const probe = (portNumber: number) => `[\"CMD\", \"wget\", \"-q\", \"-O\", \"/dev/null\", \"http://127.0.0.1:${portNumber}/readyz\"]`;\n return `# Production-shaped stack: PostgreSQL, a one-shot migration, the server and a worker, from one image.\n# Put a TLS proxy in front of \\`server\\`; it must forward to port ${project.port} with the public origin's Host.\n# cp .env.example .env # set POSTGRES_PASSWORD and the app's variables\nservices:\n postgres:\n image: ${postgresImage}\n environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: \"\\${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}\", POSTGRES_DB: app }\n volumes: [postgres-data:/var/lib/postgresql/data]\n healthcheck: { test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"], interval: 2s, timeout: 5s, retries: 30 }\n migrate:\n build: .\n command: [\"migrate\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { postgres: { condition: service_healthy } }\n server:\n build: .\n command: [\"serve\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n ports: [\"${project.port}:${project.port}\"]\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.port)}, interval: 5s, timeout: 5s, retries: 30 }\n worker:\n build: .\n command: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.probePort)}, interval: 5s, timeout: 5s, retries: 30 }\nvolumes:\n postgres-data:\n`;\n}\n\nexport const composeTarget = defineDeployTarget<{ readonly projectName?: string }>({\n id: 'compose', description: 'Run PostgreSQL, the migration, the server and a worker with Docker Compose.', tools: ['docker'],\n settings: value => {\n const settings = settingsObject(value, 'compose', ['projectName']); const projectName = settings['projectName'];\n if (projectName !== undefined && (typeof projectName !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(projectName))) throw new MayuraError('INVALID_CONFIG', 'targets.compose.projectName must be a Compose project name.');\n return projectName === undefined ? {} : { projectName };\n },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore, 'compose.yaml': composeFile(project) }),\n plan: ({ project, settings }) => {\n const compose = ['compose', '--project-name', settings.projectName ?? project.name];\n return [\n { id: 'build', description: 'Build the image', tool: 'docker', args: [...compose, 'build'] },\n { id: 'migrate', description: 'Migrate storage, once, before the new release serves', tool: 'docker', args: [...compose, 'run', '--rm', 'migrate'] },\n { id: 'start', description: 'Start or update the server and the worker, and wait until they are healthy', tool: 'docker', args: [...compose, 'up', '--detach', '--wait', 'server', 'worker'] },\n ];\n },\n});\n\ninterface KubernetesSettings { readonly namespace: string; readonly context?: string; readonly secret: string; readonly serverReplicas: number; readonly workerReplicas: number; readonly timeoutSeconds: number }\n\nconst dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nfunction count(value: JsonValue | undefined, fallback: number, max: number, what: string): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max) throw new MayuraError('INVALID_CONFIG', `targets.kubernetes.${what} must be a whole number from 1 to ${max}.`);\n return value;\n}\n\nfunction migrationJob(project: DeployProject, settings: KubernetesSettings): string {\n return `# One Job per release, run to completion before the rollout. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} and\n# ${RELEASE_PLACEHOLDER} with the release's image and tag; keep both when you edit this file.\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: ${project.name}-migrate-${RELEASE_PLACEHOLDER}\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: migrate }\nspec:\n backoffLimit: 0\n ttlSecondsAfterFinished: 86400\n template:\n spec:\n restartPolicy: Never\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: migrate\n image: ${IMAGE_PLACEHOLDER}\n args: [\"migrate\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n`;\n}\nfunction serverManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# The HTTP server and its Service. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n replicas: ${settings.serverReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: server\n image: ${IMAGE_PLACEHOLDER}\n args: [\"serve\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n ports: [{ containerPort: ${project.port} }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.port} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.port} }, periodSeconds: 10 }\n---\napiVersion: v1\nkind: Service\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n selector: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n ports: [{ port: 80, targetPort: ${project.port} }]\n`;\n}\nfunction workerManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# Workflow workers: one leads, the rest stand by. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-worker\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\nspec:\n replicas: ${settings.workerReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: worker\n image: ${IMAGE_PLACEHOLDER}\n args: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n env: [{ name: MAYURA_WORKER_ID, valueFrom: { fieldRef: { fieldPath: metadata.name } } }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.probePort} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.probePort} }, periodSeconds: 10 }\n`;\n}\n\nconst manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/kubernetes/server.yaml', worker: 'deploy/kubernetes/worker.yaml' } as const;\n\n/**\n * A release tag as it may appear in a Kubernetes name: lowercase, `.` and `_` as `-`, at most 13 characters, so that\n * `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).\n */\nexport function releaseSlug(tag: string): string {\n const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+|-+$/gu, '').slice(0, 13).replace(/-+$/u, '');\n return slug || 'release';\n}\nfunction render(manifest: string, path: string, image: string, slug: string): string {\n if (!manifest.includes(IMAGE_PLACEHOLDER)) throw new MayuraError('INVALID_CONFIG', `${path} must keep the image placeholder ${IMAGE_PLACEHOLDER}.`);\n return manifest.replaceAll(IMAGE_PLACEHOLDER, image).replaceAll(RELEASE_PLACEHOLDER, slug);\n}\n\nexport const kubernetesTarget = defineDeployTarget<KubernetesSettings>({\n id: 'kubernetes', description: 'Build and push the image, run the migration Job, then roll out the server and worker with kubectl.', tools: ['docker', 'kubectl'],\n settings: value => {\n const settings = settingsObject(value, 'kubernetes', ['namespace', 'context', 'secret', 'serverReplicas', 'workerReplicas', 'timeoutSeconds']);\n const namespace = settings['namespace'] ?? 'default'; const context = settings['context']; const secret = settings['secret'];\n if (typeof namespace !== 'string' || !dns.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.namespace must be a Kubernetes namespace name.');\n if (context !== undefined && (typeof context !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,252}$/u.test(context))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.context must be a kubeconfig context name.');\n if (secret !== undefined && (typeof secret !== 'string' || !dns.test(secret))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.secret must be a Secret name.');\n return { namespace, ...(context === undefined ? {} : { context: context as string }), secret: (secret as string | undefined) ?? '',\n serverReplicas: count(settings['serverReplicas'], 2, 100, 'serverReplicas'), workerReplicas: count(settings['workerReplicas'], 2, 100, 'workerReplicas'),\n timeoutSeconds: count(settings['timeoutSeconds'], 600, 3_600, 'timeoutSeconds') };\n },\n files: ({ project, settings }) => {\n const resolved = { ...settings, secret: settings.secret || `${project.name}-env` };\n return { Dockerfile: dockerfile(project), '.dockerignore': dockerignore,\n [manifests.job]: migrationJob(project, resolved), [manifests.server]: serverManifest(project, resolved), [manifests.worker]: workerManifest(project, resolved) };\n },\n plan: async ({ project, settings, release, readFile }) => {\n const image = needImage(release, 'kubernetes'); const slug = releaseSlug(release.tag);\n const kubectl = [...(settings.context === undefined ? [] : ['--context', settings.context]), '--namespace', settings.namespace];\n const job = render(await readFile(manifests.job), manifests.job, image, slug);\n const workloads = `${render(await readFile(manifests.server), manifests.server, image, slug)}---\\n${render(await readFile(manifests.worker), manifests.worker, image, slug)}`;\n const jobName = `${project.name}-migrate-${slug}`; const timeout = `--timeout=${settings.timeoutSeconds}s`;\n return [\n ...imageSteps(release, 'kubernetes'),\n { id: 'migrate', description: `Start the migration Job ${jobName}`, tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: job },\n // A Job's first condition appears only once it has an outcome (SuccessCriteriaMet or Complete, FailureTarget or\n // Failed), so this returns as soon as the migration succeeds or fails, instead of waiting out the timeout.\n { id: 'migrate-finish', description: 'Wait for the migration to finish', tool: 'kubectl', args: [...kubectl, 'wait', '--for=jsonpath={.status.conditions[0].type}', timeout, `job/${jobName}`] },\n { id: 'migrate-logs', description: 'Show what the migration printed', tool: 'kubectl', args: [...kubectl, 'logs', `job/${jobName}`] },\n { id: 'migrate-wait', description: 'Check that the migration succeeded', tool: 'kubectl', args: [...kubectl, 'wait', '--for=condition=complete', '--timeout=30s', `job/${jobName}`] },\n { id: 'roll-out', description: 'Apply the server and worker at the new image', tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: workloads },\n { id: 'server-ready', description: 'Wait for the server rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-server`, timeout] },\n { id: 'worker-ready', description: 'Wait for the worker rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-worker`, timeout] },\n ];\n },\n});\n\n/** The targets every project has. Others come from `@mayurajs/deploy-*` packages. */\nexport const builtInDeployTargets: Readonly<Record<string, DeployTarget>> = Object.freeze({\n docker: dockerTarget as unknown as DeployTarget, compose: composeTarget as unknown as DeployTarget, kubernetes: kubernetesTarget as unknown as DeployTarget,\n});\n"]}
|
|
1
|
+
{"version":3,"file":"deploy-targets.js","sourceRoot":"","sources":["../src/deploy-targets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,kBAAkB,EAA8E,MAAM,aAAa,CAAC;AAE7H,sHAAsH;AAEtH,MAAM,SAAS,GAAG,6FAA6F,CAAC;AAChH,MAAM,aAAa,GAAG,kFAAkF,CAAC;AACzG,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AAEpD,SAAS,cAAc,CAAC,KAA4B,EAAE,MAAc,EAAE,OAA0B;IAC9F,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IACnC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,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C,CAAC;AAEH,qFAAqF;AACrF,MAAM,CAAC,MAAM,oBAAoB,GAA2C,MAAM,CAAC,MAAM,CAAC;IACxF,MAAM,EAAE,YAAuC,EAAE,OAAO,EAAE,aAAwC,EAAE,UAAU,EAAE,gBAA2C;CAC5J,CAAC,CAAC","sourcesContent":["import { MayuraError, type JsonObject, type JsonValue } from '@mayura/core';\nimport { defineDeployTarget, type DeployProject, type DeployRelease, type DeployStep, type DeployTarget } from './deploy.js';\n\n// The container targets every Mayura app can use without a platform package: an image, Docker Compose and Kubernetes.\n\nconst nodeImage = 'node:24.14.1-alpine@sha256:8510330d3eb72c804231a834b1a8ebb55cb3796c3e4431297a24d246b8add4d5';\nconst postgresImage = 'postgres@sha256:f02121de6f74d30d8a94cd1d9584125e2178d7e6c377d8130112d4e52d867995';\n/** In the Kubernetes manifests: the image and the release, replaced when a release is planned. */\nexport const IMAGE_PLACEHOLDER = 'mayura-app-image';\nexport const RELEASE_PLACEHOLDER = 'mayura-release';\n\nfunction settingsObject(value: JsonValue | undefined, target: string, allowed: readonly string[]): JsonObject {\n if (value === undefined) return {};\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !allowed.includes(key))) {\n throw new MayuraError('INVALID_CONFIG', `targets.${target} allows only ${allowed.length ? allowed.join(', ') : 'no settings'}.`);\n }\n return value;\n}\nfunction needImage(release: DeployRelease, target: string): string {\n if (release.image === undefined) throw new MayuraError('INVALID_CONFIG', `The ${target} target pushes an image: set \"image\" in mayura.deploy.json.`);\n return release.image;\n}\n\n/**\n * The application image: built once, it runs any role. With `entrypoint: false` it has no entry point, and its default\n * command is the full `node …/bin.js serve` line, for platforms whose start commands replace the entry point.\n */\nexport function dockerfile(project: DeployProject, options: { readonly entrypoint?: boolean } = {}): string {\n const cli = 'node_modules/mayura/lib/cli/dist/bin.js';\n const start = options.entrypoint === false\n ? `CMD [\"node\", \"${cli}\", \"serve\", \"--app\", \"${project.app}\"]`\n : `ENTRYPOINT [\"node\", \"${cli}\"]\nCMD [\"serve\", \"--app\", \"${project.app}\"]`;\n return `# One image for every role; the command chooses serve, worker or migrate.\nFROM ${nodeImage} AS build\nWORKDIR /app\nCOPY package.json package-lock.json* ./\nRUN npm install --no-audit --no-fund\nCOPY . .\nRUN npx tsc -p tsconfig.json && npm prune --omit=dev\n\nFROM ${nodeImage}\nWORKDIR /app\nCOPY --from=build --chown=65532:65532 /app/package.json ./\nCOPY --from=build --chown=65532:65532 /app/node_modules ./node_modules\nCOPY --from=build --chown=65532:65532 /app/dist ./dist\nUSER 65532:65532\nENV NODE_ENV=production MAYURA_ENV=production\nEXPOSE ${project.port} ${project.probePort}\n${start}\n`;\n}\nexport const dockerignore = 'node_modules\\ndist\\n.data\\n.env\\n.env.*\\n*.sqlite*\\n.git\\n';\n\n/** Build and push the release's image: the first steps of every target that runs it somewhere else. */\nexport function imageSteps(release: DeployRelease, target: string): DeployStep[] {\n const image = needImage(release, target);\n return [\n { id: 'build-image', description: `Build ${image}`, tool: 'docker', args: ['build', '--tag', image, '.'] },\n { id: 'push-image', description: `Push ${image}`, tool: 'docker', args: ['push', image] },\n ];\n}\n\nexport const dockerTarget = defineDeployTarget<Record<string, never>>({\n id: 'docker', description: 'Build the application image and push it to its registry.', tools: ['docker'],\n settings: value => { settingsObject(value, 'docker', []); return {}; },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore }),\n plan: ({ release }) => imageSteps(release, 'docker'),\n});\n\nfunction composeFile(project: DeployProject): string {\n const database = `postgres://app:\\${POSTGRES_PASSWORD}@postgres:5432/app`;\n // BusyBox wget is in the Alpine Node image; it exits non-zero unless /readyz answers 2xx.\n const probe = (portNumber: number) => `[\"CMD\", \"wget\", \"-q\", \"-O\", \"/dev/null\", \"http://127.0.0.1:${portNumber}/readyz\"]`;\n return `# Production-shaped stack: PostgreSQL, a one-shot migration, the server and a worker, from one image.\n# Put a TLS proxy in front of \\`server\\`; it must forward to port ${project.port} with the public origin's Host.\n# cp .env.example .env # set POSTGRES_PASSWORD and the app's variables\nservices:\n postgres:\n image: ${postgresImage}\n environment: { POSTGRES_USER: app, POSTGRES_PASSWORD: \"\\${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}\", POSTGRES_DB: app }\n volumes: [postgres-data:/var/lib/postgresql/data]\n healthcheck: { test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"], interval: 2s, timeout: 5s, retries: 30 }\n migrate:\n build: .\n command: [\"migrate\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { postgres: { condition: service_healthy } }\n server:\n build: .\n command: [\"serve\", \"--app\", \"${project.app}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n ports: [\"${project.port}:${project.port}\"]\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.port)}, interval: 5s, timeout: 5s, retries: 30 }\n worker:\n build: .\n command: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n env_file: .env\n environment: { DATABASE_URL: \"${database}\" }\n depends_on: { migrate: { condition: service_completed_successfully } }\n healthcheck: { test: ${probe(project.probePort)}, interval: 5s, timeout: 5s, retries: 30 }\nvolumes:\n postgres-data:\n`;\n}\n\nexport const composeTarget = defineDeployTarget<{ readonly projectName?: string }>({\n id: 'compose', description: 'Run PostgreSQL, the migration, the server and a worker with Docker Compose.', tools: ['docker'],\n settings: value => {\n const settings = settingsObject(value, 'compose', ['projectName']); const projectName = settings['projectName'];\n if (projectName !== undefined && (typeof projectName !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(projectName))) throw new MayuraError('INVALID_CONFIG', 'targets.compose.projectName must be a Compose project name.');\n return projectName === undefined ? {} : { projectName };\n },\n files: ({ project }) => ({ Dockerfile: dockerfile(project), '.dockerignore': dockerignore, 'compose.yaml': composeFile(project) }),\n plan: ({ project, settings }) => {\n const compose = ['compose', '--project-name', settings.projectName ?? project.name];\n return [\n { id: 'build', description: 'Build the image', tool: 'docker', args: [...compose, 'build'] },\n { id: 'migrate', description: 'Migrate storage, once, before the new release serves', tool: 'docker', args: [...compose, 'run', '--rm', 'migrate'] },\n { id: 'start', description: 'Start or update the server and the worker, and wait until they are healthy', tool: 'docker', args: [...compose, 'up', '--detach', '--wait', 'server', 'worker'] },\n ];\n },\n});\n\ninterface KubernetesSettings { readonly namespace: string; readonly context?: string; readonly secret: string; readonly serverReplicas: number; readonly workerReplicas: number; readonly timeoutSeconds: number }\n\nconst dns = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\nfunction count(value: JsonValue | undefined, fallback: number, max: number, what: string): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max) throw new MayuraError('INVALID_CONFIG', `targets.kubernetes.${what} must be a whole number from 1 to ${max}.`);\n return value;\n}\n\nfunction migrationJob(project: DeployProject, settings: KubernetesSettings): string {\n return `# One Job per release, run to completion before the rollout. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} and\n# ${RELEASE_PLACEHOLDER} with the release's image and tag; keep both when you edit this file.\napiVersion: batch/v1\nkind: Job\nmetadata:\n name: ${project.name}-migrate-${RELEASE_PLACEHOLDER}\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: migrate }\nspec:\n backoffLimit: 0\n ttlSecondsAfterFinished: 86400\n template:\n spec:\n restartPolicy: Never\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: migrate\n image: ${IMAGE_PLACEHOLDER}\n args: [\"migrate\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n`;\n}\nfunction serverManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# The HTTP server and its Service. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n replicas: ${settings.serverReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: server\n image: ${IMAGE_PLACEHOLDER}\n args: [\"serve\", \"--app\", \"${project.app}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n ports: [{ containerPort: ${project.port} }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.port} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.port} }, periodSeconds: 10 }\n---\napiVersion: v1\nkind: Service\nmetadata:\n name: ${project.name}-server\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\nspec:\n selector: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: server }\n ports: [{ port: 80, targetPort: ${project.port} }]\n`;\n}\nfunction workerManifest(project: DeployProject, settings: KubernetesSettings): string {\n return `# Workflow workers: one leads, the rest stand by. \\`mayura deploy\\` replaces ${IMAGE_PLACEHOLDER} with the release's image.\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: ${project.name}-worker\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\nspec:\n replicas: ${settings.workerReplicas}\n selector: { matchLabels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker } }\n template:\n metadata:\n labels: { app.kubernetes.io/name: ${project.name}, app.kubernetes.io/component: worker }\n spec:\n terminationGracePeriodSeconds: 45\n securityContext: { runAsNonRoot: true, runAsUser: 65532 }\n containers:\n - name: worker\n image: ${IMAGE_PLACEHOLDER}\n args: [\"worker\", \"--app\", \"${project.app}\", \"--probe-host\", \"0.0.0.0\", \"--probe-port\", \"${project.probePort}\"]\n envFrom: [{ secretRef: { name: ${settings.secret} } }]\n env: [{ name: MAYURA_WORKER_ID, valueFrom: { fieldRef: { fieldPath: metadata.name } } }]\n readinessProbe: { httpGet: { path: /readyz, port: ${project.probePort} }, periodSeconds: 5 }\n livenessProbe: { httpGet: { path: /livez, port: ${project.probePort} }, periodSeconds: 10 }\n`;\n}\n\nconst manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/kubernetes/server.yaml', worker: 'deploy/kubernetes/worker.yaml' } as const;\n\n/**\n * A release tag as it may appear in a Kubernetes name: lowercase, `.` and `_` as `-`, at most 13 characters, so that\n * `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).\n */\nexport function releaseSlug(tag: string): string {\n const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+/u, '').slice(0, 13).replace(/-+$/u, '');\n return slug || 'release';\n}\nfunction render(manifest: string, path: string, image: string, slug: string): string {\n if (!manifest.includes(IMAGE_PLACEHOLDER)) throw new MayuraError('INVALID_CONFIG', `${path} must keep the image placeholder ${IMAGE_PLACEHOLDER}.`);\n return manifest.replaceAll(IMAGE_PLACEHOLDER, image).replaceAll(RELEASE_PLACEHOLDER, slug);\n}\n\nexport const kubernetesTarget = defineDeployTarget<KubernetesSettings>({\n id: 'kubernetes', description: 'Build and push the image, run the migration Job, then roll out the server and worker with kubectl.', tools: ['docker', 'kubectl'],\n settings: value => {\n const settings = settingsObject(value, 'kubernetes', ['namespace', 'context', 'secret', 'serverReplicas', 'workerReplicas', 'timeoutSeconds']);\n const namespace = settings['namespace'] ?? 'default'; const context = settings['context']; const secret = settings['secret'];\n if (typeof namespace !== 'string' || !dns.test(namespace)) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.namespace must be a Kubernetes namespace name.');\n if (context !== undefined && (typeof context !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,252}$/u.test(context))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.context must be a kubeconfig context name.');\n if (secret !== undefined && (typeof secret !== 'string' || !dns.test(secret))) throw new MayuraError('INVALID_CONFIG', 'targets.kubernetes.secret must be a Secret name.');\n return { namespace, ...(context === undefined ? {} : { context: context as string }), secret: (secret as string | undefined) ?? '',\n serverReplicas: count(settings['serverReplicas'], 2, 100, 'serverReplicas'), workerReplicas: count(settings['workerReplicas'], 2, 100, 'workerReplicas'),\n timeoutSeconds: count(settings['timeoutSeconds'], 600, 3_600, 'timeoutSeconds') };\n },\n files: ({ project, settings }) => {\n const resolved = { ...settings, secret: settings.secret || `${project.name}-env` };\n return { Dockerfile: dockerfile(project), '.dockerignore': dockerignore,\n [manifests.job]: migrationJob(project, resolved), [manifests.server]: serverManifest(project, resolved), [manifests.worker]: workerManifest(project, resolved) };\n },\n plan: async ({ project, settings, release, readFile }) => {\n const image = needImage(release, 'kubernetes'); const slug = releaseSlug(release.tag);\n const kubectl = [...(settings.context === undefined ? [] : ['--context', settings.context]), '--namespace', settings.namespace];\n const job = render(await readFile(manifests.job), manifests.job, image, slug);\n const workloads = `${render(await readFile(manifests.server), manifests.server, image, slug)}---\\n${render(await readFile(manifests.worker), manifests.worker, image, slug)}`;\n const jobName = `${project.name}-migrate-${slug}`; const timeout = `--timeout=${settings.timeoutSeconds}s`;\n return [\n ...imageSteps(release, 'kubernetes'),\n { id: 'migrate', description: `Start the migration Job ${jobName}`, tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: job },\n // A Job's first condition appears only once it has an outcome (SuccessCriteriaMet or Complete, FailureTarget or\n // Failed), so this returns as soon as the migration succeeds or fails, instead of waiting out the timeout.\n { id: 'migrate-finish', description: 'Wait for the migration to finish', tool: 'kubectl', args: [...kubectl, 'wait', '--for=jsonpath={.status.conditions[0].type}', timeout, `job/${jobName}`] },\n { id: 'migrate-logs', description: 'Show what the migration printed', tool: 'kubectl', args: [...kubectl, 'logs', `job/${jobName}`] },\n { id: 'migrate-wait', description: 'Check that the migration succeeded', tool: 'kubectl', args: [...kubectl, 'wait', '--for=condition=complete', '--timeout=30s', `job/${jobName}`] },\n { id: 'roll-out', description: 'Apply the server and worker at the new image', tool: 'kubectl', args: [...kubectl, 'apply', '-f', '-'], stdin: workloads },\n { id: 'server-ready', description: 'Wait for the server rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-server`, timeout] },\n { id: 'worker-ready', description: 'Wait for the worker rollout', tool: 'kubectl', args: [...kubectl, 'rollout', 'status', `deployment/${project.name}-worker`, timeout] },\n ];\n },\n});\n\n/** The targets every project has. Others come from `@mayurajs/deploy-*` packages. */\nexport const builtInDeployTargets: Readonly<Record<string, DeployTarget>> = Object.freeze({\n docker: dockerTarget as unknown as DeployTarget, compose: composeTarget as unknown as DeployTarget, kubernetes: kubernetesTarget as unknown as DeployTarget,\n});\n"]}
|
package/lib/cli/package.json
CHANGED
|
@@ -225,7 +225,7 @@ const manifests = { job: 'deploy/kubernetes/migrate-job.yaml', server: 'deploy/k
|
|
|
225
225
|
* `<name>-migrate-<slug>` stays within Kubernetes' 63 (names are at most 40).
|
|
226
226
|
*/
|
|
227
227
|
export function releaseSlug(tag: string): string {
|
|
228
|
-
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(
|
|
228
|
+
const slug = tag.toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+/u, '').slice(0, 13).replace(/-+$/u, '');
|
|
229
229
|
return slug || 'release';
|
|
230
230
|
}
|
|
231
231
|
function render(manifest: string, path: string, image: string, slug: string): string {
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { RequestOptions } from 'node:http';
|
|
2
|
+
|
|
3
|
+
/** Parse a request target for the local development front server. */
|
|
4
|
+
export function devRequestTarget(value: string | undefined, origin: string): URL | undefined {
|
|
5
|
+
try {
|
|
6
|
+
const target = new URL(value ?? '/', origin);
|
|
7
|
+
if (target.origin === origin && !target.username && !target.password && !target.hash) return target;
|
|
8
|
+
} catch {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Derive the connection from the configured server origin and use only the routed request path and query. */
|
|
15
|
+
export function devUpstreamOptions(origin: string, target: Pick<URL, 'pathname' | 'search'>): RequestOptions {
|
|
16
|
+
const { protocol, hostname, port } = new URL(origin);
|
|
17
|
+
return { protocol, hostname, port, path: target.pathname + target.search };
|
|
18
|
+
}
|
|
@@ -8,6 +8,7 @@ import { MayuraError } from 'mayura/core';
|
|
|
8
8
|
import { createNativeMemory } from 'mayura/memory';
|
|
9
9
|
import { customerPrincipal, devSecrets, tokenDigest } from './auth.js';
|
|
10
10
|
import { loadConfig } from './config.js';
|
|
11
|
+
import { devRequestTarget, devUpstreamOptions } from './dev-request.js';
|
|
11
12
|
import { demoCustomers } from './orders.js';
|
|
12
13
|
import { startServer } from './server.js';
|
|
13
14
|
import { openServices } from './services.js';
|
|
@@ -60,9 +61,9 @@ async function serveFile(pathname: string, response: ServerResponse): Promise<vo
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
/** Forward one API request (including the streamed run events) to the Mayura server, unchanged but for the host. */
|
|
63
|
-
function proxy(request: IncomingMessage, response: ServerResponse): void {
|
|
64
|
+
function proxy(request: IncomingMessage, response: ServerResponse, target: URL): void {
|
|
64
65
|
const headers = { ...request.headers }; delete headers.host; delete headers.connection;
|
|
65
|
-
const upstream = forward(
|
|
66
|
+
const upstream = forward({ ...devUpstreamOptions(server.origin, target), method: request.method, headers }, reply => {
|
|
66
67
|
response.writeHead(reply.statusCode ?? 502, reply.headers); reply.pipe(response);
|
|
67
68
|
});
|
|
68
69
|
upstream.on('error', () => { if (!response.headersSent) response.writeHead(502).end(); else response.destroy(); });
|
|
@@ -84,9 +85,11 @@ async function session(request: IncomingMessage, response: ServerResponse): Prom
|
|
|
84
85
|
}
|
|
85
86
|
|
|
86
87
|
const web = createServer((request, response) => {
|
|
87
|
-
const { pathname } = new URL(request.url ?? '/', webOrigin);
|
|
88
88
|
const handle = async (): Promise<void> => {
|
|
89
|
-
|
|
89
|
+
const target = devRequestTarget(request.url, webOrigin);
|
|
90
|
+
if (!target) { response.writeHead(400, security).end(); return; }
|
|
91
|
+
const { pathname } = target;
|
|
92
|
+
if (pathname.startsWith('/v1/')) return proxy(request, response, target);
|
|
90
93
|
if (pathname === '/dev/customers' && request.method === 'GET') {
|
|
91
94
|
response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...security }).end(JSON.stringify({ customers: demoCustomers })); return;
|
|
92
95
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { test } from 'node:test';
|
|
3
|
+
import { devRequestTarget, devUpstreamOptions } from '../src/dev-request.js';
|
|
4
|
+
|
|
5
|
+
const webOrigin = 'http://127.0.0.1:5173';
|
|
6
|
+
|
|
7
|
+
test('keeps the upstream connection on the configured server and preserves the API path and query', () => {
|
|
8
|
+
const target = devRequestTarget('/v1/runs/example/events?after=2', webOrigin);
|
|
9
|
+
assert(target);
|
|
10
|
+
assert.deepEqual(devUpstreamOptions('http://127.0.0.1:4000', target), {
|
|
11
|
+
protocol: 'http:', hostname: '127.0.0.1', port: '4000', path: '/v1/runs/example/events?after=2',
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('rejects request targets outside the local development origin and malformed URLs', () => {
|
|
16
|
+
assert.equal(devRequestTarget('https://other.example/v1/runs', webOrigin), undefined);
|
|
17
|
+
assert.equal(devRequestTarget('http://[', webOrigin), undefined);
|
|
18
|
+
assert.equal(devRequestTarget(undefined, webOrigin)?.pathname, '/');
|
|
19
|
+
});
|
package/lib/client/dist/index.js
CHANGED
|
@@ -419,7 +419,7 @@ const featureNames = ['humanRequests', 'workflowIndex', 'workflowViews', 'workfl
|
|
|
419
419
|
* RUN_NOT_FOUND, a missing capability or a protocol violation, is final.
|
|
420
420
|
*/
|
|
421
421
|
function retryableStream(error) {
|
|
422
|
-
return ['TRANSPORT_FAILED', 'TIMEOUT', 'TRUNCATED_STREAM', 'RUN_RECORDS_UNAVAILABLE', 'AUTH_EXPIRED'].includes(error.code)
|
|
422
|
+
return ['TRANSPORT_FAILED', 'TIMEOUT', 'TRUNCATED_STREAM', 'RUN_RECORDS_UNAVAILABLE', 'AUTH_EXPIRED', 'AUTH_UNAVAILABLE', 'AUTH_LIMIT'].includes(error.code)
|
|
423
423
|
|| (error.status !== undefined && [408, 429, 502, 503, 504].includes(error.status));
|
|
424
424
|
}
|
|
425
425
|
/** Why a signal ended: the client's own timers abort with a TIMEOUT error; anything else is the caller's cancellation. */
|
|
@@ -694,7 +694,7 @@ export function createClient(options) {
|
|
|
694
694
|
reported = serverError({ error: JSON.parse(data.join('\n')) }, 0, null);
|
|
695
695
|
}
|
|
696
696
|
catch { /* Not a Mayura error frame. */ }
|
|
697
|
-
throw reported && ['OBSERVATION_FAILED', 'RUN_RECORDS_UNAVAILABLE', 'AUTHORIZATION_DENIED'].includes(reported.code)
|
|
697
|
+
throw reported && ['OBSERVATION_FAILED', 'RUN_RECORDS_UNAVAILABLE', 'AUTHORIZATION_DENIED', 'AUTH_INVALID', 'AUTH_EXPIRED', 'AUTH_UNAVAILABLE', 'AUTH_LIMIT'].includes(reported.code)
|
|
698
698
|
? new ClientError(reported.code, undefined, { message: reported.message, details: reported.details }) : new ClientError('OBSERVATION_FAILED');
|
|
699
699
|
}
|
|
700
700
|
let raw;
|