Cover reading null <= 0 is true above the title The Upgrade That Locks You Out
Short answer

Two finished-looking repos hide boundary bugs a demo never shows. In web-chilihub, JSON turns Infinity into null so Pro users hit the free limit, scans fail to save behind a success screen, any user can set their own plan through Supabase, and the Stripe webhook can drop an upgrade. In macrame, the checkout button only calls canLaunchUrl, login accepts anything and the privacy link points at another company's site. Test the paid path, restarts, failed saves, your own table permissions and every promise on your pricing page.

Open src/app/(dashboard)/scan/page.tsx in web-chilihub and look at line 40. It's the check that stops a user who has run out of scans. On a free account it works as written. On a Pro account, the plan that promises unlimited scans, the same line blocks every scan with "Scan limit reached. Upgrade to Pro for unlimited scans."

The cause is one JavaScript rule: JSON.stringify turns Infinity into null, and null <= 0 is true. The demo never shows this, because nobody demos a paid account after paying.

This post reviews two of my own public repos. web-chilihub is a Next.js app for chili farmers from March 2026 with one later commit in May, and its plan file opens with instructions addressed to Claude. macrame is a Flutter craft shop from January 2024. Both look finished when you click through them. Both have the kind of gap that a founder with an AI-built app usually finds only after launch, and the code is public, so you can check every claim below.

How this was checked

The ChiliHub SQL findings come from running its real migration in PGlite, a WebAssembly build of Postgres, with a small stub of Supabase's auth schema and table grants set to match what Supabase gives by default. The JSON result comes from Next's real NextResponse.json at version 16.1.6, the version pinned in the repo. The memory numbers come from TensorFlow.js on its CPU backend in Node. No live Supabase project, Stripe account or deployed site was touched. Nothing in macrame was run, because no Flutter toolchain was available, so those findings come from reading the source and its Dart snippet is uncompiled.

Repo 1: web-chilihub

ChiliHub's README describes a disease scanner that runs in the browser, a price dashboard, a growing calendar, a profit calculator, an urban growing guide and two languages, on Next.js 16, Supabase, Stripe and TensorFlow.js. It has Free, Pro and Business plans. The calendar and calculator are self-contained pages. The trouble sits wherever a user's state crosses from the browser to the server.

1. Paying customers hit the free limit

The limits live in src/types/index.ts as free: 3, pro: Infinity, business: Infinity. The API route returns remaining: Infinity for paid plans, and the page reads it back after a trip through JSON:

// GET /api/scan
const remaining = limit === Infinity
  ? Infinity
  : limit - profile.scans_this_month

// scan/page.tsx, line 40
if (limitData.remaining !== Infinity && limitData.remaining <= 0) {
  setError(t("scan.limitReached"));
  return;
}

Here's what the real response object produced:

{"remaining":null,"limit":null,"used":7,"tier":"pro"}
client check fires: true

null !== Infinity passes, and null <= 0 passes because JavaScript coerces null to 0 for that comparison. Fixing it takes two lines. Send a real value and make the client test for a number:

const blocked = typeof limitData.remaining === "number"
  && limitData.remaining <= 0;

With that check, null gives false, 0 gives true and 2 gives false. Run grep -rn Infinity src on any JavaScript project that sends limits over an API. A value that can't survive JSON has no business in a response body.

2. No scan is ever saved

The page posts image_url: "", and the route stores image_url || null. An empty string is falsy, so that becomes null. The migration declares image_url TEXT NOT NULL. Running that insert against the real schema gives:

null value in column "image_url" of relation "scans"
violates not-null constraint

The route answers 500, but the page never reads saveRes.ok. It calls setResult(scanResult) anyway, so the user sees a normal diagnosis. No row lands in scans, Scan History stays empty, and because the route returns before the counter update, scans_this_month stays at 0.

Put bugs 1 and 2 together and the pricing model runs backwards: free users never run out of scans, and paying users can't scan at all.

The migration is the place to fix this, since the app has no upload step and Scan.image_url has nothing to hold: ALTER TABLE scans ALTER COLUMN image_url DROP NOT NULL. Then make the page check saveRes.ok and tell the user when a save failed.

