Skip to content

refactor(platform): cross-platform primitives + migrate ~50 call-sites (iOS crash fix) - #249

Merged
thinkclay merged 4 commits into
mainfrom
claude/platform-safety-audit
May 19, 2026
Merged

thinkclay merged 4 commits into
mainfrom
claude/platform-safety-audit

Conversation

@thinkclay

@thinkclay thinkclay commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Introduces @scf/core/utils/platform/* — a set of Metro platform-extension primitives (.web.ts / .native.ts resolved at build time) that replace scattered Platform.OS === 'web' branches and unguarded browser-API access in feature code.
  • Migrates ~50 call-sites across scf-core and apps/scaffald onto the new primitives. Net delta is negative (LOC removed > LOC added in feature code).
  • Adds pnpm lint:platform as a guardrail to prevent regression.
  • Fixes an unrelated nx/pnpm fork-bomb in prepush that surfaced while validating this branch.
  • Drops the floating mobile search/sort toolbar from the communities hub (was conflicting with the bottom tab navigator).
  • Adds apps/web/.next/ and apps/web/next-env.d.ts to .gitignore.
  • Companion submodule PR: Scaffald/ui#3.

Why this exists

The original symptom was an iOS ErrorBoundary crash in the profile screens:

TypeError: window.addEventListener is not a function (it is undefined)
  at ProfileEducationLeft (packages/scf-core/features/profile/profile-education-left.tsx:91)

Root cause: on React Native iOS, window exists as the global object — so the common defensive guard if (typeof window === 'undefined') return silently fails, and the next line crashes when it tries to call a DOM API like window.addEventListener. The same pattern was duplicated across four profile files plus useSaveStatus.

Rather than just adding Platform.OS !== 'web' checks at each call-site, we built a small set of cross-platform primitives that own the divergence once, so feature code never sees a runtime branch.

Commits

SHA Scope
95c13d40f refactor(platform): primitives + ~50 call-site migrations (main change)
2f38d5252 fix(build): break fork-bomb recursion in nx run-many -t build (cherry-pickable)
4555fd56e refactor(communities): remove floating search/sort toolbar on mobile
2fc5fabca chore(gitignore): ignore Next.js build artifacts in apps/web

New primitives

Each is a Metro platform extension: shared .ts (types + a throwing default for static analysis), .web.ts (browser impl), .native.ts (iOS/Android impl).

Primitive Web Native
openExternalLink(url, { inApp? }) window.open Linking.openURL (+ optional expo-web-browser)
useUnsavedChangesPrompt(isDirty) beforeunload listener navigation.addListener('beforeRemove', …) → Alert
confirmDialog({ title, message, destructive? }) window.confirm wrapped in a Promise Alert.alert resolving the promise
kvStorage localStorage (async wrapper) AsyncStorage
sessionKvStorage sessionStorage (sync) in-memory Map (process-lifetime)
downloadFile({ url, filename }) hidden <a download> click Linking.openURL
pickFile({ accept, multiple? }) hidden <input type=file> expo-document-picker
getCanonicalUrl(path) ${origin}${path} undefined
setDocumentTitle(title) document.title = no-op (use navigation.setOptions)
reloadPage() window.location.reload() no-op (callers should queryClient.invalidateQueries)

Migrations

Cat A — window.open (12 sites): profile certifications, discover hover cards / preview modals, privacy dashboard, news widgets, admin background-check viewer, oauth consent. All now route through openExternalLink — including apps/scaffald/.../dashboard/news/index.tsx which previously had its own Platform.OS === 'web' ? window.open : WebBrowser.openBrowserAsync ladder.

Cat B — beforeunload (4 sites): useSaveStatus, profile-education-left, profile-experience-left, profile-general-left. Each 12-line useEffect block collapses to useUnsavedChangesPrompt(isDirty). useSaveStatus.ts was the worst offender — completely unguarded, would crash on iOS any time the skills page mounted.

Cat C — confirms: TaskDetailScreen and DeveloperPortal migrated to confirmDialog. Both now show a real Alert on native instead of silently no-opping the destructive action.

Cat D — navigation/reload: AccountSwitcher's Platform.OS === 'web' ? window.location.href : router.replace branch collapses to router.replace + reloadPage. PrivacyDashboard / office-ccpa-dashboard retry buttons use reloadPage. OAuth ConsentScreen redirects via openExternalLink. The admin CMS project page now uses router.push instead of window.location.href.

Cat E — storage: MapStateProvider, feedbackStorage, UniversalThemeProvider all migrated to kvStorage. ProfileCompletion/useCompletionNudges/oauth/passthrough migrated to sessionKvStorage. useSidebarState (in @scaffald/ui — see companion PR) split into .web.ts (sync localStorage) + .native.ts (async AsyncStorage hydrate).

Cat F — file IO: payments transaction export, connections CSV export migrated to downloadFile. Profile-certifications file pickers + CertificationProofCard's inline <input type=file> migrated to pickFile.

Cat G — SEO: apps/scaffald/(public)/jobs/[slug] canonical URL via getCanonicalUrl. JobSeoHead and usePageTitle's web branch via setDocumentTitle. IPIP ShareResults share URL via getCanonicalUrl.

Misc cleanups:

  • Deletes hooks/useSafeToast.ts — defensive wrapper that string-matched error messages to catch a now-fixed beyond-ui bug. Sole consumer migrated to useToast directly.
  • publicProfileUrl.openPublicProfileInNewTab collapses into a thin wrapper around openExternalLink.
  • discover/hooks/useUserLocation: pre-existing .ts + .native.ts pair → proper shared .ts shape + .web.ts + .native.ts.
  • Migrates api-keys + Stripe settings clipboard usage to existing copyToClipboard utility.

Companion: fork-bomb fix in prepush

While running pnpm prepush to validate this branch, the script ran away to 260+ processes in 3 minutes. Root cause: nx's @nx/js auto-discovery promotes every npm script to an nx target. The root package.json has a build script that itself invokes nx run-many -t build, so when nx run-many includes the root project, it executes pnpm build → which recurses. Fixed by excluding the root scaffald project from affected:build, build, and prepush. Independent commit, cherry-pickable: 2f38d5252.

Communities mobile toolbar removal

4555fd56e — drops the floating glass search/sort toolbar (CommunitiesBottomToolbar) from CommunitiesHubPage. The toolbar was visually conflicting with the bottom tab navigator on mobile. Desktop search/sort via PageHeader is unchanged.

.gitignore additions

2fc5fabca — adds **/.next/ and **/next-env.d.ts to the root .gitignore. The 91MB Next.js build cache was leaking into git status after pnpm prepush ran next build, tripping gh pr create's uncommitted-changes warning. next-env.d.ts is auto-regenerated on every build, so ignoring it costs nothing.

