scorezilla 0.3.0-next.1 → 0.3.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -622,13 +622,225 @@ function defaultUserAgent(version, runtime = detectRuntime()) {
622
622
  return `scorezilla-js/${version} (${runtime})`;
623
623
  }
624
624
 
625
+ // src/verifiers.ts
626
+ async function loadJose() {
627
+ try {
628
+ return await import('jose');
629
+ } catch (cause) {
630
+ throw new Error(
631
+ "scorezilla/server: the optional peer dependency 'jose' is required for verifyJwt() / verifySupabaseJwt(). Install it with `npm i jose` (or your package manager).",
632
+ { cause }
633
+ );
634
+ }
635
+ }
636
+ function extractBearerToken(req) {
637
+ const header = req.headers.get("authorization");
638
+ if (!header) return null;
639
+ const trimmed = header.trim();
640
+ if (!/^bearer\s+/i.test(trimmed)) return null;
641
+ return trimmed.replace(/^bearer\s+/i, "").trim() || null;
642
+ }
643
+ function verifyJwt(options) {
644
+ const claim = options.claim ?? "sub";
645
+ let keySet = null;
646
+ return async (req) => {
647
+ const token = extractBearerToken(req);
648
+ if (token === null) return null;
649
+ const jose = await loadJose();
650
+ if (keySet === null) {
651
+ keySet = jose.createRemoteJWKSet(
652
+ new URL(options.jwksUrl),
653
+ options.fetch ? { [jose.customFetch]: options.fetch } : void 0
654
+ );
655
+ }
656
+ try {
657
+ const { payload } = await jose.jwtVerify(token, keySet, {
658
+ ...options.issuer !== void 0 ? { issuer: options.issuer } : {},
659
+ ...options.audience !== void 0 ? { audience: options.audience } : {}
660
+ });
661
+ const id = payload[claim];
662
+ return typeof id === "string" && id.length > 0 ? { playerId: id } : null;
663
+ } catch {
664
+ return null;
665
+ }
666
+ };
667
+ }
668
+ function verifySupabaseJwt(options) {
669
+ const base = options.supabaseUrl.replace(/\/+$/, "");
670
+ return verifyJwt({
671
+ jwksUrl: `${base}/auth/v1/.well-known/jwks.json`,
672
+ issuer: `${base}/auth/v1`,
673
+ audience: "authenticated",
674
+ ...options.claim !== void 0 ? { claim: options.claim } : {},
675
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
676
+ });
677
+ }
678
+ function verifyClerkJwt(options) {
679
+ const issuer = options.issuer.replace(/\/+$/, "");
680
+ return verifyJwt({
681
+ jwksUrl: `${issuer}/.well-known/jwks.json`,
682
+ issuer,
683
+ ...options.audience !== void 0 ? { audience: options.audience } : {},
684
+ ...options.claim !== void 0 ? { claim: options.claim } : {},
685
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
686
+ });
687
+ }
688
+ function verifyAuth0Jwt(options) {
689
+ const host = options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "");
690
+ return verifyJwt({
691
+ jwksUrl: `https://${host}/.well-known/jwks.json`,
692
+ issuer: `https://${host}/`,
693
+ audience: options.audience,
694
+ ...options.claim !== void 0 ? { claim: options.claim } : {},
695
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
696
+ });
697
+ }
698
+ var FIREBASE_JWKS_URL = "https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com";
699
+ function verifyFirebaseIdToken(options) {
700
+ return verifyJwt({
701
+ jwksUrl: FIREBASE_JWKS_URL,
702
+ issuer: `https://securetoken.google.com/${options.projectId}`,
703
+ audience: options.projectId,
704
+ ...options.claim !== void 0 ? { claim: options.claim } : {},
705
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
706
+ });
707
+ }
708
+
709
+ // src/github-oauth.ts
710
+ var GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
711
+ var GITHUB_USER_URL = "https://api.github.com/user";
712
+ var MESSAGE_SOURCE = "scorezilla:github-oauth";
713
+ var USER_AGENT = "scorezilla-sdk-github-oauth";
714
+ var STATE_RE = /^[A-Za-z0-9_-]{8,128}$/;
715
+ var CODE_RE = /^[A-Za-z0-9_-]{1,128}$/;
716
+ function createGitHubOAuthHandler(config) {
717
+ if (typeof config.clientId !== "string" || config.clientId.length === 0) {
718
+ throw new TypeError("createGitHubOAuthHandler: clientId is required.");
719
+ }
720
+ if (typeof config.clientSecret !== "string" || config.clientSecret.length === 0) {
721
+ throw new TypeError("createGitHubOAuthHandler: clientSecret is required.");
722
+ }
723
+ let allowedOrigin;
724
+ try {
725
+ const parsed = new URL(config.allowedOrigin);
726
+ allowedOrigin = parsed.origin;
727
+ if (allowedOrigin === "null") throw new Error("opaque origin");
728
+ } catch {
729
+ throw new TypeError(
730
+ "createGitHubOAuthHandler: allowedOrigin must be an absolute origin, e.g. 'https://mygame.example' (got " + JSON.stringify(config.allowedOrigin) + ")."
731
+ );
732
+ }
733
+ const fetchImpl = config.fetch ?? fetch;
734
+ return async (req) => {
735
+ if (req.method !== "GET") {
736
+ return new Response("method not allowed", { status: 405, headers: { allow: "GET" } });
737
+ }
738
+ const url = new URL(req.url);
739
+ const state = url.searchParams.get("state") ?? "";
740
+ const code = url.searchParams.get("code");
741
+ const ghError = url.searchParams.get("error");
742
+ if (!STATE_RE.test(state)) {
743
+ return new Response("invalid or missing state parameter", { status: 400 });
744
+ }
745
+ if (ghError !== null) {
746
+ return callbackPage(
747
+ { state, error: ghError === "access_denied" ? "access_denied" : "exchange_failed" },
748
+ allowedOrigin
749
+ );
750
+ }
751
+ if (code === null || !CODE_RE.test(code)) {
752
+ return new Response("invalid or missing code parameter", { status: 400 });
753
+ }
754
+ let accessToken;
755
+ try {
756
+ const tokenRes = await fetchImpl(GITHUB_TOKEN_URL, {
757
+ method: "POST",
758
+ headers: {
759
+ accept: "application/json",
760
+ "content-type": "application/x-www-form-urlencoded",
761
+ "user-agent": USER_AGENT
762
+ },
763
+ body: new URLSearchParams({
764
+ client_id: config.clientId,
765
+ client_secret: config.clientSecret,
766
+ code
767
+ }).toString()
768
+ });
769
+ const tokenBody = await tokenRes.json();
770
+ if (!tokenRes.ok || typeof tokenBody.access_token !== "string") {
771
+ return callbackPage({ state, error: "exchange_failed" }, allowedOrigin);
772
+ }
773
+ accessToken = tokenBody.access_token;
774
+ } catch {
775
+ return callbackPage({ state, error: "exchange_failed" }, allowedOrigin);
776
+ }
777
+ try {
778
+ const userRes = await fetchImpl(GITHUB_USER_URL, {
779
+ method: "GET",
780
+ headers: {
781
+ authorization: `Bearer ${accessToken}`,
782
+ accept: "application/vnd.github+json",
783
+ "user-agent": USER_AGENT
784
+ }
785
+ });
786
+ if (!userRes.ok) {
787
+ return callbackPage({ state, error: "exchange_failed" }, allowedOrigin);
788
+ }
789
+ const user = await userRes.json();
790
+ if (typeof user.id !== "number" || !Number.isSafeInteger(user.id)) {
791
+ return callbackPage({ state, error: "exchange_failed" }, allowedOrigin);
792
+ }
793
+ return callbackPage({ state, id: String(user.id) }, allowedOrigin);
794
+ } catch {
795
+ return callbackPage({ state, error: "exchange_failed" }, allowedOrigin);
796
+ }
797
+ };
798
+ }
799
+ function callbackPage(payload, allowedOrigin) {
800
+ const message = JSON.stringify({ source: MESSAGE_SOURCE, ...payload });
801
+ const target = JSON.stringify(allowedOrigin);
802
+ const html = `<!doctype html>
803
+ <html>
804
+ <head><meta charset="utf-8"><title>Signing in\u2026</title></head>
805
+ <body>
806
+ <script>
807
+ (function () {
808
+ if (window.opener) {
809
+ window.opener.postMessage(${message}, ${target});
810
+ window.close();
811
+ } else {
812
+ document.body.textContent =
813
+ 'Sign-in handled \u2014 you can close this window. (If this keeps appearing, ' +
814
+ 'the game page may be setting Cross-Origin-Opener-Policy: same-origin, ' +
815
+ 'which severs the popup link; use same-origin-allow-popups.)';
816
+ }
817
+ })();
818
+ </script>
819
+ </body>
820
+ </html>`;
821
+ return new Response(html, {
822
+ status: 200,
823
+ headers: {
824
+ "content-type": "text/html; charset=utf-8",
825
+ // One-shot page embedding a one-shot state — never cache it.
826
+ "cache-control": "no-store",
827
+ // The URL carried the OAuth `code`; nothing on this page may leak it.
828
+ "referrer-policy": "no-referrer",
829
+ // Defense in depth for the inline script: nothing else may load or
830
+ // run on this page even if a future regression reflected input here.
831
+ "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'",
832
+ "x-content-type-options": "nosniff"
833
+ }
834
+ });
835
+ }
836
+
625
837
  // src/server.ts
