Skip to content

fix: generate socket ids without node:crypto - #140

Merged
electrohyun merged 2 commits into
mainfrom
fix/browser-safe-socket-id
Aug 5, 2026
Merged

electrohyun merged 2 commits into
mainfrom
fix/browser-safe-socket-id

Conversation

@electrohyun

@electrohyun electrohyun commented Aug 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

newId took its bytes from node:crypto and encoded them with Buffer.toString('base64url'). A bundler shims both for the browser, and the Buffer shim has no base64url, so newId threw. Every connection goes through it, so connect() could not return a usable client anywhere but Node. smocket did not run in a browser at all, which is the environment the README is written for.

The bytes now come from Web Crypto and the url-safe base64 is done by hand. globalThis.crypto has been a global since Node 19 and CI runs 22 and 24, so the Node side is unchanged. The id keeps the shape 0011 fixed. That ADR already limits the contract to the shape, so the entropy source was never part of it. One side effect is worth naming. crypto was the package's last external import, so the shipped bundle now references no module at all.

$ grep -ohE "from ['\"][^'\"]+['\"]|require\(['\"][^'\"]+['\"]\)" dist/index.js dist/index.cjs | sort -u
$

The padding strip reads like a no-op today and still earns its place. base64url omits padding and btoa emits it, and the two agree only when the byte length is a multiple of three, which 15 is. So it removes nothing at the current length, and it is the only thing standing between a future length change and a malformed id. Verified byte for byte against randomBytes(n).toString('base64url') over 3000 samples per length. Lengths 0, 3, 15 and 30 match either way, while 1, 2, 14, 16, 17 and 1000 grow a stray = once the strip is gone.

The shape was written down in 0011 and pinned by no test, which is how the generator could stop working outside Node with the suite fully green. It has one now, in connection.test.ts so it runs dual and reads the shape off real socket.io.

What this leaves open is the reason CI missed it. The suite runs only on Node, where base64url works, so no amount of dual-run coverage could catch a browser-only failure. That is #105, and this bug is the concrete argument for it.

Verified locally. 160 pass on the real target and 160 on the mock target, with tsc --noEmit, eslint ., prettier --check and the tsup build clean. The demo page in smocket-site that first threw now connects three clients in the browser.

This branch sits on top of #136, so that PR's commit shows here until it merges.

Related issue

Closes #139

Checklist

  • Tests added or updated
  • Behavior verified against real socket.io

Add the checks this repo's own tests cannot reach. The substitution path depends
on module resolution, so a bad entry point or a mismatched type declaration would
surface in a consumer's build rather than here.

publint and arethetypeswrong run on the built package through a check:package
script, covering that the entry points and their type declarations resolve for
both ESM and CJS. Both pass clean on the current build.

CI is split into per-concern jobs. Lint, typecheck and format stay together. The
suite runs on a Node matrix of 22 and 24, both targets on each. pnpm 11, pinned
by the new packageManager field, needs Node 22.13, so 20 cannot install here at
all, and Node 20 left maintenance in April 2026. A socket.io matrix of 4.7 and
4.8 runs the real target, so the oracle is exercised across its range rather than
one pinned version. Coverage runs the mock target, the only one that exercises
smocket's own code, and gates on thresholds in vitest.config.ts set a little
under the current numbers.

No engines field is declared. #104 planned to follow socket.io's floor of 10.2.0,
and the built output rules that out, since it carries .at() from an ES2022
target. What the package supports is settled separately, and #104 carries the
note.

The Codecov upload feeds the report and badge only. It needs a CODECOV_TOKEN
secret even on a public repository, so until that secret exists it logs the
rejection and the job stays green.
@electrohyun electrohyun added this to the v0.4.0 milestone Aug 5, 2026
@electrohyun electrohyun added the bug Something isn't working label Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@electrohyun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d9cc5525-02fa-4485-ac22-bc40eaecc8c9

📥 Commits

Reviewing files that changed from the base of the PR and between 3a94cb1 and e516074.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (5)
  • .github/workflows/ci.yml
  • package.json
  • src/connection.test.ts
  • src/mock-server.ts
  • vitest.config.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov-commenter

Copy link
Copy Markdown

Welcome to Codecov 🎉

Once you merge this PR into your default branch, you're all set! Codecov will compare coverage reports and display results in all future pull requests.

ℹ️ You can also turn on project coverage checks and project coverage reporting on Pull Request comment

Thanks for integrating Codecov - We've got you covered ☂️

`newId` took its bytes from `node:crypto` and encoded them with
`Buffer.toString('base64url')`. In a browser a bundler shims both, and the
`Buffer` shim has no `base64url`, so `newId` threw and `connect()` could not
return a usable client anywhere but Node. Every connection goes through it,
so smocket did not run in a browser at all.

The bytes now come from Web Crypto and the url-safe base64 is done by hand.
`globalThis.crypto` has been a global since Node 19 and CI runs 22 and 24, so
the Node side is unchanged; the id keeps the shape 0011 fixed, which was
always the shape and never the source. This also removes the package's last
external import: the bundle now references no module at all.

