Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

upload-state.ts

280 lines · 11.2 KB · TypeScript
// Vendored verbatim from @kody/youtube src/internal (keep in sync; no kody: dependency so this public package stays self-contained).
/**
 * Durable upload job state for resumable YouTube uploads.
 *
 * Two separate concerns:
 * - `UploadJobStore`: NON-secret checkpoint rows (offset, source identity,
 *   channel, metadata fingerprint, hash midstate, video id). Backed by the
 *   package's own `packageStorage().sql` bucket, or memory in tests/fallback.
 *   Optimistic concurrency: every write is compare-and-swap on `version`.
 * - `SessionVault`: the resumable session URL is a bearer capability (anyone
 *   holding it can append bytes to the upload). It is never written in
 *   plaintext. A durable vault seals it with AES-GCM under a per-job key
 *   derived from a Kody credential's HMAC `sign()` (the root key never reaches
 *   code). Without a signer the vault is memory-only and NOT crash-durable.
 *
 * Self-contained (no `kody:runtime` import) so it runs under plain Node tests
 * and can be vendored into @kentcdodds/google unchanged.
 */

import type { Sha256State } from './sha256.ts'

export type UploadJobState =
	/** Job row written; session-create POST not yet answered. A crash here is ambiguous. */
	| 'session_pending'
	/** Session open; bytes up to ackOffset acknowledged by YouTube. */
	| 'uploading'
	/** Resumable, stopped for a bounded reason (budget, auth, retries). Call resume. */
	| 'paused'
	/** YouTube returned the video resource; processing not yet verified. */
	| 'uploaded'
	/** Upload finished AND processing verified (processed, positive duration, right channel). */
	| 'completed'
	/** Stopped fail-closed; a person must decide. Never auto-recreated. */
	| 'needs_reconciliation'
	/** A person reconciled the job and chose to abandon it. Nothing was deleted. */
	| 'abandoned'
	/** Definitively failed before any session existed (e.g. 4xx on session create). */
	| 'failed'

export const TERMINAL_STATES: ReadonlySet<UploadJobState> = new Set(['completed', 'abandoned', 'failed'])

export type SourceIdentity = {
	bytes: number
	etag: string | null
	lastModified: string | null
	/** Caller-declared expected SHA-256 (hex) of the whole source, if any. */
	expectedSha256: string | null
	/** False when the origin ignored Range (only allowed for single-chunk sources). */
	rangeSupported: boolean
}

export type UploadJobRecord = {
	v: 1
	jobId: string
	uploadKey: string
	state: UploadJobState
	channelId: string
	metadataFingerprint: string
	/** Non-secret metadata sent to videos.insert (title, description, privacy...). */
	metadata: Record<string, unknown>
	source: SourceIdentity
	chunkSizeBytes: number
	ackOffset: number
	hash: { status: 'tracking' | 'computed' | 'unverifiable' | 'matched' | 'mismatch'; state: Sha256State | null; sha256: string | null }
	sessionDurable: boolean
	/** Sealed session capability (never plaintext). Null when none or after completion. */
	sealedSession: string | null
	sessionCreatedAt: string | null
	videoId: string | null
	processing: { uploadStatus: string | null; duration: string | null; privacyStatus: string | null; checkedAt: string } | null
	reconciliation: { reason: string; detail: string; at: string } | null
	lastError: { code: string; message: string; at: string } | null
	attempts: number
	leaseOwner: string | null
	leaseExpiresAt: number | null
	createdAt: string
	updatedAt: string
	version: number
}

export interface UploadJobStore {
	readonly durable: boolean
	get(jobId: string): Promise<UploadJobRecord | null>
	findByKey(uploadKey: string): Promise<UploadJobRecord | null>
	/** Insert iff no row has this jobId or uploadKey. Returns false on conflict. */
	insert(record: UploadJobRecord): Promise<boolean>
	/** Compare-and-swap on version. Returns the stored record (version+1) or null if stale. */
	update(record: UploadJobRecord, expectedVersion: number): Promise<UploadJobRecord | null>
}