3. Any user can upgrade themselves

The profile policy looks careful at a glance:

CREATE POLICY "Users can update own profile"
  ON profiles FOR UPDATE USING (auth.uid() = id);

Row level security decides which rows a user can touch. It says nothing about columns, and subscription_tier sits in the same row as full_name. The Supabase key in the browser is public by design, so anyone signed in can send this update. In the test, as the authenticated role:

update profiles set subscription_tier='business', scans_this_month=0
  where id = auth.uid();
-- OK, returned subscription_tier = business

A free user can become Business without touching Stripe. Supabase's docs call out this gap and give the fix: revoke the table-level update and grant only the columns a user may edit.

REVOKE UPDATE ON profiles FROM authenticated, anon;
GRANT UPDATE (full_name) ON profiles TO authenticated;

After that, the same update fails with permission denied for table profiles, while changing full_name still works. The webhook uses the service role, so Stripe upgrades keep working. If your AI tool wrote a Supabase schema for you, search it for FOR UPDATE and read every column in those tables. Billing fields, roles and credit balances are the ones to look for.

4. The scan limit is a suggestion

Fixing bug 2 alone gives you a working counter that's still easy to skip. The model runs in the browser, so /api/scan only records results after the fact. The policy "Users can create scans" also lets the client insert into scans directly, and that insert succeeded in the test with no counter change. The route adds one to a value it read earlier, so two requests at once count as one. scans_reset_at is defined in the migration and never read anywhere in src, which means a free user's count never resets either.

One database function fixes all of it, because the check, the increment and the insert happen together:

CREATE FUNCTION record_scan(p_disease text, p_confidence real,
  p_severity text, p_treatment text, p_details text)
RETURNS uuid LANGUAGE plpgsql SECURITY DEFINER
SET search_path = public AS $$
DECLARE v_id uuid; v_tier text;
BEGIN
  UPDATE profiles
     SET scans_reset_at = date_trunc('month', now()) + interval '1 month',
         scans_this_month = 0
   WHERE id = auth.uid() AND scans_reset_at <= now();

  UPDATE profiles SET scans_this_month = scans_this_month + 1
   WHERE id = auth.uid()
     AND (subscription_tier <> 'free' OR scans_this_month < 3)
  RETURNING subscription_tier INTO v_tier;

  IF v_tier IS NULL THEN
    RAISE EXCEPTION 'scan_limit_reached' USING ERRCODE = 'P0001';
  END IF;

  INSERT INTO scans (user_id, disease_name, confidence,
                     severity, treatment, details)
  VALUES (auth.uid(), p_disease, p_confidence,
          p_severity, p_treatment, p_details)
  RETURNING id INTO v_id;
  RETURN v_id;
END $$;

Revoke direct insert on scans, grant execute on the function to authenticated, and the app has one door. In the test on a free account, calls 1 to 3 passed, calls 4 and 5 raised scan_limit_reached, and after moving scans_reset_at into the past the next call passed with the count back at 1.

The limit still only covers saved scans. Someone determined can run a public model file in their own browser forever. If a limit has to be real, the inference has to happen on a server you control, and that costs the "zero API cost" the plan file was aiming for. Decide which one you're selling before you write the pricing page.

5. "Real-time" prices with no way to get prices

The hero shows "Live" for price tracking, the feature copy says "Track chili prices across regions in real-time" and promises alerts, and the Pro plan lists "Full price dashboard with alerts." The API route's first comment tells the real story: // Seed data for MVP — replace with real API/scraping later.

The eight seed rows carry source: "market_data", which reads like a feed, though they're typed constants. The seed insert doesn't work either. chili_prices has read policies and no insert policy, so the insert from a user's session fails:

new row violates row-level security policy for table "chili_prices"

The route ignores that error and returns an empty list, so unless someone filled the table by hand, the dashboard renders a heading and nothing else. Any row that does appear gets a TrendingUp icon, because the icon is hard-coded. The repo has no alert code.