The padding strip reads like a no-op and is not one. `base64url` omits
padding, `btoa` emits it, and they agree only when the byte length is a
multiple of three — 15 is, so today the strip removes nothing and the day
someone changes the length it is the only thing standing between that change
and a malformed id. Checked byte for byte against
`randomBytes(n).toString('base64url')` at lengths on both sides of 15.

The id shape was stated in 0011 and pinned by no test, which is how a
generator could stop working outside Node with the suite still green. It now
has one, running dual so the shape is read off real socket.io rather than
asserted about it.

The browser environment that would have caught this in the first place is
still missing; that is #105.

Closes #139
@electrohyun
electrohyun force-pushed the fix/browser-safe-socket-id branch from 4c969a7 to e516074 Compare August 5, 2026 14:30
@electrohyun electrohyun changed the title fix: generate socket ids without node:crypto fix: generate socket ids without node:crypto Aug 5, 2026
@electrohyun
electrohyun merged commit a7be4fb into main Aug 5, 2026
7 checks passed
@electrohyun
electrohyun deleted the fix/browser-safe-socket-id branch August 5, 2026 14:46
@electrohyun electrohyun self-assigned this Aug 5, 2026
@electrohyun electrohyun removed this from the v0.4.0 milestone Aug 5, 2026
electrohyun added a commit that referenced this pull request Aug 5, 2026
The comment on `newId` claimed the encoding was verified byte for byte against
`Buffer.toString('base64url')` and nothing held that claim. The dual-run test added
with #140 reads the id's shape, `/^[A-Za-z0-9_-]{20}$/`, which a broken encoder can
still satisfy. Drop the padding strip and it passes, because 15 bytes emit no
padding. Swap neither `+` nor `/` and it passes, until the day random bytes land on
one of those characters, at which point ids stop being url-safe with the suite green.

Split the encoder out as `toBase64Url` and cover it directly. A caller that can pass
a length other than the id's is the only thing that can pin the strip, so the export
exists for the test and stays out of `index.ts`. Three cases: the url-safe alphabet
over bytes whose standard encoding holds both `+` and `/`, the padding strip at
lengths 1, 2 and 3, and an id built from a fixed byte source so the length and the
encoding are pinned together.

Mock-only, like the adapter tests, since id generation is smocket's own and there is
no socket.io counterpart to read it off. Each case was checked against a mutation:
removing the strip fails the padding test, removing either swap fails the other two.
electrohyun added a commit that referenced this pull request Aug 5, 2026
The comment on `newId` claimed the encoding was verified byte for byte against
`Buffer.toString('base64url')` and nothing held that claim. The dual-run test added
with #140 reads the id's shape, `/^[A-Za-z0-9_-]{20}$/`, which a broken encoder can
still satisfy. Drop the padding strip and it passes, because 15 bytes emit no
padding. Swap neither `+` nor `/` and it passes, until the day random bytes land on
one of those characters, at which point ids stop being url-safe with the suite green.

Split the encoder out as `toBase64Url` and cover it directly. A caller that can pass
a length other than the id's is the only thing that can pin the strip, so the export
exists for the test and stays out of `index.ts`. Three cases: the url-safe alphabet
over bytes whose standard encoding holds both `+` and `/`, the padding strip at
lengths 1, 2 and 3, and an id built from a fixed byte source so the length and the
encoding are pinned together.

Mock-only, like the adapter tests, since id generation is smocket's own and there is
no socket.io counterpart to read it off. Each case was checked against a mutation:
removing the strip fails the padding test, removing either swap fails the other two.
electrohyun added a commit that referenced this pull request Aug 6, 2026
Turn the grep from #140 into a check that runs after the build, so an added import fails the packaging run instead of waiting for someone to open a page. It reads dist/index.js and dist/index.cjs and reports any external reference, carrying the reason the property matters since a future contributor meets it as an obstacle. Wired into check:package after the build, so the package CI job already runs it.

Reference detection lives in detect-external-imports.js as a pure function with a fixture test. The regexes skip a method call named import or require and a member call ending in from (loader.import, Array.from), so only the forms tsup emits for a dependency count. Matches inside a string or comment are not filtered: tsup does not emit them for this source, and a stray match fails loudly rather than hides.
electrohyun added a commit that referenced this pull request Aug 6, 2026
Turn the grep from #140 into a check that runs after the build, so an added import fails the packaging run instead of waiting for someone to open a page. It reads dist/index.js and dist/index.cjs and reports any external reference, carrying the reason the property matters since a future contributor meets it as an obstacle. Wired into check:package after the build, so the package CI job already runs it.

Reference detection lives in detect-external-imports.js as a pure function with a fixture test. The regexes skip a method call named import or require and a member call ending in from (loader.import, Array.from), so only the forms tsup emits for a dependency count. Matches inside a string or comment are not filtered: tsup does not emit them for this source, and a stray match fails loudly rather than hides.
@github-project-automation github-project-automation Bot moved this from Backlog to Done in smocket Aug 6, 2026
@github-project-automation github-project-automation Bot moved this to Backlog in smocket Aug 6, 2026
@electrohyun electrohyun added the 📏 l Pull request changes 200–999 lines label Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working 📏 l Pull request changes 200–999 lines

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug: newId uses node:crypto and base64url, so no client can connect in a browser

2 participants