wildhart:dynamic-import-auth

v1.0.0•Published last month

wildhart:dynamic-import-auth

Require a logged-in user for /__meteor__/dynamic-import/fetch, the endpoint every import() in a Meteor client goes through. Out of the box that endpoint is public: anyone can POST a module tree and receive the compiled source of any lazily loaded module (route components, client-side PDF generators, method stubs, test fixtures) without logging in. Meteor's own dynamic-versions.js in the main bundle even lists the paths.

This package puts a check in front of it. Logged-in users are unaffected; everyone else gets 401.

Requirements

  • Meteor 3.5.0 or later: accounts-base 3.3.0 (the HttpOnly login cookie flow) and accounts-express 1.0.0 (createAuthMiddleware) both first shipped in 3.5.0. Prefer 3.5.2 or later: its accounts-base 3.3.1 only exposes the /_accounts/cookie/* endpoints when useHttpOnlyCookies is on and rejects oversized bodies, and 3.5.1 fixed a race in the cookie login completion.
  • Browser and desktop-webview clients on the same origin as the server. Cordova is not supported: the webview is cross-origin, so the browser does not send the cookie and every import would be rejected.

Setup

  1. meteor add accounts-express wildhart:dynamic-import-auth
  2. In Meteor.settings:
1{
2	"public": {
3		"packages": {
4			"accounts": {"useHttpOnlyCookies": true},
5			"dynamic-import": {"useLocationOrigin": true}
6		}
7	}
8}
  • useHttpOnlyCookies makes accounts-base keep a meteor_login_token HttpOnly cookie (Path=/; SameSite=Lax; Secure on https) in sync with the login state. The browser sends it with dynamic-import's same-origin fetch. Without it nothing has a cookie and every import is rejected (the package warns on startup).
  • useLocationOrigin makes the client fetch from the page's own origin instead of ROOT_URL. If your app can be reached on a host that differs from ROOT_URL (a bare domain vs www, a dev tunnel), the fetch would be cross-origin and the cookie would not be sent. The package warns on startup when it detects the mismatch.

What the client must do: never fetch while logged out

Nothing pre-login may need a gated chunk. Two rules:

  1. Pages that logged-out users open (sign-in, password reset, enrolment, a public landing page) must be in the main bundle. A module that is imported statically anywhere in eager code is never a dynamic chunk, so keep the route's import() and add one static import somewhere eager:

    1import '/imports/ui/Enroll.vue'; // eager: reset-password links are opened while logged out
  2. Deep links to authenticated routes. vue-router resolves a route's async component before it confirms the navigation, so a logged-out visit to /projects fetches Projects.vue before your app can show its sign-in form. If that fetch is rejected the initial navigation never completes. Wrap the loaders of authenticated routes:

    1import { deferUntilLoggedIn } from 'meteor/wildhart:dynamic-import-auth';
    2
    3{path: '/projects', component: deferUntilLoggedIn(() => import('/imports/ui/Projects.vue')), meta: {auth: true}}

    While logged out the wrapper waits for the login and only then runs the real import(), so the navigation stays pending. Your app must show its sign-in UI while a navigation is pending and nobody is logged in (with vue-router that state is "$route is still the previous route"; a beforeEach that sets a "loading" flag is the usual hook, e.g. v-if="loadingRoute && !Meteor.userId() && !Meteor.loggingIn()" renders the sign-in form instead of a spinner). Once the user logs in the import runs, the navigation completes and the page renders with its route props and in-component guards intact. When logged in the wrapper loads immediately.

    What "logged in" means here: accounts-base sets Meteor.userId() and only then awaits the cookie POST, so an import fired in that gap gets a 401; Meteor.loggingIn() turns false after the cookie landed, and the wrapper waits for both (isLoggedInForFetch()). That also covers the startup resume login of a user who was already logged in when this package was first deployed: their token is in localStorage but there is no cookie until that first login completes.

    Offline: a client that holds a token but whose connection is down and not being attempted (Meteor.status() is waiting, failed or offline) does not wait - the login it would wait for cannot complete without a connection - and runs the import() straight away (isReadyToFetch()). The fetch never reaches the server, so an offline-capable app serves the chunk from its service worker or dynamic-import cache, or the import fails and is retried below once the connection and the login are back. connecting is not treated as offline: the login may be seconds away, and a fetch fired then would just be rejected.

    Retries: a rejected import is logged ([dynamic-import-auth] <name> rejected (HTTP 401), retry 1 of 5 in 500ms), the wrapper backs off (doubling from retryDelayMs, capped at maxRetryDelayMs), waits until it is ready to fetch again and retries, up to retries times (default 5), before logging an error and rejecting. Options: deferUntilLoggedIn(loader, {retries, retryDelayMs, maxRetryDelayMs, name}); name defaults to the file name in the loader's import() call (read from the loader's source, which survives minification).

  3. Components rendered before login completes. Anything lazy in your root layout (an app bar item, a status badge, a global dialog) is requested on the very first render, well before the startup resume login has set the cookie. Wrap those loaders too. Without the wrapper the first load after a deploy - new module hashes, so nothing is cached - gets a 401, and a Vue 2 async component whose promise rejects renders nothing for the rest of the session, never retries and only warns in development:

    1components: {
    2	SyncStatus: deferUntilLoggedIn(() => import('/imports/ui/SyncStatus.vue')),
    3}

Anything else that imports lazily before login (a toast helper, an analytics chunk) either gets a static import or shows up as a [dynamic-import-auth] denied ... line in the server log. Watch that log after deploying: apart from the burst of old clients right after the first deploy (below), every line is either an attacker or a pre-login import to fix.

First deploy: clients still running the old code

When the package first goes live, every open tab is still running the previous build:

  • It has no login cookie. A page keeps the Meteor.settings.public it was loaded with, so in those tabs useHttpOnlyCookies is still off and accounts-base never sets the cookie. Every import() of a module the tab has not fetched yet gets a 401. Modules it already has (in memory or in dynamic-import's IndexedDB cache) do not touch the server and keep working.
  • It has no deferUntilLoggedIn. A rejected import is not retried: a lazy route fails to navigate, and a Vue 2 async component renders nothing until the page is reloaded.

Usually this lasts seconds. The deploy restarts the server, the client reconnects, autoupdate sees a new client version and reloads the page, and the new client's startup resume login sets the cookie (accounts-base syncs it on every login, resume included) while deferUntilLoggedIn waits for it. It lasts longer when:

  • the user opens a not-yet-loaded route between the reconnect and the reload;
  • the app defers hot code push (Reload._onMigrate, a "new version available - reload" prompt): such a tab stays broken for every lazy route it has not loaded until the user reloads;
  • a tab is backgrounded or offline, and only picks up the new version when it reconnects.

These requests also produce a burst of denied lines right after the deploy. They are your own users (referer on your own origin, timestamps around the deploy), not attackers.

To avoid all of this, roll out in two deploys:

  1. Deploy the settings, the deferUntilLoggedIn wrappers and the package in report-only mode:

    1DynamicImportAuth.configure({enforce: false});

    Requests that fail the check are logged (would deny (enforce: false) ...) and passed to onDenied with {enforced: false}, but still served. Every client reloads onto code that sets the cookie and waits for it.

  2. Watch the log. Once the old tabs have reloaded, the remaining would deny lines are attackers and pre-login imports still to fix (rules 1 and 3 above). Fix those, then remove enforce: false and deploy again.

Server API

1import { DynamicImportAuth } from 'meteor/wildhart:dynamic-import-auth';
2
3DynamicImportAuth.configure({
4	// extra check for logged-in users, e.g. roles. Default: every logged-in user may fetch.
5	authorize: async (userId, req) => true,
6	// called for every request that fails the check, with the module paths it asked for. `enforced` is false in
7	// report-only mode. Default: one console.warn line with method, url, address, referer and the paths.
8	onDenied: (req, imports, {enforced}) => {},
9	// let `?key=...` requests from a loopback address through (the server's own dynamic import()). Default false:
10	// app code cannot verify the key, and in dev behind a tunnel every request is loopback.
11	allowServerImports: false,
12	// false = report-only: failing requests are reported but still served. For the first deploy, see above.
13	enforce: true,
14});

The check does not read the request body to decide, so authorize cannot see which modules were requested; it gates the whole endpoint per user. A rejected request's body is read afterwards (dynamic-import never sees that request) so the log line and onDenied can list the module paths. In report-only mode the body is recorded as dynamic-import reads it, and onDenied runs once that read is complete. Rejections are 401 with the JSON string "login required" (a string so that a service worker which stores the keys of every fetch response stores nothing).

What this does not protect

Only import()-loaded modules go through the endpoint. Everything in the main bundle stays public whatever this package does, including method stubs and shared code that is imported statically. Move server logic into server-only modules for those; meteor --production --extra-packages bundle-visualizer shows what is eager.

Testing

meteor test-packages ./ --settings tests/settings.json

then open http://localhost:3000. The server tests make real HTTP requests to the fetch endpoint (no token, cookie, Bearer, expired token, authorize, onDenied, allowServerImports, enforce: false); the client tests cover the readiness checks and deferUntilLoggedIn, plus one end-to-end check that the browser's HttpOnly login cookie gets a chunk through.

How it works

dynamic-import mounts its handler on WebAppInternals.meteorInternalHandlers, which runs before WebApp.handlers. WebApp.rawConnectHandlers is a separate Express app mounted ahead of everything, so this package mounts its check there (module-level, no startup ordering involved) and passes OPTIONS and anything that is not POST straight through. The check itself is createAuthMiddleware({required: false}) from accounts-express, which parses the Cookie header itself (cookieParser has not run yet at that point), looks up the hashed token and its expiry, and sets req.userId.