Guardrail

New script scripts/check-platform-leakage.sh (wired in via pnpm lint:platform, also added to pnpm lint:affected) scans for browser-DOM/BOM usage in shared code. The allow-list captures the platform-primitive module itself, declared cross-platform utility shims (clipboard.ts, clearAuthStorage.ts, etc.), and any line annotated // platform-allow: <reason>. Final state: ✅ clean.

Test plan

  • pnpm -F @scf/core exec tsc --noEmit — clean
  • pnpm -F @scaffald/ui exec tsc --noEmit — clean
  • pnpm -F scaffald exec tsc --noEmit — clean
  • pnpm -F @scf/core lint / pnpm -F scaffald lint — pass (11 pre-existing warnings unchanged)
  • pnpm lint:platform — clean
  • pnpm prepush — completes without fork bomb (stamps HEAD as expected)
  • iOS: ProfileEducation / Experience / General screens no longer trip ErrorBoundary
  • iOS: cert "View Proof" tap opens link in OS browser via Linking
  • iOS: navigating away from a dirty profile form shows the "Discard changes?" Alert
  • iOS: dashboard news widget article tap opens the in-app browser
  • iOS: communities hub no longer renders the floating toolbar over the tab bar
  • Web: behavior preserved across all migrated screens (links open in new tab, beforeunload prompt appears on close, etc.)
  • Web preview: existing useResponsive, useToast, Popover, Sheet etc. unaffected (no edits to those primitives)