/** Shape of `packageStorage().sql` (hosted and local-execute bound storage). */
export type SqlSurface = { sql(query: string, params?: unknown[]): Promise<{ rows?: Array<Record<string, unknown>> } | unknown> }

function rowsOf(result: unknown): Array<Record<string, unknown>> {
	if (Array.isArray(result)) return result as Array<Record<string, unknown>>
	const rows = (result as { rows?: unknown } | null)?.rows
	return Array.isArray(rows) ? (rows as Array<Record<string, unknown>>) : []
}

const TABLE = 'youtube_upload_jobs_v1'

export function createSqlUploadJobStore(storage: SqlSurface): UploadJobStore {
	let ready: Promise<void> | null = null
	const ensure = () =>
		(ready ??= (async () => {
			await storage.sql(
				`CREATE TABLE IF NOT EXISTS ${TABLE} (job_id TEXT PRIMARY KEY, upload_key TEXT NOT NULL UNIQUE, version INTEGER NOT NULL, state TEXT NOT NULL, record TEXT NOT NULL, updated_at TEXT NOT NULL)`,
				[],
			)
		})().catch((error) => {
			ready = null
			throw error
		}))
	const parse = (row: Record<string, unknown> | undefined): UploadJobRecord | null => {
		if (!row || typeof row.record !== 'string') return null
		const rec = JSON.parse(row.record) as UploadJobRecord
		rec.version = Number(row.version)
		return rec
	}
	return {
		durable: true,
		async get(jobId) {
			await ensure()
			return parse(rowsOf(await storage.sql(`SELECT record, version FROM ${TABLE} WHERE job_id = ?`, [jobId]))[0])
		},
		async findByKey(uploadKey) {
			await ensure()
			return parse(rowsOf(await storage.sql(`SELECT record, version FROM ${TABLE} WHERE upload_key = ?`, [uploadKey]))[0])
		},
		async insert(record) {
			await ensure()
			const rows = rowsOf(
				await storage.sql(
					`INSERT INTO ${TABLE} (job_id, upload_key, version, state, record, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING job_id`,
					[record.jobId, record.uploadKey, record.version, record.state, JSON.stringify(record), record.updatedAt],
				),
			)
			return rows.length === 1
		},
		async update(record, expectedVersion) {
			await ensure()
			const next = { ...record, version: expectedVersion + 1 }
			const rows = rowsOf(
				await storage.sql(
					`UPDATE ${TABLE} SET version = ?, state = ?, record = ?, updated_at = ? WHERE job_id = ? AND version = ? RETURNING version`,
					[next.version, next.state, JSON.stringify(next), next.updatedAt, record.jobId, expectedVersion],
				),
			)
			return rows.length === 1 ? next : null
		},
	}
}

/** Process-local store. Not crash-durable; used in tests and when packageStorage is unavailable. */
export function createMemoryUploadJobStore(): UploadJobStore {
	const rows = new Map<string, string>()
	return {
		durable: false,
		async get(jobId) {
			const raw = rows.get(jobId)
			return raw ? (JSON.parse(raw) as UploadJobRecord) : null
		},
		async findByKey(uploadKey) {
			for (const raw of rows.values()) {
				const rec = JSON.parse(raw) as UploadJobRecord
				if (rec.uploadKey === uploadKey) return rec
			}
			return null
		},
		async insert(record) {
			if (rows.has(record.jobId)) return false
			for (const raw of rows.values()) if ((JSON.parse(raw) as UploadJobRecord).uploadKey === record.uploadKey) return false
			rows.set(record.jobId, JSON.stringify(record))
			return true
		},
		async update(record, expectedVersion) {
			const raw = rows.get(record.jobId)
			if (!raw || (JSON.parse(raw) as UploadJobRecord).version !== expectedVersion) return null
			const next = { ...record, version: expectedVersion + 1 }
			rows.set(record.jobId, JSON.stringify(next))
			return next
		},
	}
}

