// Vendored verbatim from @kody/youtube src/internal (keep in sync; no kody: dependency so this public package stays self-contained). /** * Crash-safe YouTube resumable upload engine. * * Invariants (see AGENTS.md "Upload reliability"): * - Exactly one session-create POST per job. A job row is persisted BEFORE the * POST, so a lost/ambiguous create response leaves `session_pending`, which * is never retried automatically (fail closed: needs_reconciliation). * - The session URL is a capability: sealed by the SessionVault, never logged, * returned, or stored in plaintext. Errors pass through `redactText`. * - Every retry first asks the SAME session for its acknowledged offset * (`PUT bytes * /total`). A lost final response is reconciled by that query, * never by a new insert. Expired/unknown sessions stop for reconciliation. * - Checkpoint (CAS on version) after every acknowledgement. * - Channel and metadata fingerprint are immutable for a job. * - Source bytes are read with validated Range responses into one bounded * chunk buffer; an origin that ignores Range is refused (no whole-file cache). * - Every response body we do not need (308s, retries) is cancelled. * * No `kody:runtime` import: callers inject the credentialed fetch, source fetch, * store, vault, and clock so tests use synthetic origins only. */ import { Sha256 } from './sha256.ts' import { type SessionVault, TERMINAL_STATES, type SourceIdentity, type UploadJobRecord, type UploadJobState, type UploadJobStore, } from './upload-state.ts' export type FetchLike = (input: string, init?: RequestInit) => Promise export type EngineDeps = { /** Credentialed fetch for googleapis.com (OAuth placed by Kody). */ ytFetch: FetchLike /** Plain fetch for the media source (may carry {{secret:…}} header placeholders). */ sourceFetch: FetchLike store: UploadJobStore vault: SessionVault now?: () => number sleep?: (ms: number) => Promise random?: () => number /** Unique per process/invocation; used for the job lease. */ leaseOwner?: string log?: (event: Record) => void } export type EngineLimits = { /** Stop (state paused) after this much wall time in one invocation. Default: unlimited. */ maxRunMs?: number /** Retries per offset for retryable failures before pausing. Default 6. */ maxRetries?: number /** Backoff base/cap in ms (full jitter). Defaults 1000 / 60000. */ backoffBaseMs?: number backoffMaxMs?: number /** Job lease duration; renewed on every checkpoint. Default 5 minutes. */ leaseMs?: number /** Consecutive no-progress acknowledgements tolerated. Default 4. */ maxStalls?: number } export const UPLOAD_URL = 'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status' export const CHUNK_MULTIPLE = 256 * 1024 /** 3 MiB default (12 x 256 KiB). */ export const DEFAULT_CHUNK_BYTES = 12 * CHUNK_MULTIPLE /** * Hard cap enforced by the engine itself (not only by validation or docs). Since Kody 506c4e15 with * @kodycodes/cli >= 3.33.1, local-execute credential fetch streams ArrayBuffer bodies of any size; older * CLIs and the JSON hop still base64 into a 5 MiB envelope. The runtime exposes no capability marker, so * the package keeps a size that is safe on both. Raising it is a deliberate package release, not a doc change. */ export const MAX_SAFE_CHUNK_BYTES = 12 * CHUNK_MULTIPLE export class UploadEngineError extends Error { code: string jobId?: string state?: UploadJobState retryable: boolean constructor(code: string, message: string, extra: { jobId?: string; state?: UploadJobState; retryable?: boolean } = {}) { super(redactText(message)) this.name = 'UploadEngineError' this.code = code this.jobId = extra.jobId this.state = extra.state this.retryable = extra.retryable ?? false } } const REDACTIONS: RegExp[] = [ /https?:\/\/[^\s"'<>]*(?:upload_id|upload_protocol|uploadType=resumable)[^\s"'<>]*/gi, /\b(upload_id|access_token|refresh_token|id_token|client_secret|key|sig|signature|token|X-Amz-Signature|X-Amz-Credential)=([^&\s"']+)/gi, /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi, /ya29\.[A-Za-z0-9._-]+/g, /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+/g, /\{\{(?:secret|integration-token)[^}]*\}\}/g, /sv1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, ] /** Any remaining URL: keep only scheme + host (paths and queries of temporary links are capabilities). */ const ANY_URL = /\b(https?):\/\/([^\s"'<>/?#@]*@)?([A-Za-z0-9.-]+)(?::\d+)?[^\s"'<>]*/gi /** Strip session URLs, tokens, signed-URL params, sealed blobs, and URL paths/queries; cap length. */ export function redactText(text: string, max = 400): string { let out = String(text) for (const re of REDACTIONS) out = out.replace(re, (m, name) => (typeof name === 'string' && m.includes('=') ? `${name}=[redacted]` : '[redacted]')) out = out.replace(ANY_URL, (_m, scheme: string, _userinfo: string | undefined, host: string) => `${scheme}://${host}/[redacted]`) return out.length > max ? out.slice(0, max) + '…' : out } /** A resumable session Location must be https on a googleapis.com host, with no userinfo. */ /** * Classify a thrown transport error (Kody local-execute transport contract, kody-hq/kody#5025): * `AbortError` / `KodyGatewayError { code, status?, mayHaveReachedOrigin }`. Only explicit fields are * trusted; an error without them (older runtime, plain Error) stays "ambiguous", never "not sent". */ const DEFINITE_GATEWAY_CODES = new Set([ 'payload_too_large', 'host_not_allowed', 'insecure_transport', 'invalid_request', 'stream_host_missing', 'credential_denied', 'credential_unbound', 'credential_not_found', 'credential_ambiguous', 'credential_required', ]) export type TransportFailure = { aborted: boolean; gatewayCode: string | null; definite: boolean; notSent: boolean } export function classifyTransportError(error: unknown): TransportFailure { const e = error as { name?: unknown; code?: unknown; mayHaveReachedOrigin?: unknown } | null const name = typeof e?.name === 'string' ? e.name : '' const code = name === 'KodyGatewayError' && typeof e?.code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(e.code) ? e.code : null return { aborted: name === 'AbortError', gatewayCode: code, definite: code !== null && DEFINITE_GATEWAY_CODES.has(code), notSent: e?.mayHaveReachedOrigin === false, } } export function isTrustedSessionUrl(value: string | null): boolean { if (!value) return false let u: URL try { u = new URL(value) } catch { return false } const host = u.hostname.toLowerCase() return u.protocol === 'https:' && !u.username && !u.password && !u.port && (host === 'googleapis.com' || host.endsWith('.googleapis.com')) } // ---------- pure helpers ---------- /** Parse `Range: bytes=0-N` from a 308. Returns the next offset (N+1), 0 when absent, or null when malformed. */ export function parseAckRange(header: string | null): number | null { if (header === null || header === '') return 0 const m = /^bytes=0-(\d+)$/i.exec(header.trim()) return m ? Number(m[1]) + 1 : null } export function parseContentRange(header: string | null): { start: number; end: number; total: number | null } | null { if (!header) return null const m = /^bytes (\d+)-(\d+)\/(\d+|\*)$/i.exec(header.trim()) if (!m) return null const start = Number(m[1]) const end = Number(m[2]) if (end < start) return null return { start, end, total: m[3] === '*' ? null : Number(m[3]) } } function canonical(value: unknown): string { if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']' if (value && typeof value === 'object') { return '{' + Object.keys(value as object).sort().filter((k) => (value as any)[k] !== undefined).map((k) => JSON.stringify(k) + ':' + canonical((value as any)[k])).join(',') + '}' } return JSON.stringify(value) } export async function sha256Hex(text: string): Promise { const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) return Array.from(new Uint8Array(d), (b) => b.toString(16).padStart(2, '0')).join('') } export async function metadataFingerprint(channelId: string, body: unknown): Promise { return await sha256Hex('yt-meta:v1:' + channelId + ':' + canonical(body)) } export function backoffDelay(attempt: number, baseMs: number, maxMs: number, random: () => number): number { const cap = Math.min(maxMs, baseMs * 2 ** Math.max(0, attempt - 1)) return Math.floor(random() * cap) } async function discard(response: Response | null | undefined) { try { await response?.body?.cancel() } catch {} } /** Read exactly `expected` bytes from a body into one buffer; refuse overflow or short reads. */ export async function readExact(response: Response, expected: number): Promise { const out = new Uint8Array(expected) if (!response.body) { if (expected === 0) return out throw new UploadEngineError('source_short_read', `Source returned no body; expected ${expected} bytes.`, { retryable: true }) } const reader = response.body.getReader() let n = 0 try { for (;;) { const { done, value } = await reader.read() if (done) break if (n + value.byteLength > expected) { throw new UploadEngineError('source_overflow', `Source sent more than the ${expected} bytes requested; refusing to buffer it.`) } out.set(value, n) n += value.byteLength } } catch (error) { try { await reader.cancel() } catch {} throw error } finally { try { reader.releaseLock() } catch {} } if (n !== expected) throw new UploadEngineError('source_short_read', `Source range returned ${n} of ${expected} bytes.`, { retryable: true }) return out } /** A strong ETag (not `W/`) identifies exact bytes; a weak one only "equivalent" content. */ export function isStrongEtag(etag: string | null | undefined): etag is string { return typeof etag === 'string' && etag.length > 0 && !/^W\//i.test(etag) } /** * How the job can prove every range came from the same immutable source: * - `strong_etag` / `last_modified`: an origin validator recorded at the probe and re-checked on every range; * - `expected_sha256`: no usable validator, but a caller digest must match the bytes sent (else fail closed); * - `none`: nothing proves it; refused before any upload. */ export function sourceIdentityLevel(source: SourceIdentity): 'strong_etag' | 'last_modified' | 'expected_sha256' | 'none' { if (isStrongEtag(source.etag)) return 'strong_etag' if (source.lastModified) return 'last_modified' if (source.expectedSha256) return 'expected_sha256' return 'none' } /** * Check a response's validators against the job's recorded identity. Returns null when identity holds, * or the failure. A validator recorded at the probe that is MISSING later fails closed unless another * recorded validator (a strong ETag) was verified on this same response. */ export function checkSourceIdentity(source: SourceIdentity, etag: string | null, lastModified: string | null): { code: 'source_changed' | 'source_identity_unverifiable'; reason: string } | null { let verified = false if (source.etag) { if (!etag) { if (isStrongEtag(source.etag)) return { code: 'source_changed', reason: 'the origin stopped sending the ETag recorded at the start' } } else if (etag !== source.etag) { return { code: 'source_changed', reason: 'the ETag changed' } } else if (isStrongEtag(source.etag)) { verified = true } } if (source.lastModified) { if (!lastModified) { if (!verified) return { code: 'source_changed', reason: 'the origin stopped sending the Last-Modified recorded at the start' } } else if (lastModified !== source.lastModified) { return { code: 'source_changed', reason: 'Last-Modified changed' } } else { verified = true } } if (!verified && !source.expectedSha256) return { code: 'source_identity_unverifiable', reason: 'no strong ETag, Last-Modified, or expectedSha256 proves the bytes are from one unchanged file' } return null } /** * Idempotency key for a caller that did not pass one. Anchored ONLY on immutable content identity * (caller digest or strong ETag) plus channel, metadata, and size. Never derived from the source URL. * Throws when no such anchor exists, so an unrelated same-size, same-metadata file can never rejoin. */ export async function deriveUploadKey(scope: string[], channelId: string, metadata: unknown, source: SourceIdentity): Promise { const anchor = source.expectedSha256 ? `sha256:${source.expectedSha256}` : isStrongEtag(source.etag) ? `etag:${source.etag}` : null if (!anchor) { throw new UploadEngineError( 'upload_key_required', 'Cannot derive a safe idempotency key: the media source has no strong ETag and no expectedSha256 was given. Pass expectedSha256 (lowercase hex SHA-256 of the whole file) or an explicit uploadKey that is unique to this video. Nothing was uploaded.', ) } return 'auto2:' + (await sha256Hex(['v2', ...scope, channelId, canonical(metadata), String(source.bytes), anchor].join('|'))).slice(0, 40) } /** True when an origin validator (strong ETag or Last-Modified) is checked on every range, so a re-read equals what was sent. */ function validatorIdentity(source: SourceIdentity): boolean { const level = sourceIdentityLevel(source) return level === 'strong_etag' || level === 'last_modified' } /** Explain how strongly the uploaded bytes were verified. */ export function integrityOf(r: Pick): { level: string; detail: string } { const expected = r.source.expectedSha256 const h = r.hash.status if (h === 'tracking') return { level: 'pending', detail: 'Upload not finished.' } if (expected) { if (h === 'matched') return { level: 'expected_sha256_verified', detail: 'SHA-256 of every byte sent equals the caller-supplied expectedSha256 (end-to-end digest).' } if (h === 'mismatch') return { level: 'expected_sha256_mismatch', detail: 'Bytes sent do NOT match expectedSha256. Never treated as success.' } return { level: 'expected_sha256_unverified', detail: 'expectedSha256 was given but the sent bytes could not all be hashed. Never treated as success.' } } if (h === 'computed') return { level: 'local_sha256_origin_validated', detail: 'Locally hashed every byte sent, and every range carried the origin validator recorded at the start. No caller digest to compare against.' } return { level: 'origin_validated_hash_incomplete', detail: 'Every range carried the origin validator recorded at the start, but not all sent bytes were hashed locally (for example after an acknowledgement from an earlier run). No caller digest.' } } // ---------- source ---------- /** Probe size and identity with `Range: bytes=0-0`. Never reads an unbounded body. */ export async function probeSource( sourceFetch: FetchLike, url: string, headers: Record | undefined, chunkSizeBytes: number, expectedSha256: string | null, ): Promise { const h = new Headers(headers ?? {}) h.set('Range', 'bytes=0-0') let res: Response try { res = await sourceFetch(url, { method: 'GET', headers: h }) } catch (error) { throw new UploadEngineError('source_unreachable', `Could not reach the media source: ${(error as Error)?.message ?? error}`, { retryable: true }) } const etag = res.headers.get('etag') const lastModified = res.headers.get('last-modified') if (res.status === 206) { const cr = parseContentRange(res.headers.get('content-range')) await discard(res) if (!cr || cr.start !== 0 || cr.end !== 0 || !cr.total) throw new UploadEngineError('source_bad_content_range', 'Media source answered the size probe with a malformed Content-Range.') return { bytes: cr.total, etag, lastModified, expectedSha256, rangeSupported: true } } if (res.status === 200) { const len = Number(res.headers.get('content-length')) await discard(res) if (!Number.isSafeInteger(len) || len <= 0) throw new UploadEngineError('source_no_size', 'Media source ignored Range and did not report Content-Length.') if (len > chunkSizeBytes) { throw new UploadEngineError( 'source_range_ignored', `Media source ignored Range for a ${len}-byte file. Refusing to buffer the whole file; host it on an origin that honors Range (R2/S3/Dropbox temporary link).`, ) } return { bytes: len, etag, lastModified, expectedSha256, rangeSupported: false } } await discard(res) throw new UploadEngineError('source_http', `Media source size probe returned HTTP ${res.status}.`, { retryable: res.status === 429 || res.status >= 500 }) } async function fetchSourceRange( sourceFetch: FetchLike, url: string, headers: Record | undefined, source: SourceIdentity, start: number, end: number, ): Promise { const h = new Headers(headers ?? {}) h.set('Range', `bytes=${start}-${end}`) let res: Response try { res = await sourceFetch(url, { method: 'GET', headers: h }) } catch (error) { throw new UploadEngineError('source_unreachable', `Media source request failed at ${start}-${end}: ${(error as Error)?.message ?? error}`, { retryable: true }) } const expected = end - start + 1 if (res.status !== 206 && res.status !== 200) { await discard(res) throw new UploadEngineError('source_http', `Media source range ${start}-${end} returned HTTP ${res.status}.`, { retryable: res.status === 429 || res.status >= 500 }) } const idFail = checkSourceIdentity(source, res.headers.get('etag'), res.headers.get('last-modified')) if (idFail) { await discard(res) throw new UploadEngineError(idFail.code, `Media source range ${start}-${end}: ${idFail.reason}; refusing to mix bytes from two files.`) } if (res.status === 206) { const cr = parseContentRange(res.headers.get('content-range')) if (!cr || cr.start !== start || cr.end !== end || cr.total !== source.bytes) { await discard(res) throw new UploadEngineError('source_bad_content_range', `Media source returned Content-Range for the wrong bytes at ${start}-${end}.`) } const len = res.headers.get('content-length') if (len !== null && Number(len) !== expected) { await discard(res) throw new UploadEngineError('source_bad_length', `Media source Content-Length ${len} does not match the ${expected}-byte range.`) } return await readExact(res, expected) } if (res.status === 200) { const whole = start === 0 && end === source.bytes - 1 const len = Number(res.headers.get('content-length')) if (!whole || len !== source.bytes) { await discard(res) throw new UploadEngineError('source_range_ignored', `Media source ignored Range at ${start}-${end}; refusing to buffer the whole file.`) } return await readExact(res, expected) } await discard(res) throw new UploadEngineError('source_http', `Media source range ${start}-${end} returned HTTP ${res.status}.`, { retryable: res.status === 429 || res.status >= 500 }) } // ---------- engine ---------- export type StartJobInput = { uploadKey: string channelId: string metadata: Record sourceUrl: string sourceHeaders?: Record chunkSizeBytes: number expectedSha256?: string | null /** Pre-probed identity (dry-run reuse); probed again when omitted. */ source?: SourceIdentity } export type ResumeJobInput = { jobId: string; sourceUrl: string; sourceHeaders?: Record } export type UploadStatus = { jobId: string uploadKey: string state: UploadJobState channelId: string metadataFingerprint: string bytes: number ackOffset: number percent: number chunkSizeBytes: number sessionDurable: boolean hasSession: boolean videoId: string | null url: string | null hash: { status: string; sha256: string | null; expected: string | null } /** How strongly the sent bytes were verified; see integrityOf. */ integrity: { level: string; detail: string } sourceIdentity: 'strong_etag' | 'last_modified' | 'expected_sha256' | 'none' processing: UploadJobRecord['processing'] reconciliation: UploadJobRecord['reconciliation'] lastError: UploadJobRecord['lastError'] attempts: number createdAt: string updatedAt: string next: string } /** Public, secret-free view of a job row. Never includes the session or source URL. */ export function toStatus(r: UploadJobRecord): UploadStatus { const next: Record = { session_pending: 'Session-create outcome unknown. Check the channel for an orphan upload, then reconcileUpload. Not retried automatically.', uploading: 'Call resumeUpload with the same jobId and source URL to continue.', paused: 'Call resumeUpload with the same jobId and source URL to continue.', uploaded: 'Upload accepted. Call getUploadStatus with verify: true until processing is confirmed.', completed: 'Done: upload finished and processing verified.', needs_reconciliation: 'Stopped fail-closed. A person must inspect the channel and call reconcileUpload. No automatic new session, delete, or privacy change.', abandoned: 'Abandoned by reconciliation. Nothing on YouTube was deleted or changed.', failed: 'Failed before any session existed; safe to start a new upload.', } return { jobId: r.jobId, uploadKey: r.uploadKey, state: r.state, channelId: r.channelId, metadataFingerprint: r.metadataFingerprint, bytes: r.source.bytes, ackOffset: r.ackOffset, percent: r.source.bytes ? Math.floor((r.ackOffset / r.source.bytes) * 1000) / 10 : 0, chunkSizeBytes: r.chunkSizeBytes, sessionDurable: r.sessionDurable, hasSession: Boolean(r.sealedSession), videoId: r.videoId, url: r.videoId ? `https://www.youtube.com/watch?v=${r.videoId}` : null, hash: { status: r.hash.status, sha256: r.hash.sha256, expected: r.source.expectedSha256 }, integrity: integrityOf(r), sourceIdentity: sourceIdentityLevel(r.source), processing: r.processing, reconciliation: r.reconciliation, lastError: r.lastError, attempts: r.attempts, createdAt: r.createdAt, updatedAt: r.updatedAt, next: next[r.state], } } function aadFor(r: Pick): string { return `${r.jobId}|${r.channelId}|${r.metadataFingerprint}` } function randomId(): string { const b = crypto.getRandomValues(new Uint8Array(12)) return 'ytu_' + Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('') } type QueryResult = | { kind: 'progress'; next: number } | { kind: 'complete'; videoId: string; data: Record } | { kind: 'expired'; status: number } | { kind: 'auth'; status: number } | { kind: 'retry'; status: number | null; message: string } | { kind: 'fatal'; status: number; message: string } /** Transport abort or a definite Kody refusal: stop paused, never retry in this run. */ | { kind: 'halt'; code: string } export function createUploadEngine(deps: EngineDeps, limits: EngineLimits = {}) { const now = deps.now ?? (() => Date.now()) const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))) const random = deps.random ?? Math.random const leaseOwner = deps.leaseOwner ?? randomId() const maxRetries = limits.maxRetries ?? 6 const baseMs = limits.backoffBaseMs ?? 1000 const capMs = limits.backoffMaxMs ?? 60_000 const leaseMs = limits.leaseMs ?? 5 * 60_000 const maxStalls = limits.maxStalls ?? 4 const log = (e: Record) => deps.log?.(e) const iso = () => new Date(now()).toISOString() async function save(r: UploadJobRecord, patch: Partial): Promise { const next: UploadJobRecord = { ...r, ...patch, updatedAt: iso() } if (next.leaseOwner === leaseOwner) next.leaseExpiresAt = now() + leaseMs const saved = await deps.store.update(next, r.version) if (!saved) throw new UploadEngineError('job_conflict', 'Another worker changed this upload job; stopping so two workers never write the same session.', { jobId: r.jobId, state: r.state, retryable: true }) return saved } async function acquire(r: UploadJobRecord): Promise { if (r.leaseOwner && r.leaseOwner !== leaseOwner && (r.leaseExpiresAt ?? 0) > now()) { throw new UploadEngineError('job_busy', 'This upload job is being worked on by another invocation; wait for its lease to expire or check getUploadStatus.', { jobId: r.jobId, state: r.state, retryable: true }) } return await save(r, { leaseOwner }) } async function release(r: UploadJobRecord, patch: Partial = {}): Promise { return await save(r, { ...patch, leaseOwner: null, leaseExpiresAt: null }) } async function stop(r: UploadJobRecord, state: UploadJobState, code: string, message: string): Promise { const at = iso() const patch: Partial = { state, lastError: { code, message: redactText(message), at } } if (state === 'needs_reconciliation') patch.reconciliation = { reason: code, detail: redactText(message), at } log({ event: 'upload_stop', jobId: r.jobId, state, code }) return await release(r, patch) } /** Ask the same session what it has. Disposes bodies we do not need. */ async function querySession(sessionUrl: string, total: number): Promise { let res: Response try { res = await deps.ytFetch(sessionUrl, { method: 'PUT', redirect: 'manual', headers: { 'content-range': `bytes */${total}`, 'x-kody-secret-resolution': 'headers-only' }, }) } catch (error) { const t = classifyTransportError(error) if (t.aborted || t.definite) return { kind: 'halt', code: t.aborted ? 'aborted' : `gateway_${t.gatewayCode}` } return { kind: 'retry', status: null, message: redactText(String((error as Error)?.message ?? error)) } } return await classify(res) } async function classify(res: Response): Promise { if (res.status === 308) { const next = parseAckRange(res.headers.get('range')) await discard(res) if (next === null) return { kind: 'retry', status: 308, message: 'YouTube returned a malformed Range header.' } return { kind: 'progress', next } } if (res.status === 200 || res.status === 201) { let data: Record | null = null try { data = (await res.json()) as Record } catch { data = null } if (data && typeof data.id === 'string' && data.id) return { kind: 'complete', videoId: data.id, data } // Finished but the body was lost or unreadable: the same session answers again on a status query. return { kind: 'retry', status: res.status, message: 'Upload finished but the response body was unreadable.' } } const text = await res.text().catch(() => '') if (res.status === 404 || res.status === 410) return { kind: 'expired', status: res.status } if (res.status === 401) return { kind: 'auth', status: 401 } if (res.status === 408 || res.status === 429 || res.status >= 500) return { kind: 'retry', status: res.status, message: redactText(text, 200) } return { kind: 'fatal', status: res.status, message: redactText(text, 300) } } async function finishUploaded(r: UploadJobRecord, videoId: string, hasher: Sha256 | null, data: Record): Promise { let hash = r.hash if (hasher && r.hash.status === 'tracking' && hasher.bytesHashed === r.source.bytes) { const sha = hasher.digestHex() const expected = r.source.expectedSha256 hash = { status: expected ? (expected === sha ? 'matched' : 'mismatch') : 'computed', state: null, sha256: sha } } else if (r.hash.status === 'tracking') { hash = { status: 'unverifiable', state: null, sha256: null } } const returnedChannel = typeof data?.snippet?.channelId === 'string' ? data.snippet.channelId : null await deps.vault.forget(r.jobId) let next = await save(r, { state: 'uploaded', videoId, ackOffset: r.source.bytes, hash, sealedSession: null }) if (returnedChannel && returnedChannel !== r.channelId) { return await stop(next, 'needs_reconciliation', 'channel_mismatch', `YouTube created video ${videoId} on a different channel than the job's immutable channel.`) } if (hash.status === 'mismatch') { return await stop(next, 'needs_reconciliation', 'source_hash_mismatch', `Uploaded bytes hash ${hash.sha256} does not match expectedSha256. Video ${videoId} was not changed or deleted.`) } if (r.source.expectedSha256 && hash.status !== 'matched') { return await stop(next, 'needs_reconciliation', 'source_hash_unverified', `expectedSha256 was given but not every byte sent could be hashed, so video ${videoId} is not verified. Nothing was changed or deleted.`) } log({ event: 'upload_uploaded', jobId: r.jobId, videoId }) return await release(next) } /** Drive one job until completion, a bounded stop, or the run budget. */ async function drive(start: UploadJobRecord, sourceUrl: string, sourceHeaders: Record | undefined, opts: { queryFirst: boolean }): Promise { let r = start const deadline = limits.maxRunMs ? now() + limits.maxRunMs : Infinity const sessionUrl = r.sealedSession ? await deps.vault.open(r.jobId, aadFor(r), r.sealedSession) : null if (!sessionUrl) { return await stop(r, 'needs_reconciliation', 'session_unavailable', r.sessionDurable ? 'The sealed session could not be opened (wrong signer credential or tampered row). Not creating a new session automatically.' : 'The resumable session was held only in memory and was lost when the process stopped. Not creating a new session automatically.') } if (!isSafeChunk(r.chunkSizeBytes)) { return await stop(r, 'paused', 'chunk_too_large', `This job's chunk size ${r.chunkSizeBytes} exceeds the package's ${MAX_SAFE_CHUNK_BYTES}-byte chunk cap.`) } const total = r.source.bytes let hasher: Sha256 | null = r.hash.status === 'tracking' && r.hash.state ? new Sha256(r.hash.state) : null if (hasher && hasher.bytesHashed !== r.ackOffset) { hasher = null r = await save(r, { hash: { status: 'unverifiable', state: null, sha256: null } }) } let retries = 0 let stalls = 0 let needQuery = opts.queryFirst /** Last chunk sent, so a status-query acknowledgement can still feed the hash. */ let pending: { start: number; bytes: Uint8Array } | null = null /** A lost final response leaves the tail unhashed; re-read it (bounded: < one chunk) to finish the hash. */ const completeHash = async () => { if (!hasher || r.hash.status !== 'tracking' || hasher.bytesHashed >= total) return const from = hasher.bytesHashed if (pending && pending.start === from && pending.start + pending.bytes.byteLength === total) { hasher.update(pending.bytes) return } if (total - from > r.chunkSizeBytes || !validatorIdentity(r.source)) { // Without an origin validator a re-read cannot prove these are the bytes that were sent. hasher = null return } try { hasher.update(await fetchSourceRange(deps.sourceFetch, sourceUrl, sourceHeaders, r.source, from, total - 1)) } catch { hasher = null } } const applyAck = async (next: number, chunk: Uint8Array | null, chunkStart: number): Promise => { if (next > total || next < 0) throw new UploadEngineError('bad_ack', `YouTube acknowledged ${next} of ${total} bytes.`, { jobId: r.jobId }) let hash = r.hash if (hasher && hash.status === 'tracking') { const covered = chunk && next > r.ackOffset && r.ackOffset === chunkStart && next <= chunkStart + chunk.byteLength && (next - chunkStart) % 64 === 0 if (covered) { hasher.update(chunk!.subarray(0, next - chunkStart)) hash = { ...hash, state: hasher.snapshot() } } else if (next === 0) { // YouTube persisted nothing (308 without Range): start the hash over with the bytes. hasher = new Sha256() hash = { ...hash, state: hasher.snapshot() } } else if (next > r.ackOffset && hasher.bytesHashed === r.ackOffset && (next - r.ackOffset) % 64 === 0 && next - r.ackOffset <= r.chunkSizeBytes && validatorIdentity(r.source)) { // Acknowledged bytes we no longer hold (e.g. a response lost before a crash). They were sent from // this same validator-checked source, so re-read that one bounded gap to keep the hash complete. try { hasher.update(await fetchSourceRange(deps.sourceFetch, sourceUrl, sourceHeaders, r.source, r.ackOffset, next - 1)) hash = { ...hash, state: hasher.snapshot() } } catch { hasher = null hash = { status: 'unverifiable', state: null, sha256: null } } } else if (next !== r.ackOffset) { hasher = null hash = { status: 'unverifiable', state: null, sha256: null } } } stalls = next > r.ackOffset ? 0 : stalls + 1 r = await save(r, { ackOffset: next, hash, state: 'uploading' }) log({ event: 'upload_ack', jobId: r.jobId, ackOffset: next, bytes: total }) } const handleFailure = async (q: QueryResult): Promise => { if (q.kind === 'expired') return await stop(r, 'needs_reconciliation', 'session_expired', `The resumable session answered HTTP ${q.status} (expired or unknown). Not creating a new session automatically.`) if (q.kind === 'fatal') return await stop(r, 'needs_reconciliation', 'session_rejected', `YouTube rejected the upload with HTTP ${q.status}: ${q.message}`) if (q.kind === 'halt') return await stop(r, 'paused', q.code, `Session status query stopped (${q.code}); resumeUpload queries the same session first.`) retries += 1 r = await save(r, { attempts: r.attempts + 1, lastError: { code: q.kind === 'auth' ? 'auth' : 'retryable', message: q.kind === 'retry' ? q.message : 'HTTP 401', at: iso() } }) if (retries > (q.kind === 'auth' ? 2 : maxRetries)) { return await stop(r, 'paused', q.kind === 'auth' ? 'auth_failed' : 'retries_exhausted', q.kind === 'auth' ? 'YouTube kept answering 401. Reconnect the youtube credential, then resumeUpload (same session).' : `Gave up after ${maxRetries} retries at byte ${r.ackOffset}; resumeUpload continues the same session.`) } const delay = backoffDelay(retries, baseMs, capMs, random) if (now() + delay > deadline) return await stop(r, 'paused', 'run_budget', 'Run budget reached during backoff; resumeUpload continues the same session.') await sleep(delay) needQuery = true return null } for (;;) { if (needQuery) { const q = await querySession(sessionUrl, total) if (q.kind === 'progress') { needQuery = false if (q.next !== r.ackOffset) await applyAck(q.next, pending?.bytes ?? null, pending?.start ?? -1) pending = null } else if (q.kind === 'complete') { await completeHash() return await finishUploaded(r, q.videoId, hasher, q.data) } else { const stopped = await handleFailure(q) if (stopped) return stopped continue } } if (r.ackOffset >= total) { // All bytes acknowledged but no final resource seen: ask the same session. needQuery = true const q = await querySession(sessionUrl, total) if (q.kind === 'complete') { await completeHash() return await finishUploaded(r, q.videoId, hasher, q.data) } const stopped = await handleFailure(q.kind === 'progress' ? { kind: 'retry', status: 308, message: 'All bytes acknowledged; waiting for the final resource.' } : q) if (stopped) return stopped continue } if (now() >= deadline) return await stop(r, 'paused', 'run_budget', 'Run budget reached; resumeUpload continues the same session.') if (stalls >= maxStalls) return await stop(r, 'paused', 'no_progress', `No upload progress after ${stalls} attempts at byte ${r.ackOffset}; resumeUpload continues the same session.`) const chunkStart = r.ackOffset const end = Math.min(chunkStart + r.chunkSizeBytes, total) - 1 let chunk: Uint8Array try { chunk = await fetchSourceRange(deps.sourceFetch, sourceUrl, sourceHeaders, r.source, chunkStart, end) } catch (error) { const e = error as UploadEngineError if (e?.retryable) { const stopped = await handleFailure({ kind: 'retry', status: null, message: e.message }) if (stopped) return stopped needQuery = false continue } return await stop(r, 'paused', e?.code ?? 'source_error', e?.message ?? String(error)) } pending = { start: chunkStart, bytes: chunk } let res: Response try { res = await deps.ytFetch(sessionUrl, { method: 'PUT', redirect: 'manual', headers: { 'content-type': 'video/*', 'content-range': `bytes ${chunkStart}-${end}/${total}`, 'x-kody-secret-resolution': 'headers-only' }, // readExact allocates an exact-size buffer, so this is the chunk's own bytes (no copy). body: chunk.buffer as ArrayBuffer, }) } catch (error) { const t = classifyTransportError(error) // Caller abort or a Kody refusal that retrying cannot fix: stop resumable; the next run queries the session first. if (t.aborted) return await stop(r, 'paused', 'aborted', `The request was aborted at byte ${chunkStart}; resumeUpload queries the same session first.`) if (t.definite) return await stop(r, 'paused', `gateway_${t.gatewayCode}`, `Kody refused the chunk request (${t.gatewayCode}); fix that, then resumeUpload (same session, status query first).`) // Otherwise bytes may or may not have reached YouTube: ambiguous, so query the same session. const stopped = await handleFailure({ kind: 'retry', status: null, message: redactText(String((error as Error)?.message ?? error)) }) if (stopped) return stopped continue } const q = await classify(res) if (q.kind === 'progress') { // An ack beyond this chunk means our offset was stale; the session is the source of truth // (applyAck marks the hash unverifiable because this chunk does not cover it). retries = 0 await applyAck(q.next, chunk, chunkStart) pending = null continue } if (q.kind === 'complete') { if (end + 1 !== total) return await stop(r, 'needs_reconciliation', 'early_complete', `YouTube finished the upload at byte ${end + 1} of ${total}.`) if (hasher && r.hash.status === 'tracking' && hasher.bytesHashed === chunkStart) hasher.update(chunk) return await finishUploaded(r, q.videoId, hasher, q.data) } const stopped = await handleFailure(q) if (stopped) return stopped } } return { leaseOwner, async status(jobId: string): Promise { return await deps.store.get(jobId) }, /** Create (or return) the job for uploadKey. Exactly one session-create POST per job, ever. */ async start(input: StartJobInput): Promise<{ record: UploadJobRecord; created: boolean }> { assertSafeChunk(input.chunkSizeBytes) const fingerprint = await metadataFingerprint(input.channelId, input.metadata) const source = input.source ?? (await probeSource(deps.sourceFetch, input.sourceUrl, input.sourceHeaders, input.chunkSizeBytes, input.expectedSha256 ?? null)) const existing = await deps.store.findByKey(input.uploadKey) if (existing) { if (existing.channelId !== input.channelId || existing.metadataFingerprint !== fingerprint) { throw new UploadEngineError('job_conflict', 'uploadKey already belongs to an upload with a different channel or metadata. Channel and metadata are immutable per job; use a new uploadKey.', { jobId: existing.jobId, state: existing.state }) } const sameSource = existing.source.bytes === source.bytes && (source.expectedSha256 == null || source.expectedSha256 === existing.source.expectedSha256) && checkSourceIdentity(existing.source, source.etag, source.lastModified) === null if (!sameSource) { throw new UploadEngineError('job_conflict', 'uploadKey already belongs to an upload of a different (or unprovable) source file. The source is immutable per job; use a new uploadKey.', { jobId: existing.jobId, state: existing.state }) } if (existing.state === 'failed') { throw new UploadEngineError('job_failed', 'This uploadKey failed before a session existed. Use a new uploadKey to start again.', { jobId: existing.jobId, state: existing.state }) } return { record: existing, created: false } } if (sourceIdentityLevel(source) === 'none') { throw new UploadEngineError( 'source_identity_unverifiable', 'The media source sends no strong ETag or Last-Modified and no expectedSha256 was given, so nothing can prove every chunk comes from one unchanged file. Pass expectedSha256 (lowercase hex SHA-256 of the whole file) or host it on an origin with a strong ETag (R2/S3). Nothing was uploaded.', ) } const at = iso() let r: UploadJobRecord = { v: 1, jobId: randomId(), uploadKey: input.uploadKey, state: 'session_pending', channelId: input.channelId, metadataFingerprint: fingerprint, metadata: input.metadata, source, chunkSizeBytes: input.chunkSizeBytes, ackOffset: 0, hash: { status: 'tracking', state: new Sha256().snapshot(), sha256: null }, sessionDurable: deps.vault.durable && deps.store.durable, sealedSession: null, sessionCreatedAt: null, videoId: null, processing: null, reconciliation: null, lastError: null, attempts: 0, leaseOwner, leaseExpiresAt: now() + leaseMs, createdAt: at, updatedAt: at, version: 1, } if (!(await deps.store.insert(r))) { const winner = await deps.store.findByKey(input.uploadKey) if (winner) return { record: winner, created: false } throw new UploadEngineError('job_conflict', 'Could not create the upload job row.', {}) } // Checkpoint exists BEFORE the create POST, so a crash or lost response is visible as session_pending. let res: Response try { res = await deps.ytFetch(UPLOAD_URL, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/json; charset=UTF-8', 'x-upload-content-length': String(source.bytes), 'x-upload-content-type': 'video/*', 'x-kody-secret-resolution': 'headers-only', }, body: JSON.stringify(input.metadata), }) } catch (error) { const t = classifyTransportError(error) if (t.notSent) { // The transport proved no byte reached YouTube (mayHaveReachedOrigin: false): no session exists. r = await stop(r, 'failed', t.gatewayCode ? `session_create_not_sent_${t.gatewayCode}` : 'session_create_not_sent', `Session-create request was not sent (${t.aborted ? 'aborted' : t.gatewayCode ?? 'transport'}); no YouTube session exists. Start again with a new uploadKey.`) return { record: r, created: true } } r = await stop(r, 'needs_reconciliation', 'session_create_ambiguous', `Session-create request failed in a way that may have reached YouTube: ${(error as Error)?.message ?? error}`) return { record: r, created: true } } if (!res.ok) { const text = await res.text().catch(() => '') const definite = res.status >= 400 && res.status < 500 && res.status !== 408 && res.status !== 429 r = await stop(r, definite ? 'failed' : 'needs_reconciliation', definite ? `session_create_http_${res.status}` : 'session_create_ambiguous', `Session create returned HTTP ${res.status}: ${redactText(text, 300)}`) return { record: r, created: true } } const location = res.headers.get('location') await discard(res) if (!isTrustedSessionUrl(location)) { r = await stop(r, 'needs_reconciliation', 'session_create_ambiguous', 'YouTube accepted the session create without a usable Location.') return { record: r, created: true } } let sealed: string try { sealed = await deps.vault.seal(r.jobId, aadFor(r), location!) } catch (error) { // A session now exists on YouTube but could not be protected: never retry the create. r = await stop(r, 'needs_reconciliation', 'session_seal_failed', `A session was created but could not be sealed (${(error as Error)?.name ?? 'error'}); the upload may appear on the channel as incomplete. Not retried.`) return { record: r, created: true } } r = await save(r, { state: 'uploading', sealedSession: sealed, sessionCreatedAt: iso() }) log({ event: 'upload_session', jobId: r.jobId, durable: r.sessionDurable }) return { record: r, created: true } }, /** Upload from the current checkpoint. Always begins with a status query when resuming. */ async run(jobId: string, sourceUrl: string, sourceHeaders: Record | undefined, opts: { resumed: boolean }): Promise { let r = await deps.store.get(jobId) if (!r) throw new UploadEngineError('job_not_found', `No upload job ${jobId}.`) if (TERMINAL_STATES.has(r.state) || r.state === 'uploaded' || r.state === 'needs_reconciliation') return r if (r.state === 'session_pending') { // Lease still ours only within the same start call; a later run means the create outcome is unknown. if (r.leaseOwner === leaseOwner && !opts.resumed) return r r = await acquire(r) return await stop(r, 'needs_reconciliation', 'session_create_ambiguous', 'A previous run stopped before the session-create response was recorded. Check the channel for an orphan upload before deciding.') } r = await acquire(r) // Re-validate source identity against the checkpoint before sending more bytes. if (opts.resumed) { let probed: SourceIdentity try { probed = await probeSource(deps.sourceFetch, sourceUrl, sourceHeaders, r.chunkSizeBytes, r.source.expectedSha256) } catch (error) { return await stop(r, 'paused', (error as UploadEngineError)?.code ?? 'source_error', (error as Error)?.message ?? String(error)) } if (probed.bytes !== r.source.bytes) { return await stop(r, 'paused', 'source_changed', `Resume source is ${probed.bytes} bytes; the job expects ${r.source.bytes} bytes of the original file.`) } const idFail = checkSourceIdentity(r.source, probed.etag, probed.lastModified) if (idFail) return await stop(r, 'paused', idFail.code, `Resume source: ${idFail.reason}. Not appending bytes.`) } return await drive(r, sourceUrl, sourceHeaders, { queryFirst: opts.resumed || r.ackOffset > 0 }) }, /** Persist a processing check (from videos.list). Only `completed` once processed with positive duration on the right channel. */ async recordProcessing(jobId: string, item: Record | null, expectedDurationSeconds?: number): Promise { let r = await deps.store.get(jobId) if (!r) throw new UploadEngineError('job_not_found', `No upload job ${jobId}.`) if (r.state !== 'uploaded' && r.state !== 'completed') return r const at = iso() if (!item) return await save(r, { processing: { uploadStatus: 'not_found', duration: null, privacyStatus: null, checkedAt: at } }) const uploadStatus = typeof item?.status?.uploadStatus === 'string' ? item.status.uploadStatus : null const duration = typeof item?.contentDetails?.duration === 'string' ? item.contentDetails.duration : null const privacyStatus = typeof item?.status?.privacyStatus === 'string' ? item.status.privacyStatus : null const processing = { uploadStatus, duration, privacyStatus, checkedAt: at } if (item?.snippet?.channelId && item.snippet.channelId !== r.channelId) { r = await save(r, { processing }) return await stop(r, 'needs_reconciliation', 'channel_mismatch', 'The uploaded video is on a different channel than the job.') } if (uploadStatus === 'failed' || uploadStatus === 'rejected' || uploadStatus === 'deleted') { r = await save(r, { processing }) return await stop(r, 'needs_reconciliation', `processing_${uploadStatus}`, `YouTube reports uploadStatus ${uploadStatus}. Nothing was changed.`) } const seconds = parseIsoDuration(duration) const durationOk = seconds > 0 && (expectedDurationSeconds === undefined || Math.abs(seconds - expectedDurationSeconds) <= Math.max(2, expectedDurationSeconds * 0.01)) if (uploadStatus === 'processed' && seconds > 0 && !durationOk) { r = await save(r, { processing }) return await stop(r, 'needs_reconciliation', 'duration_mismatch', `Processed duration ${duration} does not match expected ${expectedDurationSeconds}s.`) } const hashOk = r.source.expectedSha256 ? r.hash.status === 'matched' : r.hash.status !== 'mismatch' const done = uploadStatus === 'processed' && durationOk && hashOk return await save(r, { processing, state: done ? 'completed' : 'uploaded' }) }, /** Explicit human reconciliation. Never deletes or edits anything on YouTube. */ async reconcile(jobId: string, action: 'abandon' | 'mark_uploaded', videoId?: string): Promise { let r = await deps.store.get(jobId) if (!r) throw new UploadEngineError('job_not_found', `No upload job ${jobId}.`) if (TERMINAL_STATES.has(r.state)) return r if (r.state === 'uploaded') throw new UploadEngineError('bad_state', 'This job already uploaded a video; verify it with getUploadStatus instead of reconciling.', { jobId, state: r.state }) if (r.leaseOwner && r.leaseOwner !== leaseOwner && (r.leaseExpiresAt ?? 0) > now()) { throw new UploadEngineError('job_busy', 'Job is leased by a running invocation; reconcile after it stops.', { jobId, state: r.state, retryable: true }) } await deps.vault.forget(jobId) const at = iso() if (action === 'mark_uploaded') { if (!videoId) throw new UploadEngineError('bad_input', 'mark_uploaded needs the videoId a person confirmed on the channel.') return await save(r, { state: 'uploaded', videoId, sealedSession: null, leaseOwner: null, leaseExpiresAt: null, reconciliation: { reason: 'manual_mark_uploaded', detail: `Marked uploaded as ${videoId} by a person.`, at } }) } return await save(r, { state: 'abandoned', sealedSession: null, leaseOwner: null, leaseExpiresAt: null, reconciliation: { reason: 'manual_abandon', detail: r.reconciliation?.detail ?? 'Abandoned by a person.', at } }) }, } } export function isSafeChunk(n: number): boolean { return Number.isInteger(n) && n > 0 && n % CHUNK_MULTIPLE === 0 && n <= MAX_SAFE_CHUNK_BYTES } function assertSafeChunk(n: number): void { if (!isSafeChunk(n)) { throw new UploadEngineError('chunk_too_large', `chunkSizeBytes must be a multiple of ${CHUNK_MULTIPLE} and at most ${MAX_SAFE_CHUNK_BYTES} (the package's chunk cap).`) } } export function parseIsoDuration(value: string | null): number { if (!value) return 0 const m = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/.exec(value) if (!m) return 0 return (Number(m[1] ?? 0) * 86400) + (Number(m[2] ?? 0) * 3600) + (Number(m[3] ?? 0) * 60) + Number(m[4] ?? 0) }