feat(ql3): add secure console cron scheduling

This commit is contained in:
whyour
2026-08-29 17:13:09 +08:00
parent 951de26ffd
commit b970e2aede
30 changed files with 1916 additions and 31 deletions
@@ -28,6 +28,11 @@ import type { LocalApiTaskReadRoute } from '../task/taskReadRoute';
import type { LocalApiTaskStartRoute } from '../task/taskStartRoute';
import type { LocalApiTaskPutRoute } from '../task/taskPutRoute';
import type { LocalApiTaskAuthoringRoute } from '../task/taskAuthoringRoute';
import type {
LocalApiTriggerListRoute,
LocalApiTriggerReadRoute,
} from '../trigger/triggerReadRoutes';
import type { LocalApiTriggerPutRoute } from '../trigger/triggerPutRoute';
import type { LocalApiResponse } from '../transport/contract';
export type LocalApiAdmissionOperation =
@@ -90,6 +95,22 @@ export type LocalApiAdmissionOperation =
operationId: 'task.authoring';
projectId: string;
taskId: string;
}>
| Readonly<{
operationId: 'trigger.list';
projectId: string;
limit: number;
after?: Readonly<{ readonly triggerId: string }>;
}>
| Readonly<{
operationId: 'trigger.get';
projectId: string;
triggerId: string;
}>
| Readonly<{
operationId: 'trigger.put';
projectId: string;
triggerId: string;
}>;
export interface LocalApiAdmissionRequest {
@@ -128,6 +149,9 @@ export interface LocalApiAdmissionOptions {
readonly taskStartRoute: LocalApiTaskStartRoute;
readonly taskPutRoute: LocalApiTaskPutRoute;
readonly taskAuthoringRoute: LocalApiTaskAuthoringRoute;
readonly triggerListRoute: LocalApiTriggerListRoute;
readonly triggerReadRoute: LocalApiTriggerReadRoute;
readonly triggerPutRoute: LocalApiTriggerPutRoute;
readonly now?: () => number;
readonly randomUuid?: () => string;
}
@@ -208,6 +232,9 @@ export function createLocalApiAdmission(
typeof options.taskStartRoute?.handle !== 'function' ||
typeof options.taskPutRoute?.handle !== 'function' ||
typeof options.taskAuthoringRoute?.handle !== 'function' ||
typeof options.triggerListRoute?.handle !== 'function' ||
typeof options.triggerReadRoute?.handle !== 'function' ||
typeof options.triggerPutRoute?.handle !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.randomUuid !== undefined &&
typeof options.randomUuid !== 'function')
@@ -296,6 +323,25 @@ export function createLocalApiAdmission(
});
}
if (request.operation.operationId === 'trigger.put') {
const triggerPutOperation = request.operation;
return Object.freeze({
bodyMode: 'json' as const,
maximumBodyBytes: 20 * 1_024,
async handle(body: unknown | null) {
return options.triggerPutRoute.handle({
requestId: request.requestId,
projectId: triggerPutOperation.projectId,
triggerId: triggerPutOperation.triggerId,
body,
presence: request.localPresence,
authenticated,
signal: request.signal,
});
},
});
}
let decision: Readonly<SecurityPolicyDecision>;
try {
decision = normalizeSecurityPolicyDecision(
@@ -309,7 +355,9 @@ export function createLocalApiAdmission(
: request.operation.operationId === 'task.start'
? 'run.start'
: request.operation.operationId === 'task.list' ||
request.operation.operationId === 'task.get'
request.operation.operationId === 'task.get' ||
request.operation.operationId === 'trigger.list' ||
request.operation.operationId === 'trigger.get'
? 'task.read'
: 'run.read',
),
@@ -443,8 +491,24 @@ export function createLocalApiAdmission(
principal: authenticated.principal,
policyFence: decision.fence,
});
case 'trigger.list':
if (body !== null) return response(400, 'invalid_request_body');
return options.triggerListRoute.handle({
projectId: request.operation.projectId,
limit: request.operation.limit,
...(request.operation.after
? { after: request.operation.after }
: {}),
});
case 'trigger.get':
if (body !== null) return response(400, 'invalid_request_body');
return options.triggerReadRoute.handle({
projectId: request.operation.projectId,
triggerId: request.operation.triggerId,
});
case 'task.put':
case 'task.authoring':
case 'trigger.put':
return response(503, 'request_unavailable');
}
},
@@ -22,6 +22,11 @@ import { createLocalApiTaskReadRoute } from '../task/taskReadRoute';
import { createLocalApiTaskStartRoute } from '../task/taskStartRoute';
import { createLocalApiTaskPutRoute } from '../task/taskPutRoute';
import { createLocalApiTaskAuthoringRoute } from '../task/taskAuthoringRoute';
import {
createLocalApiTriggerListRoute,
createLocalApiTriggerReadRoute,
} from '../trigger/triggerReadRoutes';
import { createLocalApiTriggerPutRoute } from '../trigger/triggerPutRoute';
import { startLocalApiHttpSurface } from '../transport/httpSurface';
export interface LocalApiProductSurfaceEvent {
@@ -165,6 +170,31 @@ export function createLocalApiProductSurface(
? {}
: { randomUuid: options.randomUuid }),
});
const triggerListRoute = createLocalApiTriggerListRoute(
authority.triggers,
);
const triggerReadRoute = createLocalApiTriggerReadRoute(
authority.triggers,
);
const triggerPutRoute = createLocalApiTriggerPutRoute({
projectPolicy: authority.projectPolicy,
triggers: authority.triggers,
triggerAdministrationForCredential: (fence) => {
if (fence.subjectType !== 'user') {
throw new TypeError('Trigger mutation requires a User credential');
}
return authority.triggerAdministrationForCredential({
...fence,
subjectType: 'user',
});
},
securityAudit: authority.securityAudit,
presenceProof,
...(options.now === undefined ? {} : { now: options.now }),
...(options.randomUuid === undefined
? {}
: { randomUuid: options.randomUuid }),
});
const admission = createLocalApiAdmission({
authenticator,
policy,
@@ -180,6 +210,9 @@ export function createLocalApiProductSurface(
taskStartRoute,
taskPutRoute,
taskAuthoringRoute,
triggerListRoute,
triggerReadRoute,
triggerPutRoute,
...(options.now === undefined ? {} : { now: options.now }),
...(options.randomUuid === undefined
? {}
@@ -0,0 +1,26 @@
import {
normalizeSecurityPrincipal,
type SecurityPrincipal,
} from '@qinglong/runtime-core/security';
import type { AuthenticatedLocalApiRequest } from './credentialAuthenticator';
import type { ConsumedLocalPresenceProof } from './localPresenceProof';
export function strongLocalConsolePrincipal(
authenticated: Readonly<AuthenticatedLocalApiRequest>,
proof: Readonly<ConsumedLocalPresenceProof>,
): Readonly<SecurityPrincipal> {
return normalizeSecurityPrincipal(
{
subject: authenticated.principal.subject,
authenticationId: `local_presence:${proof.authorizationId}`,
authenticatedAtMs: proof.authenticatedAtMs,
expiresAtMs: Math.min(
proof.expiresAtMs,
authenticated.principal.expiresAtMs,
),
assurance: 'local_console',
},
proof.authenticatedAtMs,
);
}
@@ -14,7 +14,6 @@ import {
} from '@qinglong/runtime-core/project-policy';
import {
normalizeSecurityPolicyDecision,
normalizeSecurityPrincipal,
type SecurityPolicyDecision,
} from '@qinglong/runtime-core/security';
import {
@@ -38,6 +37,7 @@ import {
} from '@qinglong/runtime-core/task-definition-administration';
import type { AuthenticatedLocalApiRequest } from '../authentication/credentialAuthenticator';
import { strongLocalConsolePrincipal } from '../authentication/strongLocalPrincipal';
import {
LocalPresenceProofUnavailableError,
type LocalPresenceBinding,
@@ -491,18 +491,9 @@ export function createLocalApiTaskPutRoute(
}
let strongPrincipal;
try {
strongPrincipal = normalizeSecurityPrincipal(
{
subject: request.authenticated.principal.subject,
authenticationId: `local_presence:${proof.authorizationId}`,
authenticatedAtMs: proof.authenticatedAtMs,
expiresAtMs: Math.min(
proof.expiresAtMs,
request.authenticated.principal.expiresAtMs,
),
assurance: 'local_console',
},
proof.authenticatedAtMs,
strongPrincipal = strongLocalConsolePrincipal(
request.authenticated,
proof,
);
} catch {
return response(503, { code: 'authentication_unavailable' });
@@ -42,6 +42,10 @@ const TASK_START_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/tasks\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/runs$/;
const TASK_AUTHORING_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/tasks\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/authoring$/;
const TRIGGER_LIST_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/triggers$/;
const TRIGGER_READ_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/triggers\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})$/;
const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const LOCAL_CONSOLE_CONTENT_SECURITY_POLICY =
@@ -55,7 +59,8 @@ type LocalApiRouteResolution =
| 'invalid_run_event_list_query'
| 'invalid_run_step_list_query'
| 'invalid_run_log_read_query'
| 'invalid_task_list_query';
| 'invalid_task_list_query'
| 'invalid_trigger_list_query';
}>;
export interface LocalApiHttpSurfaceOptions {
@@ -393,6 +398,53 @@ function parseTaskListQuery(
});
}
function parseTriggerListQuery(
rawQuery: string | undefined,
profile: LocalApplicationProfile,
): Readonly<{
limit: number;
after?: Readonly<{ readonly triggerId: string }>;
}> {
if (rawQuery === undefined) {
return Object.freeze({ limit: profile === 'edge' ? 16 : 32 });
}
if (rawQuery.length === 0) throw new TypeError();
const values = new Map<string, string>();
for (const field of rawQuery.split('&')) {
const separator = field.indexOf('=');
if (
separator < 1 ||
separator !== field.lastIndexOf('=') ||
separator === field.length - 1
) {
throw new TypeError();
}
const name = field.slice(0, separator);
const value = field.slice(separator + 1);
if (values.has(name) || (name !== 'limit' && name !== 'after_trigger_id')) {
throw new TypeError();
}
values.set(name, value);
}
const rawLimit = values.get('limit');
const limit =
rawLimit === undefined ? (profile === 'edge' ? 16 : 32) : Number(rawLimit);
const triggerId = values.get('after_trigger_id');
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > 64 ||
(rawLimit !== undefined && String(limit) !== rawLimit) ||
(triggerId !== undefined && !TASK_ID_PATTERN.test(triggerId))
) {
throw new TypeError();
}
return Object.freeze({
limit,
...(triggerId === undefined ? {} : { after: Object.freeze({ triggerId }) }),
});
}
function parseRunAttemptLogReadQuery(
rawQuery: string | undefined,
profile: LocalApplicationProfile,
@@ -482,6 +534,14 @@ function route(
: null;
}
if (request.method === 'PUT') {
const triggerPutMatch = TRIGGER_READ_ROUTE_PATTERN.exec(path);
if (triggerPutMatch && rawQuery === undefined) {
return Object.freeze({
operationId: 'trigger.put',
projectId: triggerPutMatch[1]!,
triggerId: triggerPutMatch[2]!,
});
}
const taskPutMatch = TASK_READ_ROUTE_PATTERN.exec(path);
return taskPutMatch && rawQuery === undefined
? Object.freeze({
@@ -492,6 +552,29 @@ function route(
: null;
}
if (request.method !== 'GET') return null;
const triggerReadMatch = TRIGGER_READ_ROUTE_PATTERN.exec(path);
if (triggerReadMatch) {
return rawQuery === undefined
? Object.freeze({
operationId: 'trigger.get',
projectId: triggerReadMatch[1]!,
triggerId: triggerReadMatch[2]!,
})
: null;
}
const triggerListMatch = TRIGGER_LIST_ROUTE_PATTERN.exec(path);
if (triggerListMatch) {
try {
const input = parseTriggerListQuery(rawQuery, profile);
return Object.freeze({
operationId: 'trigger.list',
projectId: triggerListMatch[1]!,
...input,
});
} catch {
return Object.freeze({ errorCode: 'invalid_trigger_list_query' });
}
}
const runAttemptLogReadMatch = RUN_ATTEMPT_LOG_READ_ROUTE_PATTERN.exec(path);
if (runAttemptLogReadMatch) {
try {
@@ -0,0 +1,469 @@
import { createHash, randomUUID } from 'node:crypto';
import {
LocalTriggerAdministrationAuthenticationError,
LocalTriggerAdministrationAuthorizationError,
LocalTriggerAdministrationConfigurationError,
LocalTriggerAdministrationUnavailableError,
createLocalTriggerAdministrationService,
} from '@qinglong/local-admin/trigger-administration';
import {
ProjectPolicyEngine,
ProjectPolicyUnavailableError,
type ProjectPolicyRepository,
} from '@qinglong/runtime-core/project-policy';
import {
normalizeSecurityPolicyDecision,
type SecurityPolicyDecision,
} from '@qinglong/runtime-core/security';
import {
normalizeSecurityAuditRecord,
type SecurityAuditOutcome,
type SecurityAuditSink,
} from '@qinglong/runtime-core/security-audit';
import {
InvalidTriggerError,
InvalidTriggerSpecSemanticError,
TriggerConflictError,
TriggerUnavailableError,
UnsupportedTriggerSpecError,
normalizeAppendTriggerRevisionCommand,
type AppendTriggerRevisionCommand,
type TriggerRecord,
type TriggerSource,
} from '@qinglong/runtime-core/trigger';
import {
TriggerAdministrationAuthorizationFenceConflictError,
TriggerAdministrationMutationConflictError,
type TriggerAdministrationRepository,
} from '@qinglong/runtime-core/trigger-administration';
import type { AuthenticatedLocalApiRequest } from '../authentication/credentialAuthenticator';
import {
LocalPresenceProofUnavailableError,
type LocalPresenceBinding,
type LocalPresenceProofManager,
} from '../authentication/localPresenceProof';
import { strongLocalConsolePrincipal } from '../authentication/strongLocalPrincipal';
import type { LocalApiResponse } from '../transport/contract';
const BODY_KEYS = Object.freeze([
'enabled',
'expectedRevision',
'mutationId',
'occurredAtMs',
'spec',
'taskContentDigest',
'taskId',
'taskRevision',
]);
export interface LocalApiTriggerPutRequest {
readonly requestId: string;
readonly projectId: string;
readonly triggerId: string;
readonly body: unknown | null;
readonly presence: string | null;
readonly authenticated: Readonly<AuthenticatedLocalApiRequest>;
readonly signal: AbortSignal;
}
export interface LocalApiTriggerPutRoute {
handle(
request: Readonly<LocalApiTriggerPutRequest>,
): Promise<LocalApiResponse>;
}
export interface LocalApiTriggerPutRouteOptions {
readonly projectPolicy: ProjectPolicyRepository;
readonly triggers: TriggerSource;
readonly triggerAdministrationForCredential: (
fence: Readonly<AuthenticatedLocalApiRequest['credentialFence']>,
) => Promise<TriggerAdministrationRepository>;
readonly securityAudit: SecurityAuditSink;
readonly presenceProof: LocalPresenceProofManager;
readonly now?: () => number;
readonly randomUuid?: () => string;
}
function response(
statusCode: number,
body: Readonly<Record<string, unknown>>,
): LocalApiResponse {
return Object.freeze({ statusCode, body: Object.freeze(body) });
}
function canonicalJson(value: unknown): string {
if (
value === null ||
typeof value === 'boolean' ||
typeof value === 'number' ||
typeof value === 'string'
) {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
}
const record = value as Readonly<Record<string, unknown>>;
return `{${Object.keys(record)
.sort()
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
.join(',')}}`;
}
function normalizeBody(
body: unknown | null,
projectId: string,
triggerId: string,
): Readonly<AppendTriggerRevisionCommand> {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
throw new InvalidTriggerError('HTTP body must be an object');
}
const keys = Object.keys(body).sort();
if (
BODY_KEYS.some((key) => !keys.includes(key)) ||
keys.some((key) => !BODY_KEYS.includes(key))
) {
throw new InvalidTriggerError('HTTP body has an invalid shape');
}
return normalizeAppendTriggerRevisionCommand({
projectId,
triggerId,
...(body as Omit<AppendTriggerRevisionCommand, 'projectId' | 'triggerId'>),
});
}
function operationId(
command: Readonly<AppendTriggerRevisionCommand>,
): 'trigger.create' | 'trigger.update' {
return command.expectedRevision === null
? 'trigger.create'
: 'trigger.update';
}
function requestDigest(
command: Readonly<AppendTriggerRevisionCommand>,
): string {
return createHash('sha256')
.update('qinglong3.local-api-trigger-put.v1\0', 'utf8')
.update(canonicalJson(command), 'utf8')
.digest('hex');
}
function presenceBinding(
command: Readonly<AppendTriggerRevisionCommand>,
authenticated: Readonly<AuthenticatedLocalApiRequest>,
): Readonly<LocalPresenceBinding> {
if (
authenticated.principal.subject.type !== 'user' ||
authenticated.credentialFence.subjectType !== 'user'
) {
throw new LocalPresenceProofUnavailableError(
'strong User credential is required',
);
}
return Object.freeze({
requestDigest: requestDigest(command),
credentialId: authenticated.credentialFence.credentialId,
credentialVersion: authenticated.credentialFence.credentialVersion,
subjectType: 'user',
subjectId: authenticated.credentialFence.subjectId,
});
}
function timestamp(now: () => number): number {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new LocalPresenceProofUnavailableError('clock is invalid');
}
return value;
}
async function recordAudit(
audit: SecurityAuditSink,
values: {
readonly eventId: string;
readonly requestId: string;
readonly operationId: 'trigger.create' | 'trigger.update';
readonly projectId: string;
readonly authenticated: Readonly<AuthenticatedLocalApiRequest> | null;
readonly outcome: SecurityAuditOutcome;
readonly reasons: readonly string[];
readonly fence: SecurityPolicyDecision['fence'];
readonly occurredAtMs: number;
},
): Promise<boolean> {
try {
await audit.record(
normalizeSecurityAuditRecord({
eventId: values.eventId,
requestId: values.requestId,
operationId: values.operationId,
projectId: values.projectId,
subject: values.authenticated?.principal.subject ?? null,
authenticationId:
values.authenticated?.principal.authenticationId ?? null,
outcome: values.outcome,
reasons: values.reasons,
fence: values.fence,
occurredAtMs: values.occurredAtMs,
}),
);
return true;
} catch {
return false;
}
}
function summary(trigger: Readonly<TriggerRecord>) {
return Object.freeze({
triggerId: trigger.triggerId,
revision: trigger.revision,
taskId: trigger.taskId,
taskRevision: trigger.taskRevision,
taskContentDigest: trigger.taskContentDigest,
spec: trigger.spec,
enabled: trigger.enabled,
contentDigest: trigger.contentDigest,
createdAtMs: trigger.createdAtMs,
updatedAtMs: trigger.updatedAtMs,
});
}
function isCredentialFenceConflict(error: unknown): boolean {
return (
!!error &&
typeof error === 'object' &&
'code' in error &&
typeof error.code === 'string' &&
error.code.startsWith('LOCAL_SQLITE_AUTHENTICATED_')
);
}
export function createLocalApiTriggerPutRoute(
options: Readonly<LocalApiTriggerPutRouteOptions>,
): Readonly<LocalApiTriggerPutRoute> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
typeof options.projectPolicy?.resolve !== 'function' ||
typeof options.triggers?.findCurrentTrigger !== 'function' ||
typeof options.triggers?.listTriggers !== 'function' ||
typeof options.triggerAdministrationForCredential !== 'function' ||
typeof options.securityAudit?.record !== 'function' ||
typeof options.presenceProof?.issue !== 'function' ||
typeof options.presenceProof?.consume !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.randomUuid !== undefined &&
typeof options.randomUuid !== 'function')
) {
throw new TypeError('Local API Trigger put route options are invalid');
}
const now = options.now ?? Date.now;
const uuid = options.randomUuid ?? randomUUID;
const policy = new ProjectPolicyEngine(options.projectPolicy);
return Object.freeze({
async handle(request: Readonly<LocalApiTriggerPutRequest>) {
if (request.signal.aborted) {
return response(503, { code: 'request_unavailable' });
}
let command: Readonly<AppendTriggerRevisionCommand>;
try {
command = normalizeBody(
request.body,
request.projectId,
request.triggerId,
);
} catch (error) {
return error instanceof InvalidTriggerError
? response(400, { code: 'invalid_trigger' })
: response(503, { code: 'trigger_unavailable' });
}
const operation = operationId(command);
let occurredAtMs: number;
try {
occurredAtMs = timestamp(now);
} catch {
return response(503, { code: 'local_presence_unavailable' });
}
let decision: Readonly<SecurityPolicyDecision>;
try {
decision = normalizeSecurityPolicyDecision(
await policy.authorize(
request.authenticated.principal,
request.projectId,
'task.update',
),
);
} catch (error) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: request.authenticated,
outcome: 'authorization_unavailable',
reasons: ['policy_unavailable'],
fence: null,
occurredAtMs,
});
return response(503, {
code:
audited && error instanceof ProjectPolicyUnavailableError
? 'authorization_unavailable'
: 'security_audit_unavailable',
});
}
if (decision.effect !== 'allow') {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: request.authenticated,
outcome:
decision.effect === 'require_approval'
? 'approval_required'
: 'denied',
reasons: decision.reasons,
fence: decision.fence,
occurredAtMs,
});
if (!audited) {
return response(503, { code: 'security_audit_unavailable' });
}
return response(403, {
code:
decision.effect === 'require_approval'
? 'approval_required'
: 'forbidden',
});
}
let binding: Readonly<LocalPresenceBinding>;
try {
binding = presenceBinding(command, request.authenticated);
} catch {
return response(401, { code: 'strong_authentication_required' });
}
if (!request.presence) {
let challenge;
try {
challenge = options.presenceProof.issue(binding);
} catch {
return response(503, { code: 'local_presence_unavailable' });
}
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: request.authenticated,
outcome: 'approval_required',
reasons: ['local_presence_required'],
fence: decision.fence,
occurredAtMs,
});
if (!audited) {
return response(503, { code: 'security_audit_unavailable' });
}
return response(428, {
code: 'local_presence_required',
authorizationId: challenge.authorizationId,
requestDigest: challenge.requestDigest,
expiresAtMs: challenge.expiresAtMs,
proofFileName: challenge.proofFileName,
});
}
let proof;
try {
await request.authenticated.confirm();
proof = options.presenceProof.consume(request.presence, binding);
} catch {
return response(503, { code: 'authentication_unavailable' });
}
if (!proof) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: null,
outcome: 'authentication_rejected',
reasons: ['local_presence_rejected'],
fence: null,
occurredAtMs,
});
return audited
? response(401, { code: 'local_presence_rejected' })
: response(503, { code: 'security_audit_unavailable' });
}
if (request.signal.aborted) {
return response(503, { code: 'request_unavailable' });
}
let strongPrincipal;
try {
strongPrincipal = strongLocalConsolePrincipal(
request.authenticated,
proof,
);
} catch {
return response(503, { code: 'authentication_unavailable' });
}
try {
const mutations = await options.triggerAdministrationForCredential(
request.authenticated.credentialFence,
);
const service = createLocalTriggerAdministrationService(
options.projectPolicy,
mutations,
options.triggers,
options.securityAudit,
{ now },
);
const result = await service.put({
...command,
requestId: request.requestId,
principal: strongPrincipal,
});
return response(result.status === 'created' ? 201 : 200, {
status: result.status,
trigger: summary(result.trigger),
});
} catch (error) {
if (
error instanceof TriggerConflictError ||
error instanceof TriggerAdministrationMutationConflictError ||
error instanceof
TriggerAdministrationAuthorizationFenceConflictError ||
isCredentialFenceConflict(error)
) {
return response(409, { code: 'trigger_fence_rejected' });
}
if (error instanceof LocalTriggerAdministrationAuthenticationError) {
return response(401, { code: 'strong_authentication_required' });
}
if (error instanceof LocalTriggerAdministrationAuthorizationError) {
return response(403, { code: 'forbidden' });
}
if (
error instanceof InvalidTriggerError ||
error instanceof InvalidTriggerSpecSemanticError ||
error instanceof UnsupportedTriggerSpecError ||
error instanceof LocalTriggerAdministrationConfigurationError
) {
return response(400, { code: 'invalid_trigger' });
}
if (
error instanceof TriggerUnavailableError ||
error instanceof LocalTriggerAdministrationUnavailableError
) {
return response(503, { code: 'trigger_unavailable' });
}
return response(503, { code: 'trigger_unavailable' });
}
},
});
}
@@ -0,0 +1,121 @@
import {
InvalidTriggerError,
TriggerUnavailableError,
type TriggerRecord,
type TriggerSource,
} from '@qinglong/runtime-core/trigger';
import type { LocalApiResponse } from '../transport/contract';
export interface LocalApiTriggerListRequest {
readonly projectId: string;
readonly limit: number;
readonly after?: Readonly<{ readonly triggerId: string }>;
}
export interface LocalApiTriggerReadRequest {
readonly projectId: string;
readonly triggerId: string;
}
export interface LocalApiTriggerListRoute {
handle(
request: Readonly<LocalApiTriggerListRequest>,
): Promise<LocalApiResponse>;
}
export interface LocalApiTriggerReadRoute {
handle(
request: Readonly<LocalApiTriggerReadRequest>,
): Promise<LocalApiResponse>;
}
function response(
statusCode: number,
body: Readonly<Record<string, unknown>>,
): LocalApiResponse {
return Object.freeze({ statusCode, body: Object.freeze(body) });
}
function summary(trigger: Readonly<TriggerRecord>) {
return Object.freeze({
triggerId: trigger.triggerId,
revision: trigger.revision,
taskId: trigger.taskId,
taskRevision: trigger.taskRevision,
specSchema: trigger.spec.schema,
enabled: trigger.enabled,
contentDigest: trigger.contentDigest,
createdAtMs: trigger.createdAtMs,
updatedAtMs: trigger.updatedAtMs,
});
}
function detail(trigger: Readonly<TriggerRecord>) {
return Object.freeze({
...summary(trigger),
projectId: trigger.projectId,
taskContentDigest: trigger.taskContentDigest,
spec: trigger.spec,
});
}
function unavailable(error: unknown): LocalApiResponse | null {
return error instanceof InvalidTriggerError ||
error instanceof TriggerUnavailableError
? response(503, { code: 'trigger_query_unavailable' })
: null;
}
export function createLocalApiTriggerListRoute(
triggers: Pick<TriggerSource, 'listTriggers'>,
): Readonly<LocalApiTriggerListRoute> {
if (!triggers || typeof triggers.listTriggers !== 'function') {
throw new TypeError('Local API Trigger list repository is invalid');
}
return Object.freeze({
async handle(request: Readonly<LocalApiTriggerListRequest>) {
try {
const page = await triggers.listTriggers({
projectId: request.projectId,
limit: request.limit,
...(request.after ? { after: request.after } : {}),
});
return response(200, {
triggers: Object.freeze(page.triggers.map(summary)),
truncated: page.truncated,
next: page.next ?? null,
});
} catch (error) {
const mapped = unavailable(error);
if (mapped) return mapped;
throw error;
}
},
});
}
export function createLocalApiTriggerReadRoute(
triggers: Pick<TriggerSource, 'findCurrentTrigger'>,
): Readonly<LocalApiTriggerReadRoute> {
if (!triggers || typeof triggers.findCurrentTrigger !== 'function') {
throw new TypeError('Local API Trigger read repository is invalid');
}
return Object.freeze({
async handle(request: Readonly<LocalApiTriggerReadRequest>) {
try {
const trigger = await triggers.findCurrentTrigger(
request.projectId,
request.triggerId,
);
return trigger
? response(200, { trigger: detail(trigger) })
: response(404, { code: 'trigger_not_found' });
} catch (error) {
const mapped = unavailable(error);
if (mapped) return mapped;
throw error;
}
},
});
}