// ---------- session vault ----------

export interface SessionVault {
	/** True when a sealed session survives process death. */
	readonly durable: boolean
	readonly kind: 'signer-sealed' | 'memory'
	seal(jobId: string, aad: string, sessionUrl: string): Promise<string>
	/** Returns null when the capability is unavailable (e.g. memory vault after restart). */
	open(jobId: string, aad: string, sealed: string): Promise<string | null>
	forget(jobId: string): Promise<void>
}

/** A Kody credential client (Key) that can HMAC; the key never reaches code. */
export type HmacSigner = {
	sign(input: { type: 'hmac'; algorithm: 'hmac-sha256'; message: string; encoding?: 'hex' | 'base64' }): Promise<unknown>
}

const memorySessions = new Map<string, string>()

/** Memory-only: the session dies with the process. Resume after a crash becomes needs_reconciliation. */
export function createMemorySessionVault(): SessionVault {
	return {
		durable: false,
		kind: 'memory',
		async seal(jobId, _aad, sessionUrl) {
			memorySessions.set(jobId, sessionUrl)
			return 'mem.v1'
		},
		async open(jobId, _aad, sealed) {
			return sealed === 'mem.v1' ? (memorySessions.get(jobId) ?? null) : null
		},
		async forget(jobId) {
			memorySessions.delete(jobId)
		},
	}
}

const enc = new TextEncoder()
const dec = new TextDecoder()
function b64(bytes: Uint8Array): string {
	let s = ''
	for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
	return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function unb64(text: string): Uint8Array {
	const s = atob(text.replace(/-/g, '+').replace(/_/g, '/'))
	const out = new Uint8Array(s.length)
	for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i)
	return out
}
function signatureBytes(sig: unknown): Uint8Array {
	if (typeof sig === 'string' && sig.length >= 16) return enc.encode(sig)
	if (sig instanceof ArrayBuffer) return new Uint8Array(sig)
	if (ArrayBuffer.isView(sig)) return new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength)
	const inner = (sig as { signature?: unknown } | null)?.signature
	if (inner !== undefined && inner !== sig) return signatureBytes(inner)
	throw new Error('Session vault signer returned no usable HMAC signature.')
}

/**
 * Durable vault: AES-256-GCM, key = SHA-256(HMAC(root, label:jobId:salt)).
 * The AAD binds the ciphertext to the job, channel, and metadata fingerprint,
 * so a sealed session cannot be replayed into another job row.
 */
export function createSignerSessionVault(signer: HmacSigner): SessionVault {
	if (!signer || typeof signer.sign !== 'function') throw new Error('createSignerSessionVault needs a credential client with sign().')
	const deriveKey = async (jobId: string, salt: string) => {
		const sig = await signer.sign({ type: 'hmac', algorithm: 'hmac-sha256', message: `kody-youtube-upload-vault:v1:${jobId}:${salt}`, encoding: 'hex' })
		const raw = await crypto.subtle.digest('SHA-256', signatureBytes(sig) as BufferSource)
		return await crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
	}
	return {
		durable: true,
		kind: 'signer-sealed',
		async seal(jobId, aad, sessionUrl) {
			const salt = b64(crypto.getRandomValues(new Uint8Array(16)))
			const iv = crypto.getRandomValues(new Uint8Array(12))
			const key = await deriveKey(jobId, salt)
			const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: enc.encode(aad) }, key, enc.encode(sessionUrl)))
			return `sv1.${salt}.${b64(iv)}.${b64(ct)}`
		},
		async open(jobId, aad, sealed) {
			const parts = sealed.split('.')
			if (parts.length !== 4 || parts[0] !== 'sv1') return null
			try {
				const key = await deriveKey(jobId, parts[1])
				const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(parts[2]) as BufferSource, additionalData: enc.encode(aad) }, key, unb64(parts[3]) as BufferSource)
				return dec.decode(pt)
			} catch {
				return null
			}
		},
		async forget() {},
	}
}