/** * Shared CoreMail contracts. * * Workload authority is always derived from an authenticated transport * session. Application-facing request DTOs therefore carry message or * delivery identifiers only and never caller-selected tenant, service, or * binding authority. */ export type TCoreMailSha256 = `sha256:${string}`; export type TCoreMailCapability = 'outbound' | 'inbound'; export type TCoreMailBindingState = 'active' | 'draining' | 'disabled'; export type TCoreMailCredentialState = 'current' | 'retiring'; export type TCoreMailCredentialVerifierFormat = 'argon2id-v1'; export type TCoreMailPartKind = 'text' | 'html' | 'attachment'; export type TCoreMailTransferMethod = 'PUT' | 'GET'; export type TCoreMailSubmissionState = | 'preparing' | 'uploading' | 'ready' | 'accepted' | 'queued' | 'delivering' | 'delivered' | 'deferred' | 'failed' | 'deadLettered'; export type TCoreMailInboundDeliveryState = 'pending' | 'fetching' | 'fetched' | 'acknowledged'; export type TCoreMailInboundAckOutcome = 'processed' | 'discarded'; export type TCoreMailRecipientAction = 'accept' | 'reject' | 'defer' | 'unhandled'; export type TCoreMailReconciliationState = 'applying' | 'ready' | 'failed'; export type TCoreMailWorkloadOperation = | 'coreMailPrepareOutboundSubmission' | 'coreMailPrepareOutboundPartUpload' | 'coreMailCompleteOutboundPartUpload' | 'coreMailFinalizeOutboundSubmission' | 'coreMailGetOutboundSubmission' | 'coreMailListInboundDeliveries' | 'coreMailPrepareInboundFetch' | 'coreMailCompleteInboundFetch' | 'coreMailAcknowledgeInboundDelivery'; export type TCoreMailErrorCode = | 'AUTHENTICATION_FAILED' | 'AUTHENTICATION_EXPIRED' | 'AUTHORITY_REVOKED' | 'CAPABILITY_DENIED' | 'NOT_FOUND' | 'INVALID_REQUEST' | 'INVALID_MAILBOX' | 'INVALID_SENDER' | 'INVALID_RECIPIENT' | 'INVALID_HEADER' | 'PAYLOAD_LIMIT_EXCEEDED' | 'QUOTA_EXCEEDED' | 'IDEMPOTENCY_CONFLICT' | 'STATE_CONFLICT' | 'TRANSFER_GRANT_EXPIRED' | 'TRANSFER_GRANT_REPLAYED' | 'TRANSFER_LENGTH_MISMATCH' | 'TRANSFER_DIGEST_MISMATCH' | 'TRANSFER_ENCODING_UNSUPPORTED' | 'OBJECT_INTEGRITY_CONFLICT' | 'DELIVERY_NOT_FETCHED' | 'DELIVERY_DEFERRED' | 'DELIVERY_FAILED' | 'DELIVERY_DEAD_LETTERED' | 'GATEWAY_UNAVAILABLE' | 'RECONCILIATION_FENCE_MISMATCH'; export interface ICoreMailErrorData { code: TCoreMailErrorCode; retryable: boolean; retryAfterMs?: number; } export interface ICoreMailMailbox { address: string; displayName?: string; } export interface ICoreMailEnvelope { mailFrom: string; rcptTo: string[]; } export interface ICoreMailHeader { name: string; value: string; } export interface ICoreMailContentDescriptor { partId: string; kind: TCoreMailPartKind; contentType: string; filename?: string; contentId?: string; sha256: TCoreMailSha256; lengthBytes: number; } export interface ICoreMailOutboundMessageDescriptor { sender: ICoreMailMailbox; recipients: { to: ICoreMailMailbox[]; cc?: ICoreMailMailbox[]; bcc?: ICoreMailMailbox[]; }; replyTo?: ICoreMailMailbox; subject: string; /** Ordered headers. Transport-owned MIME headers are not accepted here. */ headers?: ICoreMailHeader[]; /** Ordered body and attachment descriptors. Bytes move through bounded HTTP transfers. */ parts: ICoreMailContentDescriptor[]; } export interface ICoreMailTransferGrant { grantId: string; method: TCoreMailTransferMethod; /** Same-origin path. Callers use the authenticated CoreMail or gateway endpoint they already hold. */ path: string; /** One-time bearer capability. It must never be logged or persisted by a consumer. */ bearerToken: string; sha256: TCoreMailSha256; lengthBytes: number; contentType: string; issuedAt: number; expiresAt: number; } export interface ICoreMailUploadGrant extends ICoreMailTransferGrant { method: 'PUT'; } export interface ICoreMailDownloadGrant extends ICoreMailTransferGrant { method: 'GET'; } export interface ICoreMailPartStatus { partId: string; state: 'missing' | 'uploading' | 'complete' | 'failed'; sha256: TCoreMailSha256; lengthBytes: number; } export interface ICoreMailSubmission { submissionId: string; idempotencyKey: string; submissionDigest: TCoreMailSha256; state: TCoreMailSubmissionState; parts: ICoreMailPartStatus[]; transportMessageId?: string; attempts: number; nextAttemptAt?: number; error?: ICoreMailErrorData; acceptedAt?: number; deliveredAt?: number; terminalAt?: number; createdAt: number; updatedAt: number; } export interface ICoreMailInboundDelivery { deliveryId: string; transportDeliveryId: string; state: TCoreMailInboundDeliveryState; envelope: ICoreMailEnvelope; rawMime: { sha256: TCoreMailSha256; lengthBytes: number; contentType: 'message/rfc822'; }; messageId?: string; subject?: string; receivedAt: number; updatedAt: number; acknowledgedAt?: number; acknowledgedOutcome?: TCoreMailInboundAckOutcome; } export interface ICoreMailInboundDeliveryPage { deliveries: ICoreMailInboundDelivery[]; nextCursor?: string; } export interface ICoreMailBindingCredentialVerifier { credentialId: string; version: number; state: TCoreMailCredentialState; /** Versioned verifier contract. CoreMail currently accepts only argon2id-v1. */ format: TCoreMailCredentialVerifierFormat; /** Password-verifier string only. Plaintext credential material is never part of desired state. */ verificationHash: string; acceptUntil?: number; } export interface ICoreMailBindingDesiredState { schemaVersion: 2; bindingId: string; serviceId: string; tenantId: string; revision: number; state: TCoreMailBindingState; capabilities: TCoreMailCapability[]; credentials: ICoreMailBindingCredentialVerifier[]; allowedSenders: string[]; inboundRecipients: string[]; defaultSender?: string; limits: { messagesPerMinute: number; messagesPerDay: number; maxPendingInbound: number; }; } export interface ICoreMailGatewayDesiredState { endpointUrl: string; /** Canonical CoreMail HTTPS origin authorized for path-only transfer grants. */ coreMailTransferOrigin: string; credentialId: string; credentialVersion: number; /** Key in CoreMail's resolved runtime secret material, never a plaintext value. */ credentialSecretKey: string; } /** * Bootstrap authority installed in CoreMail before Coreflow can reconcile * ordinary desired state. The verifier payload is safe to deliver as runtime * configuration; the matching plaintext is delivered only to Coreflow. */ export interface ICoreMailControlBootstrap { schemaVersion: 1; coreMailServiceId: string; credentials: ICoreMailBindingCredentialVerifier[]; } /** * dcrouter-owned desired state for one authenticated CoreMail gateway peer. * transferOrigin is authoritative control-plane data, never peer supplied. */ export interface ICoreMailGatewayPeerDesiredState { schemaVersion: 1; coreMailServiceId: string; transferOrigin: string; credentials: ICoreMailBindingCredentialVerifier[]; } export interface ICoreMailRuntimeKeyReference { keyId: string; version: number; state: TCoreMailCredentialState; /** Key in CoreMail's resolved runtime secret material, never a plaintext value. */ secretKey: string; acceptUntil?: number; } export interface ICoreMailDesiredState { schemaVersion: 2; configEpoch: number; bindings: ICoreMailBindingDesiredState[]; gateway: ICoreMailGatewayDesiredState; cursorKeys: ICoreMailRuntimeKeyReference[]; } export interface ICoreMailReplicaIdentity { taskId: string; serviceId: string; rolloutId: string; rolloutGeneration: number; imageDigest: TCoreMailSha256; } export interface ICoreMailBindingReconciliationStatus { bindingId: string; revision: number; state: TCoreMailBindingState; pendingInboundCount: number; activeSessionsByCredential: Array<{ credentialId: string; version: number; count: number; }>; } export interface ICoreMailReconciliationStatus { replica: ICoreMailReplicaIdentity; state: TCoreMailReconciliationState; appliedConfigEpoch: number; appliedDesiredStateDigest: TCoreMailSha256; bindings: ICoreMailBindingReconciliationStatus[]; updatedAt: number; errorCode?: TCoreMailErrorCode; } export interface ICoreMailRecipientResolution { recipient: string; action: TCoreMailRecipientAction; /** Opaque, short-lived handle returned only for accepted recipients. */ routingHandle?: string; smtpCode?: number; message?: string; } export interface ICoreMailGatewayMessageDescriptor { envelope: ICoreMailEnvelope; rawMime: { sha256: TCoreMailSha256; lengthBytes: number; contentType: 'message/rfc822'; }; } export interface ICoreMailGatewayOutboundStatus { transportMessageId: string; state: Extract< TCoreMailSubmissionState, 'accepted' | 'queued' | 'delivering' | 'delivered' | 'deferred' | 'failed' | 'deadLettered' >; attempts: number; nextAttemptAt?: number; error?: ICoreMailErrorData; smtpCode?: number; deliveredAt?: number; terminalAt?: number; updatedAt: number; } export const coreMailLimits = Object.freeze({ controlMessageBytes: 64 * 1024, desiredStateBytes: 8 * 1024 * 1024, textPartBytes: 1 * 1024 * 1024, htmlPartBytes: 2 * 1024 * 1024, attachmentCount: 16, attachmentBytes: 10 * 1024 * 1024, aggregateAttachmentBytes: 17 * 1024 * 1024, mimeFramingBytes: 512 * 1024, serializedMimeBytes: 30 * 1024 * 1024, recipientCount: 100, inboundPageSize: 100, inboundPageBytes: 56 * 1024, cursorBytes: 1_024, cursorMinimumDecodedBytes: 32, routingHandleTtlMs: 5 * 60 * 1000, transferGrantTtlMs: 5 * 60 * 1000, transferHeaderTimeoutMs: 10 * 1000, transferIdleTimeoutMs: 15 * 1000, transferOverallTimeoutMs: 2 * 60 * 1000, } as const); export const coreMailTransferTokenPolicy = Object.freeze({ format: 'base64url-256' as const, decodedBytes: 32, encodedCharacters: 43, }); export const coreMailWorkloadOperationPolicy = Object.freeze({ active: Object.freeze({ outbound: Object.freeze([ 'coreMailPrepareOutboundSubmission', 'coreMailPrepareOutboundPartUpload', 'coreMailCompleteOutboundPartUpload', 'coreMailFinalizeOutboundSubmission', 'coreMailGetOutboundSubmission', ] satisfies TCoreMailWorkloadOperation[]), inbound: Object.freeze([ 'coreMailListInboundDeliveries', 'coreMailPrepareInboundFetch', 'coreMailCompleteInboundFetch', 'coreMailAcknowledgeInboundDelivery', ] satisfies TCoreMailWorkloadOperation[]), }), draining: Object.freeze({ outbound: Object.freeze([ 'coreMailGetOutboundSubmission', ] satisfies TCoreMailWorkloadOperation[]), inbound: Object.freeze([ 'coreMailListInboundDeliveries', 'coreMailPrepareInboundFetch', 'coreMailCompleteInboundFetch', 'coreMailAcknowledgeInboundDelivery', ] satisfies TCoreMailWorkloadOperation[]), }), disabled: Object.freeze({ outbound: Object.freeze([] satisfies TCoreMailWorkloadOperation[]), inbound: Object.freeze([] satisfies TCoreMailWorkloadOperation[]), }), }); export const coreMailRetentionPolicy = Object.freeze({ terminalOutboundMs: 30 * 24 * 60 * 60 * 1000, acknowledgedInboundMs: 30 * 24 * 60 * 60 * 1000, idempotencyReceiptMs: 30 * 24 * 60 * 60 * 1000, expiredCapabilityMs: 24 * 60 * 60 * 1000, pendingInboundAgePurge: false as const, }); export const coreMailQuotaPolicy = Object.freeze({ windows: 'fixed-utc-minute-and-day' as const, outboundUnit: 'first-durable-idempotency-insert' as const, outboundReplayConsumesUnit: false as const, pendingInboundStates: ['pending', 'fetching', 'fetched'] as const, inboundAcknowledgementReleasesUnit: true as const, }); export const coreMailTransferProtocol = Object.freeze({ pathPrefix: '/transfers/', authorizationScheme: 'Bearer', putSuccessStatus: 204, getSuccessStatus: 200, requireContentLength: true, requireContentType: true, integritySource: 'grant-metadata-and-completion' as const, }); export const coreMailCredentialVerifierPolicy = Object.freeze({ format: 'argon2id-v1' as const, version: 19, memoryCost: 65_536, timeCost: 3, parallelism: 1, saltLengthBytes: 16, hashLengthBytes: 32, } as const); export const coreMailRuntimeKeys = Object.freeze({ controlBootstrap: 'COREMAIL_CONTROL_BOOTSTRAP', controlCredentialSecret: 'COREMAIL_CONTROL_CREDENTIAL_SECRET', gatewayCredentialSecret: 'COREMAIL_GATEWAY_CREDENTIAL', } as const);