The cheap fix is honest copy: say "Sample prices", show recorded_at on each row, drop the alert promise and remove the arrow. Seed the table in the migration. Build the feed later, with a scheduled job using the service role. Copy that promises a feature you haven't built is a bigger problem in a paid plan than in a free one, since people are paying for that line.

6. The model isn't in the repo, and nothing says so

The app loads /model/model.json, but public/model doesn't exist in the repo. scripts/train-model.py produces it from a dataset you have to collect yourself. The page handles a missing model like this:

.catch(() => {
  setModelLoading(false);
  // Model not available yet (needs training) - show graceful message
});

No message is set. The spinner stops and the uploader stays active, so a user who uploads a photo gets a generic analysis error. On a fresh deploy from this repo, the headline feature fails after the user has already picked a photo.

When a model is present, a different risk appears. classifyImage takes the top class with no minimum confidence, so a photo of a shoe still gets a diagnosis and a treatment. Softmax output always adds up to 1, and something has to win. Two fallbacks also lean the wrong way: CLASS_LABELS[maxIdx] || "healthy" reports health when the index is out of range, and getDiseaseInfo gives unknown classes a severity of "healthy", with a unit test that locks that in. On an app telling a farmer whether to spray a crop, "unknown" should never display as healthy.

const MIN_CONFIDENCE = 0.6; // pick yours from validation data
if (maxProb < MIN_CONFIDENCE) {
  return { ...unknownResult, confidence: maxProb };
}

The 0.6 is a placeholder. Choose the threshold from a validation set that includes photos that aren't chili plants. Also add a state for "model unavailable" that disables the uploader and says why. And note that the training script validates on the same augmented generator it trains with, so its accuracy figure won't describe real field photos.

7. Every scan leaks memory

This one is small. classifyImage chains fromPixels, resizeNearestNeighbor, toFloat, div and expandDims, then disposes only the last result and the prediction. On the WebGL backend, TensorFlow.js's guide says memory must be managed explicitly, because a tensor going out of scope doesn't free it. Measured over three scans of a 64 by 64 test image:

original:  12 tensors kept, 5,566,464 bytes
tf.tidy:    0 tensors kept, 0 bytes

That's four tensors a scan, and the first one grows with the photo, so a full-size phone image costs more. Wrap the tensor work in tf.tidy(), return the prediction, read its data and dispose it.

8. The Stripe webhook can lose an upgrade

The webhook verifies signatures correctly. The weak part is what comes next. It awaits the Supabase update, ignores the returned error and always answers { received: true } with a 200. If that update fails, Stripe sees a delivered event and the customer has paid for a Free account. Stripe retries undelivered events for up to three days, but only if your endpoint reports failure.

const { error } = await supabaseAdmin
  .from("profiles")
  .update({ subscription_tier: plan })
  .eq("id", userId);

if (error) {
  console.error("tier update failed", event.id, error);
  return NextResponse.json({ error: "retry" }, { status: 500 });
}

This update is safe to repeat, which matters because Stripe's docs warn that the same event can arrive more than once. They also recommend returning a 2xx quickly and moving heavy work to a queue, so if your handler grows past a single update, follow that advice. This snippet wasn't run against Stripe.

Two related gaps: the handler listens only for checkout.session.completed and customer.subscription.deleted, so a plan change between Pro and Business does nothing, and the repo has no billing portal, so a subscriber has no way to cancel from inside the app.

9. The login callback trusts its redirect

/auth/callback reads next from the query string and redirects to `${origin}${next}`. Gluing a string onto an origin is risky, because the next character can extend the hostname:

.evil.example/x  => https://app.example.com.evil.example/x
@evil.example/x  => https://app.example.com@evil.example/x

An attacker still needs a valid auth code for the redirect to fire, so this ranks below the others, and the fix is one line:

const safe = /^\/(?![\/\\])/.test(next) && !/[\t\n\r]/.test(next)
  ? next : "/scan";

The first version of this check, which only looked for a leading slash and a double slash, was tested on all three attack shapes and sent each one to /scan while leaving /scan/history alone. The version above is stricter, for a reason found later and described near the end of this post.

Repo 2: macrame

Macrame is a Flutter shop for handmade goods with 57 Dart files: splash, login, register, home, search, product details, bookmarks, cart, orders, reviews, profile and settings. It has a tidy module layout, a theme, go_router and a full ApiService with typed results. That service is never called. apiBaseURL is an empty string, and every screen loads JSON from assets/json with rootBundle. The six products, the orders and the reviews are all files in the app.

That's a sensible way to build a UI first. The problem comes when an app like this goes to App Review, or to a client, as the finished thing. Guideline 2.1(a) asks for final versions with temporary content scrubbed, and demo account info if the app has a login, with the back end turned on. Here's what that reviewer would meet. Why Your AI-Built App Sits in Waiting for Review (and What to Do About It) covers what happens once it is submitted.

10. The Check Out button only asks a question

Future<void> launchWhatsApp() async {
  String url = 'https://wa.me/$phoneNumber?text=...';

  if (await canLaunchUrl(Uri.parse(url))) {
    await canLaunchUrl(Uri.parse(url));
  } else {
    debugPrint('Could not launch WhatsApp');
  }
}

The second line should be launchUrl. canLaunchUrl only checks whether a URL can be opened, so the shop's only checkout step does nothing and shows no error. It's a one-word slip that would survive a skim of the diff. The fix, uncompiled:

final uri = Uri.parse(url);
final opened = await launchUrl(uri,
    mode: LaunchMode.externalApplication);
if (!opened && mounted) {
  context.showErrorSnackbar('Could not open WhatsApp');
}

Selling physical goods is fine outside in-app purchase: Guideline 3.1.3(e) requires payment methods other than IAP for goods consumed outside the app. A WhatsApp order flow can work, if the button opens WhatsApp. The message is also the placeholder "Hello, this is a pre-filled message!", so even a working button would tell the seller nothing about the order.

11. Login accepts anything

_validateLogin() only checks that both fields aren't empty, then the button routes to home. One letter in each field is enough, and register behaves the same way. The Google and Facebook buttons are wired to () {}, so they do nothing when tapped. If they ever become real, Guideline 4.8 requires an equivalent login option as well. If account creation becomes real, Guideline 5.1.1(v) requires account deletion inside the app, and Settings has none.

12. The cart is a picture of a cart

The cart screen is ListView.builder(itemCount: 2) with a hard-coded image URL, so it shows two items whatever you tapped. The Order button on the product page is onPressed: () {}. Nothing connects a product to the cart. The profile menu adds a smaller version of the same problem: it says "Already have 10 orders" as a default string, while user.json says 5.

13. Removing a bookmark adds a bookmark

The bookmark icon flips selectedBookmark and then always calls AppPrefs.saveJsonToSharedPreferences(_products). There's no check for which way it flipped and no duplicate check in the save. Tap on, tap off, and the saved list has the product twice. The fix is to branch on the new state and call the existing removeJsonByIdFromSharedPreferences when it's off.

14. The privacy policy belongs to someone else

Settings has FAQ, Contact Us and Privacy and Policy. All three open the same URL: a FAQ page for test users on testingtime.com, a website that has nothing to do with this shop. Guideline 5.1.1(i) requires a link to your privacy policy in App Store Connect and inside the app. Filler like this is easy to miss because the screen looks done and the link loads. For more on what reviewers check here, see why AI-built apps get rejected under Guideline 2.1.

15. The template is still showing

The iOS bundle ID is com.example.macrameApp and the Android ID is com.example.macrame_app. pubspec.yaml still says "A new Flutter project." The only test is the default counter test, which looks for a 0 and a plus button this app doesn't have. None of this hurts a user, but each one tells a reviewer or a technical buyer how far the project got.

Three of the fixes, re-run on a Mac

Three findings were re-run later on macOS 26.0.1 with Node 22.17.0, using the code in this post. The two repos were not cloned for this, and the PGlite and TensorFlow.js results above were not run again.

The plan limit. Node's built-in Response.json, the web standard that NextResponse.json builds on, turned remaining: Infinity into "remaining":null, the same body shown earlier. The original check blocked that Pro response and the fixed check let it through, and both blocked a free account with 0 scans left. One case gets past both: if the route answers with an error body such as {"error":"Unauthorized"}, there is no remaining field, so neither check blocks. Check res.ok before reading the limit, so a failed request stops the scan.