🤖 Generated with Claude Code

thinkclay and others added 4 commits May 19, 2026 10:41
…50 call-sites

Adds `@scf/core/utils/platform/*` — a set of Metro platform-extension
primitives that replace scattered `Platform.OS === 'web'` branches and
unguarded `window.*` / `document.*` / `localStorage` access throughout
feature code. The original symptom that prompted this audit was an iOS
ErrorBoundary crash from `window.addEventListener is not a function`
in profile screens (`window` exists on RN as the global object, so
`typeof window === 'undefined'` guards silently failed).

## New primitives (each as .ts shared shape + .web.ts + .native.ts)

- `openExternalLink(url, { inApp? })` — `window.open` / `Linking.openURL`
  (plus optional `expo-web-browser` in-app browser on native).
- `useUnsavedChangesPrompt(isDirty)` — replaces the 4× duplicated
  `beforeunload` `useEffect` block in profile screens. Native attaches
  `navigation.addListener('beforeRemove', ...)` for a native Alert.
- `confirmDialog({ title, message, destructive? })` — promise-wrapped
  `window.confirm` / `Alert.alert` (so native no longer silently
  no-ops).
- `kvStorage` (localStorage / AsyncStorage) + `sessionKvStorage`
  (sessionStorage / in-memory Map) — async key/value with consistent
  shape across both platforms.
- `downloadFile({ url, filename })` — anchor-click trick on web,
  `Linking.openURL` on native.
- `pickFile({ accept, multiple? })` — hidden file-input on web,
  `expo-document-picker` on native; returns a uniform `PickedFile[]`.
- `getCanonicalUrl(path)` — `${origin}${path}` on web, `undefined` on
  native (SEO is a web-only concept).
- `setDocumentTitle(title)` — `document.title =` on web, no-op on
  native (use `navigation.setOptions({ title })`).
- `reloadPage()` — `window.location.reload()` on web, no-op on native
  (callers should `queryClient.invalidateQueries` for parity).

## Migrations (~50 files)

- 12× `window.open` → `openExternalLink` (profile certifications,
  discover modals/hover cards, privacy, news, admin background checks,
  oauth consent).
- 4× `beforeunload` `useEffect` blocks → `useUnsavedChangesPrompt`
  (profile education/experience/general/skills + `useSaveStatus`).
- `window.confirm` in TasksDetail + DeveloperPortal → `confirmDialog`.
- `window.location.href` in AccountSwitcher + admin cms → `router.push`
  / `reloadPage`; oauth ConsentScreen → `openExternalLink`.
- `localStorage` / `sessionStorage` direct access in MapStateProvider,
  ProfileCompletion, useCompletionNudges, oauth/passthrough,
  feedbackStorage, UniversalThemeProvider → `kvStorage` /
  `sessionKvStorage`.
- File-download anchor tricks in payments + ConnectionsList →
  `downloadFile`.
- File-picker `<input type=file>` + `document.getElementById().click()`
  in profile certifications → `pickFile`.
- Canonical-URL builders in `apps/scaffald/(public)/jobs/[slug]` and
  IPIP share results → `getCanonicalUrl`.
- `document.title` writes in `usePageTitle` web branch + JobSeoHead →
  `setDocumentTitle`.

## Platform-extension splits (companion to packages/ui PR)

- `useUserLocation` split into shared `.ts` shape + existing `.native.ts`
  + new `.web.ts` (was a single `.ts` doing runtime branching).
