import { exactInteger } from '../exact-json.ts'; // GIT LFS (architecture, "The tree contract": Git LFS is the git library's too): the batch API git-lfs speaks // (https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md, the basic transfer), a pointer file read // (https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md), and an upload accepted only when its bytes hash to the // object's oid and its size is the one declared. The objects are the caller's (a pack's resource blobs, by oid); the // caller says where objects go up and come down (the vendor's own hosts) and decides who may do either before it calls. // Importing it does nothing. export const LFS_TYPE = 'application/vnd.git-lfs+json'; export type LfsObject = { oid: string; size: number | string }; /** Where a pack keeps its objects: by oid. */ /** Where a server keeps its LFS objects: an object's size when it holds one (the batch API answers from it, never * loading the object), and the store an upload's verified bytes go to. */ export type LfsStore = { size(oid: string): Promise; put(oid: string, bytes: Uint8Array): Promise; /** an upload's body written as it arrives and kept only when `accept` holds for its size and SHA-256 (`ctx.blobs.putStream`): * a store with it never holds an object whole */ putStream?(oid: string, chunks: AsyncIterable, accept: (written: { size: number; sha256: string }) => boolean): Promise; }; const OID = /^[0-9a-f]{64}$/; const lfsJson = (status: number, body: unknown): Response => Response.json(body, { status, headers: { 'content-type': LFS_TYPE } }); /** A pointer file's object (`version https://git-lfs.github.com/spec/v1`, `oid sha256:`, `size `), or null * for any other file. */ export function parseLfsPointer(file: Uint8Array | string): LfsObject | null { const text = typeof file === 'string' ? file : file.length > 1024 ? '' : new TextDecoder().decode(file); if (!text.startsWith('version https://git-lfs.github.com/spec/')) return null; const oid = /^oid sha256:([0-9a-f]{64})$/m.exec(text)?.[1]; const size = /^size (\d+)$/m.exec(text)?.[1]; return oid && size ? { oid, size: exactInteger(size) } : null; } /** A pointer file's text for an object. */ export const lfsPointer = (o: LfsObject): string => `version https://git-lfs.github.com/spec/v1\noid sha256:${o.oid}\nsize ${o.size}\n`; /** An object's sha256, as its oid. */ export async function lfsOid(bytes: Uint8Array): Promise { const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes as unknown as ArrayBuffer); return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join(''); } /** `POST …/info/lfs/objects/batch`: for each object asked, an upload's action (none when the object is held already) or * a download's (an error when it is not held), by the basic transfer. `href` names where an object goes up or comes * down; `header` is sent with each action. */ export async function lfsBatch(body: unknown, opts: { store: LfsStore; href: (operation: 'upload' | 'download', o: LfsObject) => string; header?: Record }): Promise { const b = (body && typeof body === 'object' ? body : {}) as { operation?: unknown; transfers?: unknown; objects?: unknown }; // source: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md "Should be download or upload." if (b.operation !== 'upload' && b.operation !== 'download') return lfsJson(422, { message: 'operation must be download or upload' }); if (Array.isArray(b.transfers) && b.transfers.length && !b.transfers.includes('basic')) return lfsJson(422, { message: 'no transfer adapter in common: this server speaks basic' }); if (!Array.isArray(b.objects)) return lfsJson(422, { message: 'objects is required' }); const operation = b.operation; const objects = []; for (const raw of b.objects as Array<{ oid?: unknown; size?: unknown }>) { const o = { oid: String(raw?.oid ?? ''), size: /^-?\d+$/.test(String(raw?.size)) ? exactInteger(String(raw?.size)) : Number(raw?.size) }; // source: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md "The object is invalid (for example, an invalid oid or size)." if (!OID.test(o.oid) || !Number.isSafeInteger(o.size) || Number(o.size) < 0) { objects.push({ ...o, error: { code: 422, message: 'Invalid object' } }); continue; } const held = await opts.store.size(o.oid); if (operation === 'upload') { objects.push(held !== null ? { ...o, authenticated: true } : { ...o, authenticated: true, actions: { upload: { href: opts.href('upload', o), ...(opts.header ? { header: opts.header } : {}), expires_in: 3600 } } }); } else { // source: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md "The object does not exist on the server." objects.push(held !== null ? { oid: o.oid, size: held, authenticated: true, actions: { download: { href: opts.href('download', o), ...(opts.header ? { header: opts.header } : {}), expires_in: 3600 } } } : { ...o, error: { code: 404, message: 'Object does not exist' } }); } } return lfsJson(200, { transfer: 'basic', objects, hash_algo: 'sha256' }); } /** A basic transfer's upload (`PUT` of the object's bytes): kept when they hash to the oid and have the declared size * (the size is the request's Content-Length when the caller has no other), else refused and nothing kept. A body * stream goes to the store's `putStream` as it arrives, read no further than the declared size; bytes, or a store * without one, are checked whole. */ export async function lfsUpload(body: Uint8Array | ReadableStream | null, o: LfsObject, store: LfsStore): Promise { const refused = (): Response => lfsJson(422, { message: `the object's bytes do not match ${o.oid} (${o.size} bytes)` }); if (body instanceof Uint8Array || body === null || !store.putStream) { const bytes = body instanceof Uint8Array ? body : new Uint8Array(body === null ? new ArrayBuffer(0) : await new Response(body).arrayBuffer()); if (bytes.length !== o.size || (await lfsOid(bytes)) !== o.oid) return refused(); await store.put(o.oid, bytes); return new Response(null, { status: 200 }); } const declared = Number(o.size); let over = false; async function* upTo(stream: ReadableStream): AsyncGenerator { const reader = stream.getReader(); let read = 0; try { for (;;) { const { done, value } = await reader.read(); if (done) return; read += value.byteLength; // a body longer than declared is refused without reading the rest of it if (read > declared) { over = true; await reader.cancel(); return; } yield value; } } finally { reader.releaseLock(); } } const kept = await store.putStream(o.oid, upTo(body), (w) => !over && w.size === declared && w.sha256 === o.oid); return kept ? new Response(null, { status: 200 }) : refused(); }