The login redirect. Node's URL parser confirmed the original problem: @evil.example/x made evil.example the host, and .evil.example/x made it app.example.com.evil.example. With the redirect built by joining strings, as in this repo, the first version of the fix held. Many Next.js handlers build it with new URL(next, origin) instead, and there two shapes got past that first version: /\evil.example/x, and a slash, a tab and a second slash. URL parsers treat a backslash like a slash and drop tabs, so both landed on evil.example. The check above rejects a second slash or a backslash right after the first slash, plus any tab or line break. With both ways of building the URL, it sent all five attack shapes to /scan, kept /scan/history, and left an encoded /%2F%2Fevil.example on the same host as a plain path.

The empty handler search. On a sample Dart file, the pattern in the checklist below found onPressed: () {} and onTap: () {}. It missed four other ways a control can do nothing: onLongPress: () {}, because the pattern allows only one capital letter in the name; a handler with an argument, such as onSubmitted: (value) {}; Dart's arrow form () => {}; and onPressed: null, which disables the button. This wider search found all six lines in the sample:

grep -rnE 'on[A-Z][A-Za-z]*: (\([^)]*\) \{ *\}|\(\) => \{\}|null)' lib

A disabled button can be deliberate, so read each hit. The count of six for macrame comes from the first pattern and was not checked again here.

The test that finds these in your own app

Fifteen findings across two repos, and almost none would show up if you tapped through the happy path. A screen recording of either app looks fine. Most of these bugs live in a boundary: browser to server, server to database, app to outside world. So test the boundaries, in this order.

  1. Walk the paid path with a real test purchase. Stripe's test mode is free. Buy the top plan, then use the top feature. ChiliHub would fail on the first scan.
  2. Restart and look for your data. Do one action, kill the app or clear the tab, and open it again. If the work is gone, or the history is empty, you've found a save that failed without telling anyone.
  3. Read the network tab for every save. Any 4xx or 5xx behind a success screen means the client isn't checking.
  4. Attack your own rows. With the public key and a normal account, try to update every column of every table you own, including plan, role, credits and user_id. Write down which succeed.
  5. Search for empty handlers. grep -rnE 'on[A-Z][a-z]+: \(\) \{\}' lib finds six in macrame. In React, look for onClick={() => {}}.
  6. Search for leftovers: com.example, TODO, later, MVP, dummy, lorem, Hello. Then open every link in your settings screen and read the page it lands on.
  7. Audit your promises. Copy every claim from your landing page and pricing page into a list, the words "live", "real-time", "alerts" and "unlimited" first, and find the code behind each one. If there's none, change the copy today.
  8. Deploy from a clean clone. Clone the repo fresh, follow your README, and deploy. Anything ignored, trained locally or set by hand shows up here, as the missing model does in ChiliHub.

Then hand this list to your coding agent as acceptance criteria, one line per check. Agents do well with a checkable sentence like "a Pro user with 50 scans can run scan 51" and poorly with "add subscriptions." The Best Coding Agent Fully Finished 26% of Real Tasks. Write Your Acceptance Criteria Before You Prompt explains why the sentence matters.

Where to start if you only have an hour

For a ChiliHub-shaped app, the order is the column grants, then the image_url migration, then the remaining check, then record_scan. The grants come first because they're the only item that gets worse the longer you're live: every day a self-upgrade stays possible, the plan data in your database means less. For a macrame-shaped app, fix launchUrl, write a real privacy policy page, and decide whether login exists at all. A shop with no accounts is a legitimate app, and it removes three of the problems above.

If you use Claude Code and want the "checkable sentence" habit built into your workflow, I sell Ship It Solo: The Claude Code Agent Team Kit, $26. It's a four-agent pipeline where a spec-writer produces acceptance criteria, an implementer works in small commits, a reviewer checks the diff against the spec, and a QA agent writes and runs tests against those criteria. It also has guard hooks for destructive commands and secrets. It needs Claude Code, it's stack-agnostic, and its product page says plainly that it doesn't replace code review.

Sources