- `packages/ui` submodule bump to include the parallel
  `useSidebarState` and `useAccessibilityInfo` splits (see Scaffald/ui#3).

## Other clean-ups

- Removes `hooks/useSafeToast.ts` — was a defensive wrapper around an
  old beyond-ui toast bug (string-matching error messages). Sole
  consumer (`profile-general-left`) now uses `useToast` directly.
- Collapses `publicProfileUrl.openPublicProfileInNewTab` into a thin
  wrapper around `openExternalLink`.

## Guardrail

- New `scripts/check-platform-leakage.sh` + `pnpm lint:platform` flags
  browser-DOM/BOM API use outside platform-extension files. Wired into
  `pnpm lint:affected`. 5 surviving call-sites are annotated with
  `// platform-allow: <reason>` (web-only debug flags, web-only map
  pins, etc.) — see the script for the allow-list rules.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The root package.json defines `build` as
`pnpm locales:validate && nx run-many -t build --exclude=@scaffald/ui-docs`.
Nx's @nx/js auto-discovery picks up that script and adds a `build`
target on the root `scaffald` project itself. When `nx run-many -t build`
runs, it sees the root project as a candidate, invokes its `build`
target (which calls `pnpm build` again), and recurses without bound —
each pass forks a new `pnpm` + `sh` + `nx run-many` + `run-executor`
quartet. A single `pnpm prepush` ballooned to 260+ processes within
three minutes during this branch's push attempt.

Fix by excluding the root project from the recursive invocations:

- `affected:build`: `--exclude=scaffald`
- `build`: `--exclude=@scaffald/ui-docs,scaffald`
- `prepush`: `--exclude=scaffald` on the affected-build leg and
  `--exclude=...,scaffald` on the test leg

The root project never had a useful build artifact — its `build`
script is an orchestrator, not a build target — so excluding it
from the run-many sweep is the right thing regardless of the fork
bomb fix.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The bottom toolbar's floating glass buttons conflicted with the bottom tab
navigator. Desktop search/sort via PageHeader is unchanged.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
`apps/web/.next/` (91MB build cache) and `apps/web/next-env.d.ts`
(auto-regenerated by every `next build`) were leaking into `git status`
after `pnpm prepush` ran. Neither has ever been tracked.

Add both to the root `.gitignore` so they stop tripping `gh pr create`'s
uncommitted-changes warning. `next-env.d.ts` is regenerated on demand
by Next.js so ignoring it costs nothing.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2f38d5252f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

consentUrl.searchParams.set('code_challenge_method', pendingAuth.code_challenge_method)

window.location.href = consentUrl.toString()
openExternalLink(consentUrl.toString())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep pending OAuth continuation in same tab

continueOAuthFlowIfPending() is called during app bootstrap from a useEffect (see apps/scaffald/app/index.tsx), not from a direct user gesture. Switching this redirect to openExternalLink() means web now uses window.open(..., '_blank'), which popup blockers can deny in that context; the function still returns true, so bootstrap skips normal routing and the user can be left on the wrong screen instead of being navigated to /oauth/consent. This redirect should use same-tab navigation (location.href/location.assign) rather than the external-link primitive.

Useful? React with 👍 / 👎.

// Redirect to client app
if (result.redirect_url) {
window.location.href = result.redirect_url
openExternalLink(result.redirect_url)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use same-tab redirect after OAuth consent completion

After grantConsent resolves, this now calls openExternalLink(result.redirect_url), which opens a new tab on web instead of replacing the current authorization tab and may be popup-blocked after the async boundary. OAuth authorization flows expect the current user-agent context to be redirected to the client callback URL; opening a separate tab can leave the consent tab stranded and break client-side completion logic. Use a same-tab redirect API here (and in the deny branch) instead of openExternalLink.

Useful? React with 👍 / 👎.

@thinkclay
thinkclay merged commit d9683f7 into main May 19, 2026
3 of 11 checks passed
@thinkclay
thinkclay deleted the claude/platform-safety-audit branch May 19, 2026 15:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant