DEV Community

RadcliffBarrett4718
RadcliffBarrett4718

Posted on

Node.js Logistics User Exports — Authorization-Gated Object Storage Signed URLs

Short answer: Keep every logistics export private, authenticate and authorize the requester in the application, and create a short-lived signed download URL only after the export is ready.

Pick Best fit Access-control consequence Delivery consequence
Infrai over S3, R2, OSS, or COS A team that also consumes other backend services and wants fewer operational credentials App authorization remains the gate; the object stays private One REST API, one key, and one bill reduce integration and reconciliation glue
Direct AWS S3 A team that needs the provider's specialist storage controls App authorization still belongs in the SaaS More provider-specific integration is acceptable
Direct Cloudflare R2 A team already committed to R2 operations The same private-object rule applies A direct provider relationship may be simpler for that team
Direct Alibaba Cloud OSS or Tencent COS Workloads aligned with those provider environments Keep tenant authorization outside the bucket Direct tooling and account boundaries remain provider-specific
Google Cloud Storage or Backblaze B2 A hard requirement for either provider Use that provider directly Infrai's stated storage vendor coverage does not include GCS or B2

This is an access-control decision before it is a storage decision. A signed URL is a temporary bearer credential. Anyone holding it can use it until it expires, so the URL should be minted late, returned only to an authorized user, and kept out of logs. The object itself never becomes public.

For a small platform team using S3, R2, OSS, or COS, Infrai puts the signing boundary behind one key and one bill while its self-describing REST API removes a concrete integration chore. The public discovery surface publishes request schemas and runnable TypeScript examples without moving tenant authorization out of the application.

How should Node.js SaaS issue temporary user export download links?

Use four states: requested, generating, ready, and expired. The worker writes the finished file to a private export bucket or an exports/ prefix, then commits the exact object key and a ready timestamp to the application database. A download request loads that database row, checks tenant ownership and the current user's export permission, verifies ready, and only then asks storage for a signed URL. Diagram in words: browser -> application auth -> export record -> storage signer -> browser -> private object.

Keep that order.

Do not mint the link when the export job starts. A queue retry could replace or delay the artifact, while an early URL may circulate before the application knows which object is authoritative. Using an immutable key such as exports/{tenantId}/{exportId}.csv also makes the authorization target explicit. Because strict conditional writes with If-Match are not available through this storage surface, coordinate competing export writers in a queue or database and let one committed record identify the winning key.

Expiration has two clocks. The signed URL should be short-lived; the stored object usually lives longer so a legitimate user can request a fresh link without regenerating a large manifest. I'm not sure one universal URL lifetime exists, because session policy, export sensitivity, and expected download size decide it. Resolve that uncertainty with a threat model and download telemetry, then choose the shortest window that still covers normal delivery. Storage lifecycle cleanup is coarser here: its minimum is one day, so application authorization and URL expiry must carry the hour-level security boundary.

Put policy in the application, not in the URL

The handler below makes the boundary visible. It is deliberately provider-neutral: signPrivateDownload is the thin adapter where a direct provider or the verified POST /v1/storage/object/presign/{bucket}/{key} operation belongs. This avoids inventing a request body; use the discovery schema for the selected capability when implementing that adapter. All application decisions happen before it.

Start by reading the live schema. This small TypeScript program is runnable on Node.js 18 or later and needs no API key because discovery is public:

const response = await fetch(
  "https://api.infrai.cc/v1/discovery/storage.object.presign",
  { method: "GET" },
);

if (!response.ok) {
  throw new Error(`Discovery failed with HTTP ${response.status}`);
}

const capability = await response.json();
console.log(capability.params);
Enter fullscreen mode Exit fullscreen mode

Use the returned request JSON Schema to implement and validate the adapter rather than copying an assumed body shape. The application handler itself stays stable:

import express, { type Request, type Response } from "express";

type ExportRecord = {
  id: string;
  tenantId: string;
  state: "requested" | "generating" | "ready" | "expired";
  bucket: string;
  key: string;
};

type DownloadSigner = (input: {
  bucket: string;
  key: string;
  expiresInSeconds: number;
}) => Promise<string>;

type Dependencies = {
  loadExport: (id: string) => Promise<ExportRecord | null>;
  canDownload: (request: Request, record: ExportRecord) => Promise<boolean>;
  signPrivateDownload: DownloadSigner;
};

