From e40fd63986142dad03124e07311f5951473b38a7 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Tue, 24 Nov 2026 20:30:05 +0000 Subject: [PATCH] feat(upload): upload straight to the final storage path with a signed token Ask the API for a signed upload token when getting an upload URL. When one comes back, upload the Supabase copy with TUS straight to the final path through /storage/v1/upload/resumable/sign, sending the token as x-signature, so the API has nothing to copy when it finalises. The token is refreshed before a request when it is close to expiry, and when Storage refuses it, so a long upload carries on. If the signed upload fails, or the API offers none, the CLI uploads to the temp path as before. Co-Authored-By: Claude Opus 5.5 --- src/gateways/api-gateway.ts | 69 ++++++-- src/gateways/supabase-gateway.ts | 185 ++++++++++++++++--- src/methods.ts | 99 +++++++++-- test/unit/signed-upload.test.ts | 293 +++++++++++++++++++++++++++++++ 4 files changed, 596 insertions(+), 50 deletions(-) create mode 100644 test/unit/signed-upload.test.ts diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index 28e08bd..a5d1e43 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -19,6 +19,7 @@ import type { } from '../types/domain/live.types.js'; import type { TeamSettings } from '../types/domain/team-settings.types.js'; import { components, paths } from '../types/generated/schema.types.js'; +import type { SignedUpload } from './supabase-gateway.js'; import { expandHome } from '../utils/paths.js'; import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js'; @@ -145,6 +146,15 @@ export interface ResultsPollCache { etag?: string; } +/** + * An upload-URL response. `signedUpload` comes only from an API that supports + * direct uploads, and only when the request asked for it; without it the + * client uploads to `tempPath`. + */ +type UploadUrlResponse = components['schemas']['IGetBinaryUploadUrlResponse'] & { + signedUpload?: SignedUpload; +}; + export const ApiGateway = { /** * Enhances generic "fetch failed" errors with more specific diagnostic information @@ -642,8 +652,13 @@ export const ApiGateway = { */ shaPlain?: string; supabaseSuccess: boolean; + /** + * True when `path` is the final path a signed token uploaded to. The API + * then checks the object is there and skips its copy. + */ + useTus?: boolean; }) { - const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes } = config; + const { baseUrl, auth, id, metadata, path, sha, shaPlain, supabaseSuccess, backblazeSuccess, bytes, useTus } = config; try { const res = await fetch(`${baseUrl}/uploads/finaliseUpload`, { body: JSON.stringify({ @@ -651,10 +666,11 @@ export const ApiGateway = { bytes, id, metadata, - path, // This is tempPath for TUS uploads + path, // tempPath, or the signed final path when useTus is set ...(sha ? { sha } : {}), ...(shaPlain ? { shaPlain } : {}), supabaseSuccess, + ...(useTus ? { useTus } : {}), }), headers: { 'content-type': 'application/json', @@ -686,7 +702,9 @@ export const ApiGateway = { ) { try { const res = await fetch(`${baseUrl}/uploads/getBinaryUploadUrl`, { - body: JSON.stringify({ platform, fileSize }), + // signedUpload: ask for a token to upload straight to the final + // path. An API without direct uploads ignores the field. + body: JSON.stringify({ platform, fileSize, signedUpload: true }), headers: { 'content-type': 'application/json', ...auth.headers, @@ -697,9 +715,7 @@ export const ApiGateway = { await this.handleApiError(res, 'Failed to get upload URL'); } - return await parseJsonResponse< - paths['/uploads/getBinaryUploadUrl']['post']['responses']['201']['content']['application/json'] - >(res, 'Failed to get upload URL'); + return await parseJsonResponse(res, 'Failed to get upload URL'); } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, `${baseUrl}/uploads/getBinaryUploadUrl`); @@ -1007,7 +1023,7 @@ export const ApiGateway = { ) { try { const res = await fetch(`${baseUrl}/uploads/getFlowUploadUrl`, { - body: JSON.stringify({ fileSize, useTus: true }), + body: JSON.stringify({ fileSize, signedUpload: true, useTus: true }), headers: { 'content-type': 'application/json', ...auth.headers, @@ -1018,10 +1034,8 @@ export const ApiGateway = { await this.handleApiError(res, 'Failed to get flow upload URL'); } - // Same response shape as getBinaryUploadUrl: { id, tempPath, finalPath, path, b2?, token? }. - return await parseJsonResponse< - components['schemas']['IGetBinaryUploadUrlResponse'] - >(res, 'Failed to get flow upload URL'); + // Same response shape as getBinaryUploadUrl. + return await parseJsonResponse(res, 'Failed to get flow upload URL'); } catch (error) { if (error instanceof TypeError && error.message === 'fetch failed') { throw this.enhanceFetchError(error, `${baseUrl}/uploads/getFlowUploadUrl`); @@ -1031,6 +1045,39 @@ export const ApiGateway = { } }, + /** + * A fresh signed upload token for a path an upload-URL response gave us, + * so an upload whose token expired can carry on. The API refuses a path + * outside the caller's org and an upload that is already finalised. + */ + async refreshUploadToken(baseUrl: string, auth: AuthContext, path: string): Promise { + try { + const res = await fetch(`${baseUrl}/uploads/refreshUploadToken`, { + body: JSON.stringify({ path }), + headers: { + 'content-type': 'application/json', + ...auth.headers, + }, + method: 'POST', + }); + if (!res.ok) { + await this.handleApiError(res, 'Failed to refresh upload token'); + } + + const { signedUpload } = await parseJsonResponse<{ signedUpload: SignedUpload }>( + res, + 'Failed to refresh upload token', + ); + return signedUpload; + } catch (error) { + if (error instanceof TypeError && error.message === 'fetch failed') { + throw this.enhanceFetchError(error, `${baseUrl}/uploads/refreshUploadToken`); + } + + throw error; + } + }, + /** * Submits a flow test that references an already-uploaded zip (JSON body, no * multipart). The response is identical to the legacy `POST /uploads/flow`. diff --git a/src/gateways/supabase-gateway.ts b/src/gateways/supabase-gateway.ts index fff9211..619687a 100644 --- a/src/gateways/supabase-gateway.ts +++ b/src/gateways/supabase-gateway.ts @@ -14,33 +14,131 @@ export interface ResumableUploadSource { size: number; } +/** + * A signed upload for one storage path, from the API's upload-URL response. + * The token is sent as `x-signature` on every TUS request; it writes only + * `path` and never overwrites an existing object. + */ +export interface SignedUpload { + expiresInSeconds: number; + path: string; + token: string; +} + +/** Refresh this long before the token says it expires. */ +const REFRESH_MARGIN_MS = 10 * 60 * 1000; +/** Fresh tokens one upload may ask for before it gives up. */ +const MAX_TOKEN_REFRESHES = 5; +const RETRY_DELAYS = [0, 3000, 5000, 10_000, 20_000]; + +/** + * Whether a TUS error response says the upload token was refused, which a + * fresh token for the same path fixes. Storage answers an expired or bad + * signature with a 4xx whose body names the JWT or signature. + */ +export function isSignatureError(status: number, body: string): boolean { + return [400, 401, 403].includes(status) && /jwt|signature|expired/i.test(body); +} + +/** tus's own rule: retry anything but a 4xx, except 409 and 423. */ +function defaultShouldRetry(status: number): boolean { + return !(status >= 400 && status < 500) || status === 409 || status === 423; +} + export class SupabaseGateway { /** - * Upload to Supabase using resumable uploads (TUS protocol) - * Uploads to staging location (uploads/{id}/) using the publishable key - * File is later moved to final location by API after finalization - * @param env - Environment (dev or prod) - * @param path - Staging storage path (uploads/{id}/file.ext) - * @param source - Upload source descriptor; the file is streamed from disk - * @param debug - Enable debug logging - * @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal) - * @returns Promise that resolves when upload completes + * Upload straight to the final storage path with a signed token, through + * `/storage/v1/upload/resumable/sign`. No storage key of the client's own + * is needed: the token is the permission. + * + * The token lasts a couple of hours and storage checks it on every + * request, so a long or resumed upload can outlive it. Before each request + * the token is refreshed when it is close to expiry, and a request refused + * for its signature is retried with a fresh one. Either way it is the same + * path, so the same TUS upload carries on. + * + * @param refreshToken - Asks the API for a fresh token for `signed.path` + * @param options.storageUrl - Test seam; defaults to the environment's URL */ - static async uploadResumable( + static async uploadResumableSigned( env: DcdEnvName, - path: string, + signed: SignedUpload, source: ResumableUploadSource, + refreshToken: (path: string) => Promise, debug = false, - onProgress?: (bytesUploaded: number, bytesTotal: number) => void, + options: { retryDelays?: number[]; storageUrl?: string } = {}, ): Promise { - // Prod's Supabase URL is our own custom domain, so customers' networks - // only need to reach devicecloud.dev, not supabase.co. - const storageUrl = ENVIRONMENTS[env].supabase.url; + const storageUrl = options.storageUrl ?? ENVIRONMENTS[env].supabase.url; const supabaseKey = await getSupabaseKey(env); + let { token } = signed; + let expiresAt = Date.now() + signed.expiresInSeconds * 1000; + let stale = false; + let refreshes = 0; + let pending: Promise | undefined; + + const margin = Math.min(REFRESH_MARGIN_MS, (signed.expiresInSeconds * 1000) / 2); + const refresh = (): Promise => { + pending ??= (async () => { + refreshes += 1; + if (debug) console.log(`[DEBUG] Refreshing the upload token for ${signed.path}`); + const fresh = await refreshToken(signed.path); + token = fresh.token; + expiresAt = Date.now() + fresh.expiresInSeconds * 1000; + stale = false; + })().finally(() => { + pending = undefined; + }); + return pending; + }; + + await this.runTusUpload({ + debug, + endpoint: `${storageUrl}/storage/v1/upload/resumable/sign`, + // The gateway in front of Storage routes on the key; the token is the + // permission, and the upload is checked against it, not the key. + headers: supabaseKeyHeaders(supabaseKey), + async onBeforeRequest(req) { + if (stale || Date.now() >= expiresAt - margin) { + await refresh(); + } + + req.setHeader('x-signature', token); + }, + onShouldRetry(err) { + const status = err.originalResponse?.getStatus() ?? 0; + const body = err.originalResponse?.getBody() ?? ''; + if (isSignatureError(status, body)) { + if (refreshes >= MAX_TOKEN_REFRESHES) return false; + stale = true; + return true; + } + + return defaultShouldRetry(status); + }, + path: signed.path, + retryDelays: options.retryDelays ?? RETRY_DELAYS, + source, + }); + } + + /** One TUS upload of `source` to `path` in the organizations bucket. */ + private static runTusUpload(config: { + debug: boolean; + endpoint: string; + headers: Record; + onBeforeRequest?: (req: tus.HttpRequest) => Promise | void; + onProgress?: (bytesUploaded: number, bytesTotal: number) => void; + onShouldRetry?: (err: tus.DetailedError) => boolean; + path: string; + retryDelays: number[]; + source: ResumableUploadSource; + }): Promise { + const { debug, endpoint, headers, onBeforeRequest, onProgress, onShouldRetry, path, retryDelays, source } = config; + if (debug) { console.log(`[DEBUG] Resumable upload starting...`); - console.log(`[DEBUG] Storage URL: ${storageUrl}`); + console.log(`[DEBUG] Endpoint: ${endpoint}`); console.log(`[DEBUG] Upload path: ${path}`); console.log(`[DEBUG] File name: ${source.name}`); console.log(`[DEBUG] File size: ${(source.size / 1024 / 1024).toFixed(2)} MB`); @@ -56,18 +154,11 @@ export class SupabaseGateway { // Bun's node:http can't send tus's create request; see FetchHttpStack. ...tusHttpStackOptions(), - // TUS endpoint for Supabase Storage - endpoint: `${storageUrl}/storage/v1/upload/resumable`, - - // Retry configuration - will retry 5 times with increasing delays - retryDelays: [0, 3000, 5000, 10_000, 20_000], - - // Authentication and headers - // Publishable key for staging uploads to uploads/* folder - headers: { - ...supabaseKeyHeaders(supabaseKey), - 'x-upsert': 'true', // Allow overwriting existing files - }, + endpoint, + retryDelays, + headers, + ...(onBeforeRequest ? { onBeforeRequest } : {}), + ...(onShouldRetry ? { onShouldRetry } : {}), // Upload metadata metadata: { @@ -134,4 +225,42 @@ export class SupabaseGateway { upload.start(); }); } + + /** + * Upload to Supabase using resumable uploads (TUS protocol) + * Uploads to staging location (uploads/{id}/) using the publishable key + * File is later moved to final location by API after finalization + * @param env - Environment (dev or prod) + * @param path - Staging storage path (uploads/{id}/file.ext) + * @param source - Upload source descriptor; the file is streamed from disk + * @param debug - Enable debug logging + * @param onProgress - Optional callback for upload progress (bytesUploaded, bytesTotal) + * @returns Promise that resolves when upload completes + */ + static async uploadResumable( + env: DcdEnvName, + path: string, + source: ResumableUploadSource, + debug = false, + onProgress?: (bytesUploaded: number, bytesTotal: number) => void, + ): Promise { + // Prod's Supabase URL is our own custom domain, so customers' networks + // only need to reach devicecloud.dev, not supabase.co. + const storageUrl = ENVIRONMENTS[env].supabase.url; + const supabaseKey = await getSupabaseKey(env); + + return this.runTusUpload({ + debug, + endpoint: `${storageUrl}/storage/v1/upload/resumable`, + // Publishable key for staging uploads to uploads/* folder + headers: { + ...supabaseKeyHeaders(supabaseKey), + 'x-upsert': 'true', // Allow overwriting existing files + }, + onProgress, + path, + retryDelays: RETRY_DELAYS, + source, + }); + } } diff --git a/src/methods.ts b/src/methods.ts index d437c8c..c1183d5 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -16,7 +16,7 @@ import * as yazl from 'yazl'; import { inferEnvFromApiUrl } from './config/environments.js'; import { ApiError, ApiGateway } from './gateways/api-gateway.js'; -import { SupabaseGateway } from './gateways/supabase-gateway.js'; +import { type SignedUpload, SupabaseGateway } from './gateways/supabase-gateway.js'; import { detectFlutterEngine, MetadataExtractorService, @@ -603,6 +603,63 @@ async function uploadToSupabase( } } +/** + * Where the Supabase copy went, and so which path to finalise with. + * `direct` means `path` is the final path a signed token uploaded to. + */ +export interface SupabaseUploadOutcome { + direct: boolean; + path: string; + result: UploadResult; +} + +/** + * Upload the Supabase copy. When the API offered a signed upload, go straight + * to the final path, so the API has nothing to copy when it finalises. If + * that fails, or none was offered, upload to the temp path as before. + * + * When everything fails, `path` is the temp path, which an API finalising a + * Backblaze-only upload accepts from any client. + */ +export async function uploadSupabaseCopy(config: { + apiUrl: string; + auth: AuthContext; + debug: boolean; + env: 'dev' | 'prod'; + signedUpload?: SignedUpload; + source: UploadSource; + tempPath: string; +}): Promise { + const { apiUrl, auth, debug, env, signedUpload, source, tempPath } = config; + + if (signedUpload?.path && signedUpload.token) { + if (debug) { + console.log(`[DEBUG] Uploading to Supabase (${env}) straight to the final path with a signed token`); + console.log(`[DEBUG] Final path: ${signedUpload.path}`); + } + + try { + await SupabaseGateway.uploadResumableSigned( + env, + signedUpload, + source, + (signedPath) => ApiGateway.refreshUploadToken(apiUrl, auth, signedPath), + debug, + ); + return { direct: true, path: signedUpload.path, result: { error: null, success: true } }; + } catch (error) { + if (debug) { + console.error( + `[DEBUG] Signed upload failed, falling back to the temp path: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + } + + const result = await uploadToSupabase(env, tempPath, source, debug); + return { direct: false, path: tempPath, result }; +} + interface BackblazeUploadConfig { auth: AuthContext; apiUrl: string; @@ -692,6 +749,7 @@ interface UploadPaths { b2: unknown; finalPath: string; id: string; + signedUpload?: SignedUpload; tempPath: string; } @@ -720,7 +778,12 @@ async function requestUploadPaths( try { const urlRequestStartTime = Date.now(); - const { id, tempPath, finalPath, b2 } = await ApiGateway.getBinaryUploadUrl(apiUrl, auth, platform, fileSize); + const { id, tempPath, finalPath, b2, signedUpload } = await ApiGateway.getBinaryUploadUrl( + apiUrl, + auth, + platform, + fileSize, + ); if (debug) { const hasStrategy = b2 && typeof b2 === 'object' && 'strategy' in b2; @@ -729,12 +792,13 @@ async function requestUploadPaths( console.log(`[DEBUG] Temp path (TUS upload): ${tempPath}`); console.log(`[DEBUG] Final path (after finalize): ${finalPath}`); console.log(`[DEBUG] Backblaze upload URL provided: ${Boolean(b2)}`); + console.log(`[DEBUG] Signed upload offered: ${Boolean(signedUpload)}`); if (hasStrategy) console.log(`[DEBUG] Backblaze strategy: ${(b2 as { strategy: string }).strategy}`); } if (!tempPath) throw new Error('No upload path provided by API'); - return { b2, finalPath, id, tempPath }; + return { b2, finalPath, id, signedUpload, tempPath }; } catch (error) { if (debug) { console.error('[DEBUG] === FAILED TO GET UPLOAD URL ==='); @@ -833,7 +897,13 @@ async function performUpload(config: PerformUploadConfig): Promise { const { filePath, apiUrl, auth, enc, source, sha, shaPlain, debug, startTime } = config; // Request upload URL and paths - const { id, tempPath, finalPath, b2 } = await requestUploadPaths(apiUrl, auth, filePath, source.size, debug); + const { id, tempPath, finalPath, b2, signedUpload } = await requestUploadPaths( + apiUrl, + auth, + filePath, + source.size, + debug, + ); // Extract app metadata from the original (plaintext) file. Attach the // envelope so it lands on binaries.metadata.enc (#1138). @@ -871,7 +941,8 @@ async function performUpload(config: PerformUploadConfig): Promise { console.log('[DEBUG] Uploading to Supabase...'); } - const supabaseResult: UploadResult = await uploadToSupabase(env, tempPath, source, debug); + const supabase = await uploadSupabaseCopy({ apiUrl, auth, debug, env, signedUpload, source, tempPath }); + const supabaseResult: UploadResult = supabase.result; // Validate results validateUploadResults(supabaseResult, backblazeResult, b2, debug); @@ -881,8 +952,11 @@ async function performUpload(config: PerformUploadConfig): Promise { console.log(`[DEBUG] Upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`); console.log('[DEBUG] Finalizing upload...'); console.log(`[DEBUG] Target endpoint: ${apiUrl}/uploads/finaliseUpload`); - console.log(`[DEBUG] Uploaded to staging path: ${tempPath}`); - console.log(`[DEBUG] API will move to final path: ${finalPath}`); + console.log( + supabase.direct + ? `[DEBUG] Uploaded straight to final path: ${supabase.path}` + : `[DEBUG] Uploaded to staging path: ${tempPath}; API will move it to ${finalPath}`, + ); console.log(`[DEBUG] Backblaze upload status: ${backblazeResult.success ? 'SUCCESS' : 'FAILED'}`); console.log(`[DEBUG] Supabase upload status: ${supabaseResult.success ? 'SUCCESS' : 'FAILED'}`); if (!backblazeResult.success && supabaseResult.success) console.log('[DEBUG] ⚠ Warning: File only exists in Supabase (Backblaze failed)'); @@ -897,11 +971,12 @@ async function performUpload(config: PerformUploadConfig): Promise { bytes: source.size, id, metadata, - path: tempPath, + path: supabase.path, // sha is undefined when hash calculation failed — omit it explicitly ...(sha ? { sha } : {}), ...(shaPlain ? { shaPlain } : {}), supabaseSuccess: supabaseResult.success, + ...(supabase.direct ? { useTus: true } : {}), }); if (debug) { @@ -962,7 +1037,7 @@ export const uploadFlowZip = async (config: { // Same response shape as getBinaryUploadUrl. A 404 here means the API // predates the client-direct flow path — let it propagate so the caller // falls back to the multipart endpoint. - const { id, tempPath, finalPath, b2 } = await ApiGateway.getFlowUploadUrl( + const { id, tempPath, finalPath, b2, signedUpload } = await ApiGateway.getFlowUploadUrl( apiUrl, auth, buffer.length, @@ -983,7 +1058,8 @@ export const uploadFlowZip = async (config: { }); // Always upload to Supabase (always-on alongside Backblaze) - const supabaseResult = await uploadToSupabase(env, tempPath, source, debug); + const supabase = await uploadSupabaseCopy({ apiUrl, auth, debug, env, signedUpload, source, tempPath }); + const supabaseResult = supabase.result; validateUploadResults(supabaseResult, backblazeResult, b2, debug); @@ -995,7 +1071,8 @@ export const uploadFlowZip = async (config: { backblazeSuccess: backblazeResult.success, bytes: buffer.length, id, - path: tempPath, + // The signed final path or the temp path; submitFlowTest takes either. + path: supabase.path, supabaseSuccess: supabaseResult.success, useTus: true, }; diff --git a/test/unit/signed-upload.test.ts b/test/unit/signed-upload.test.ts new file mode 100644 index 0000000..8793ee2 --- /dev/null +++ b/test/unit/signed-upload.test.ts @@ -0,0 +1,293 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { resetCliConfigCache } from '../../src/config/cli-config.js'; +import { ApiGateway } from '../../src/gateways/api-gateway.js'; +import { + isSignatureError, + type SignedUpload, + SupabaseGateway, +} from '../../src/gateways/supabase-gateway.js'; +import { uploadSupabaseCopy } from '../../src/methods.js'; + +/** + * Uploads straight to the final storage path with a signed token. Storage + * checks the token on every TUS request, so the client has to send it as + * `x-signature` each time, and get a fresh one when it is refused or about + * to expire. + */ + +interface SeenRequest { + method: string; + objectName?: string; + signature?: string; + upsert?: string; + url: string; +} + +/** Decode tus's `Upload-Metadata` header (`key base64,key base64`). */ +function objectNameOf(header: string | undefined): string | undefined { + for (const pair of (header ?? '').split(',')) { + const [key, value] = pair.trim().split(' '); + if (key === 'objectName' && value) return Buffer.from(value, 'base64').toString(); + } + + return undefined; +} + +/** + * A minimal TUS server: creation with data in one request, which is all a + * file smaller than one chunk needs. `refuse` decides, per request, whether + * to answer like Storage does for a bad signature. + */ +function startTusServer(refuse: (signature: string | undefined, n: number) => boolean): Promise<{ + seen: SeenRequest[]; + server: Server; + url: string; +}> { + const seen: SeenRequest[] = []; + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const signature = req.headers['x-signature'] as string | undefined; + seen.push({ + method: req.method ?? '', + objectName: objectNameOf(req.headers['upload-metadata'] as string | undefined), + signature, + upsert: req.headers['x-upsert'] as string | undefined, + url: req.url ?? '', + }); + + res.setHeader('Tus-Resumable', '1.0.0'); + if (refuse(signature, seen.length)) { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'InvalidJWT', message: 'jwt expired', statusCode: '400' })); + return; + } + + const received = Buffer.concat(chunks).length; + res.writeHead(201, { + Location: `${req.url}/upload-1`, + 'Upload-Offset': String(received), + }); + res.end(); + }); + }); + + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as AddressInfo; + resolve({ seen, server, url: `http://127.0.0.1:${port}` }); + }); + }); +} + +describe('isSignatureError', () => { + it('spots a refused token', () => { + expect(isSignatureError(400, '{"error":"InvalidJWT","message":"jwt expired"}')).to.equal(true); + expect(isSignatureError(403, 'invalid signature')).to.equal(true); + }); + + it('leaves other failures alone', () => { + expect(isSignatureError(500, 'jwt expired')).to.equal(false); + expect(isSignatureError(400, 'The resource already exists')).to.equal(false); + }); +}); + +describe('SupabaseGateway.uploadResumableSigned', () => { + const realFetch = globalThis.fetch; + let tempDir: string; + let source: { contentType: string; diskPath: string; name: string; size: number }; + let server: Server | undefined; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-signed-upload-')); + const diskPath = path.join(tempDir, 'app.apk'); + fs.writeFileSync(diskPath, Buffer.alloc(1024, 7)); + source = { contentType: 'application/vnd.android.package-archive', diskPath, name: 'app.apk', size: 1024 }; + + // The publishable key comes from the API's /cli-config. + resetCliConfigCache(); + globalThis.fetch = (async () => + new Response(JSON.stringify({ supabase_publishable_key: 'sb_publishable_test' }), { + headers: { 'content-type': 'application/json' }, + })) as typeof fetch; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + resetCliConfigCache(); + server?.close(); + server = undefined; + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + const signed: SignedUpload = { expiresInSeconds: 7200, path: '1/binaries/android/abc.apk', token: 't1' }; + + it('sends the token to the signed endpoint for the final path, without upsert', async () => { + const tus = await startTusServer(() => false); + server = tus.server; + + await SupabaseGateway.uploadResumableSigned('dev', signed, source, async () => { + throw new Error('no refresh expected'); + }, false, { storageUrl: tus.url }); + + expect(tus.seen).to.have.length(1); + expect(tus.seen[0]).to.include({ + method: 'POST', + objectName: '1/binaries/android/abc.apk', + signature: 't1', + url: '/storage/v1/upload/resumable/sign', + }); + expect(tus.seen[0].upsert).to.equal(undefined); + }); + + it('gets a fresh token and carries on when the token is refused', async () => { + const tus = await startTusServer((signature) => signature === 't1'); + server = tus.server; + const refreshed: string[] = []; + + await SupabaseGateway.uploadResumableSigned( + 'dev', + signed, + source, + async (p) => { + refreshed.push(p); + return { ...signed, token: 't2' }; + }, + false, + { retryDelays: [0, 0, 0], storageUrl: tus.url }, + ); + + expect(refreshed).to.deep.equal(['1/binaries/android/abc.apk']); + expect(tus.seen.map((r) => r.signature)).to.deep.equal(['t1', 't2']); + }); + + it('refreshes before the first request when the token is about to expire', async () => { + const tus = await startTusServer(() => false); + server = tus.server; + + await SupabaseGateway.uploadResumableSigned( + 'dev', + { ...signed, expiresInSeconds: 0 }, + source, + async () => ({ ...signed, token: 'fresh' }), + false, + { storageUrl: tus.url }, + ); + + expect(tus.seen.map((r) => r.signature)).to.deep.equal(['fresh']); + }); + + it('gives up after a bounded number of refreshes', async () => { + const tus = await startTusServer(() => true); + server = tus.server; + let refreshes = 0; + + let failure: unknown; + try { + await SupabaseGateway.uploadResumableSigned( + 'dev', + signed, + source, + async () => { + refreshes += 1; + return { ...signed, token: `t${refreshes + 1}` }; + }, + false, + { retryDelays: Array.from({ length: 20 }, () => 0), storageUrl: tus.url }, + ); + } catch (error) { + failure = error; + } + + expect(failure).to.be.instanceOf(Error); + expect(refreshes).to.equal(5); + }); +}); + +describe('uploadSupabaseCopy', () => { + const realSigned = SupabaseGateway.uploadResumableSigned; + const realTemp = SupabaseGateway.uploadResumable; + const realRefresh = ApiGateway.refreshUploadToken; + let calls: string[]; + + const base = { + apiUrl: 'http://localhost:9999', + auth: { headers: {} } as never, + debug: false, + env: 'dev' as const, + source: { contentType: 'application/zip', diskPath: '/nowhere', name: 'f.zip', size: 1 }, + tempPath: 'uploads/abc/abc.zip', + }; + const signedUpload: SignedUpload = { expiresInSeconds: 7200, path: '1/tests/abc.zip', token: 't' }; + + beforeEach(() => { + calls = []; + SupabaseGateway.uploadResumable = (async (_env: string, p: string) => { + calls.push(`temp:${p}`); + }) as typeof SupabaseGateway.uploadResumable; + }); + + afterEach(() => { + SupabaseGateway.uploadResumableSigned = realSigned; + SupabaseGateway.uploadResumable = realTemp; + ApiGateway.refreshUploadToken = realRefresh; + }); + + it('goes straight to the final path when a signed upload is offered', async () => { + SupabaseGateway.uploadResumableSigned = (async (_env: string, s: SignedUpload) => { + calls.push(`signed:${s.path}`); + }) as typeof SupabaseGateway.uploadResumableSigned; + + const outcome = await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(outcome).to.deep.equal({ direct: true, path: '1/tests/abc.zip', result: { error: null, success: true } }); + expect(calls).to.deep.equal(['signed:1/tests/abc.zip']); + }); + + it('asks the API for a fresh token for the same path', async () => { + let refreshedFor: string | undefined; + ApiGateway.refreshUploadToken = (async (_url: string, _auth: unknown, p: string) => { + refreshedFor = p; + return signedUpload; + }) as typeof ApiGateway.refreshUploadToken; + SupabaseGateway.uploadResumableSigned = (async ( + _env: string, + s: SignedUpload, + _source: unknown, + refresh: (p: string) => Promise, + ) => { + await refresh(s.path); + }) as typeof SupabaseGateway.uploadResumableSigned; + + await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(refreshedFor).to.equal('1/tests/abc.zip'); + }); + + it('falls back to the temp path when the signed upload fails', async () => { + SupabaseGateway.uploadResumableSigned = (async () => { + throw new Error('refused'); + }) as typeof SupabaseGateway.uploadResumableSigned; + + const outcome = await uploadSupabaseCopy({ ...base, signedUpload }); + + expect(outcome.direct).to.equal(false); + expect(outcome.path).to.equal('uploads/abc/abc.zip'); + expect(outcome.result.success).to.equal(true); + expect(calls).to.deep.equal(['temp:uploads/abc/abc.zip']); + }); + + it('uses the temp path when no signed upload is offered', async () => { + const outcome = await uploadSupabaseCopy(base); + + expect(outcome.direct).to.equal(false); + expect(calls).to.deep.equal(['temp:uploads/abc/abc.zip']); + }); +});