626
838
  var Scorezilla = class _Scorezilla {
627
839
  /** The package version, injected at build time from `package.json`.
628
840
  * Mirrors the static on the public-key client so consumers can log
629
841
  * the running SDK build the same way regardless of which surface
630
842
  * they imported. */
631
- static version = "0.3.0-next.1";
843
+ static version = "0.3.0-next.3";
632
844
  #keyId;
633
845
  #secret;
634
846
  #baseUrl;
@@ -770,7 +982,131 @@ function isRealBrowserEnvironment() {
770
982
  const hasNodeLikeHost = Boolean(g.process?.versions?.node) || typeof g.Deno !== "undefined" || typeof g.Bun !== "undefined";
771
983
  return !hasNodeLikeHost;
772
984
  }
985
+ function createScoreSubmitHandler(config) {
986
+ const sz = new Scorezilla({
987
+ secretKey: config.secretKey,
988
+ ...config.baseUrl !== void 0 ? { baseUrl: config.baseUrl } : {},
989
+ ...config.fetch !== void 0 ? { fetch: config.fetch } : {},
990
+ ...config.maxRetries !== void 0 ? { maxRetries: config.maxRetries } : {},
991
+ ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {}
992
+ });
993
+ const parse = config.parseSubmission ?? defaultParseSubmission;
994
+ return async (req) => {
995
+ const cors = config.cors ? buildCorsHeaders(config.cors, req.headers.get("Origin")) : {};
996
+ if (req.method === "OPTIONS" && config.cors) {
997
+ return new Response(null, { status: 204, headers: cors });
998
+ }
999
+ if (req.method !== "POST") {
1000
+ return jsonResponse({ ok: false, error: "method_not_allowed" }, 405, cors);
1001
+ }
1002
+ if (config.rateLimit) {
1003
+ const decision = await config.rateLimit(req);
1004
+ if (!decision.ok) {
1005
+ const headers = { ...cors };
1006
+ if (decision.retryAfterSeconds !== void 0) {
1007
+ headers["Retry-After"] = String(decision.retryAfterSeconds);
1008
+ }
1009
+ return jsonResponse({ ok: false, error: "rate_limited" }, 429, headers);
1010
+ }
1011
+ }
1012
+ let identity;
1013
+ try {
1014
+ identity = await config.verify(req);
1015
+ } catch {
1016
+ identity = null;
1017
+ }
1018
+ if (!identity || typeof identity.playerId !== "string" || identity.playerId.length === 0) {
1019
+ return jsonResponse({ ok: false, error: "unauthorized" }, 401, cors);
1020
+ }
1021
+ let submission;
1022
+ try {
1023
+ submission = await parse(req);
1024
+ } catch {
1025
+ submission = null;
1026
+ }
1027
+ if (!submission || typeof submission.score !== "number" || !Number.isFinite(submission.score)) {
1028
+ return jsonResponse(
1029
+ { ok: false, error: "bad_request", message: "invalid score submission" },
1030
+ 400,
1031
+ cors
1032
+ );
1033
+ }
1034
+ const metadata = mergeMetadata(submission.metadata, identity.metadata);
1035
+ try {
1036
+ const result = await sz.submitScore({
1037
+ boardId: config.boardId,
1038
+ playerId: identity.playerId,
1039
+ score: submission.score,
1040
+ ...metadata !== void 0 ? { metadata } : {}
1041
+ });
1042
+ return jsonResponse(
1043
+ {
1044
+ ok: true,
1045
+ rank: result.rank,
1046
+ totalEntries: result.totalEntries,
1047
+ isPersonalBest: result.isPersonalBest
1048
+ },
1049
+ 200,
1050
+ cors
1051
+ );
1052
+ } catch (err) {
1053
+ return mapSubmitError(err, cors);
1054
+ }
1055
+ };
1056
+ }
1057
+ async function defaultParseSubmission(req) {
1058
+ const raw = await req.json().catch(() => null);
1059
+ if (!isPlainObject(raw)) return null;
1060
+ const score = raw.score;
1061
+ if (typeof score !== "number" || !Number.isFinite(score)) return null;
1062
+ return { score, metadata: isPlainObject(raw.metadata) ? raw.metadata : void 0 };
1063
+ }
1064
+ function isPlainObject(value) {
1065
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1066
+ }
1067
+ function mergeMetadata(client, verified) {
1068
+ if (!client && !verified) return void 0;
1069
+ return { ...client ?? {}, ...verified ?? {} };
1070
+ }
1071
+ function jsonResponse(body, status, extra) {
1072
+ return new Response(JSON.stringify(body), {
1073
+ status,
1074
+ headers: { "Content-Type": "application/json; charset=utf-8", ...extra }
1075
+ });
1076
+ }
1077
+ function mapSubmitError(err, cors) {
1078
+ if (err instanceof ScorezillaError) {
1079
+ if (err.isRateLimited()) {
1080
+ const headers = { ...cors };
1081
+ if (err.retryAfter !== void 0) headers["Retry-After"] = String(err.retryAfter);
1082
+ return jsonResponse({ ok: false, error: "rate_limited" }, 429, headers);
1083
+ }
1084
+ if (err.status >= 400 && err.status < 500) {
1085
+ return jsonResponse({ ok: false, error: err.code, message: err.message }, err.status, cors);
1086
+ }
1087
+ return jsonResponse({ ok: false, error: "upstream_error" }, 502, cors);
1088
+ }
1089
+ return jsonResponse({ ok: false, error: "server_error" }, 500, cors);
1090
+ }
1091
+ function buildCorsHeaders(cors, origin) {
1092
+ const headers = {
1093
+ "Access-Control-Allow-Methods": (cors.methods ?? ["POST", "OPTIONS"]).join(", "),
1094
+ "Access-Control-Allow-Headers": (cors.headers ?? ["content-type", "authorization"]).join(", "),
1095
+ "Access-Control-Max-Age": String(cors.maxAgeSeconds ?? 600),
1096
+ Vary: "Origin"
1097
+ };
1098
+ if (origin !== null && isCorsOriginAllowed(cors.origin, origin)) {
1099
+ headers["Access-Control-Allow-Origin"] = origin;
1100
+ }
1101
+ return headers;
1102
+ }
1103
+ function isCorsOriginAllowed(rule, origin) {
1104
+ if (typeof rule === "boolean") return rule;
1105
+ if (typeof rule === "string") return rule === origin;
1106
+ if (typeof rule === "function") return rule(origin);
1107
+ return rule.includes(origin);
1108
+ }
773
1109
 
774
- export { Scorezilla, ScorezillaError };
1110
+ export { Scorezilla, ScorezillaError, createGitHubOAuthHandler, createScoreSubmitHandler, verifyAuth0Jwt, verifyClerkJwt, verifyFirebaseIdToken, verifyJwt, verifySupabaseJwt };
775
1111
  //# sourceMappingURL=server.js.map
776
1112
  //# sourceMappingURL=server.js.map