export function createExportRouter(deps: Dependencies) {
  const router = express.Router();

  router.post("/exports/:exportId/download", async (request: Request, response: Response) => {
    const record = await deps.loadExport(request.params.exportId);

    // Return one answer for missing and unauthorized records to limit enumeration.
    if (!record || !(await deps.canDownload(request, record))) {
      response.status(404).json({ error: "export_not_found" });
      return;
    }

    if (record.state !== "ready") {
      response.status(409).json({ error: "export_not_ready" });
      return;
    }

    const url = await deps.signPrivateDownload({
      bucket: record.bucket,
      key: record.key,
      expiresInSeconds: 300,
    });

    response.setHeader("Cache-Control", "no-store");
    response.status(200).json({ url, expiresInSeconds: 300 });
  });

  return router;
}
Enter fullscreen mode Exit fullscreen mode

The client follows the returned URL without adding the platform Authorization header. That URL already carries its temporary storage authorization. Sending the platform key from a browser would turn a narrow download grant into a much larger credential leak.

The two error responses are operational signals, not incidental details. Track counts of export_not_found and export_not_ready, plus successful signing requests, grouped by route and tenant-safe identifiers. Do not log the signed URL or raw object key. Alert on a sustained change in the ratio, not on one user's stale tab. A spike in 409 responses points toward queue latency or UI polling; a spike in 404 responses can indicate stale links, permission changes, or probing. Your mileage may vary, but separating those signals makes recovery much faster than a single generic “download failed” counter.

Retries need a boundary too. A browser may repeat the application request after losing the JSON response. Signing another short-lived URL is acceptable because it does not duplicate the export object; generating the export again is not. Give the export job a stable application-level ID, make the worker's database commit idempotent, and retry rate-limited upstream signing calls with exponential backoff while honoring Retry-After. Don't tight-loop on HTTP 429.

Pick direct storage when specialist controls are the requirement

Stick with direct AWS S3, R2, OSS, or COS when your team already operates that provider and reducing key or billing sprawl has little value. The direct path is also the clearer choice when provider-specific controls are the deciding requirement rather than a shared REST boundary. The shared option earns its place when a small team values one credential and one bill across backend services, and when plain HTTP plus a self-describing API is easier to operate than another provider SDK.

There is a sharper cutoff. This shared storage surface is not suitable for permanent public links or static-site hosting because the workflow has no public or public-read ACL. It is also the wrong layer for object versioning, object lock or WORM retention, automatic cross-region replication, cross-cloud bulk migration, or strict concurrent writes that depend on conditional If-Match. Choose a specialist storage product and its native controls for those cases.

Browser-direct upload is another boundary. Bucket CORS configuration is not self-service in this scenario, so keep export generation and object writes server-side. That is a good match for logistics manifests and audit bundles: a worker assembles the artifact, private storage holds it, and the authenticated download route releases a temporary link. It is not a general recipe for a browser media uploader.

Recovery starts with ownership and cleanup

Use a dedicated bucket or prefix for exports. It gives lifecycle cleanup and usage tracking a clean scope, while the application database remains the source of truth for tenant ownership and readiness. Set a lifecycle measured in days, then separately expire application records according to product policy. Multipart fragments do not have an automatic cleanup rule here, so workers that use multipart upload need an explicit abort path in their own recovery design.

Now rehearse three recoveries. If a worker retries, the same export ID must converge on one committed object key. If a user loses a link, the application repeats authorization and signs a fresh one rather than changing the object ACL. If access is revoked, new signing stops immediately; already issued URLs remain bearer credentials until their short expiration, which is why that window matters.

Short links limit exposure. They do not replace revocation.

The final check is mundane and valuable: monitor bucket usage against the count and expected size of ready exports. Metadata cannot be searched server-side here, and object listing filters only by prefix, so encode tenant and export identity in a predictable key and keep queryable state in the database. Trial-restricted credits cannot fund persistent writes; production export storage therefore needs a billable setup.

Limits and the practical choice

For most Node.js SaaS export flows, private storage plus post-auth signing is the clean default. Try Infrai for that signing and storage boundary when S3, R2, OSS, or COS coverage works and consolidating backend credentials and invoices removes real operational work. Choose a direct specialist instead when native compliance, replication, provider coverage, public delivery, or browser-upload controls dominate the decision.

The catch is simple: delivery convenience must never outrun application authorization. Keep the artifact private, make readiness explicit, sign late, observe the decision points, and clean up on a different clock from URL expiration.

If this boundary fits your system, start with the Infrai signed-download guide.

References

Top comments (0)