@supatype/ssr 0.3.6 → 0.8.0

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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @supatype/ssr@0.3.6 build /home/runner/work/supatype/supatype/packages/ssr
2
+ > @supatype/ssr@0.8.0 build /home/runner/work/supatype/supatype/packages/ssr
3
3
  > tsc --project tsconfig.json
4
4
 
@@ -0,0 +1,15 @@
1
+
2
+ > @supatype/ssr@0.8.0 test /home/runner/work/supatype/supatype/packages/ssr
3
+ > vitest run
4
+
5
+
6
+  RUN  v4.0.18 /home/runner/work/supatype/supatype/packages/ssr
7
+
8
+ ✓ tests/cookie-parser.test.ts (3 tests) 54ms
9
+ ✓ tests/server-client.test.ts (9 tests) 559ms
10
+
11
+  Test Files  2 passed (2)
12
+  Tests  12 passed (12)
13
+  Start at  21:33:35
14
+  Duration  5.55s (transform 3.56s, setup 0ms, import 4.32s, tests 613ms, environment 0ms)
15
+
@@ -1,4 +1,4 @@
1
1
 
2
- > @supatype/ssr@0.3.6 typecheck /home/runner/work/supatype/supatype/packages/ssr
3
- > tsc --project tsconfig.json --noEmit
2
+ > @supatype/ssr@0.8.0 typecheck /home/runner/work/supatype/supatype/packages/ssr
3
+ > tsc --project tests/tsconfig.json --noEmit
4
4
 
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Supatype
3
+ Copyright (c) 2026 Supatype Ltd
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -12,7 +12,8 @@ pnpm add @supatype/ssr
12
12
 
13
13
  ### Next.js App Router
14
14
 
15
- Create a server client factory that reads cookies on each request:
15
+ Create server client factories that read cookies on each request: one for Server Components, which
16
+ cannot write cookies, and one for Route Handlers and Server Actions, which can:
16
17
 
17
18
  ```ts
18
19
  // lib/supatype-server.ts
@@ -23,17 +24,26 @@ import type { Database } from "@/types/database"
23
24
  const url = process.env.NEXT_PUBLIC_SUPATYPE_URL!
24
25
  const anonKey = process.env.NEXT_PUBLIC_SUPATYPE_ANON_KEY!
25
26
 
27
+ // Server Components: no `setAll`, so the client never refreshes the session.
26
28
  export async function createClient() {
29
+ const cookieStore = await cookies()
30
+ return createServerClient<Database>(url, anonKey, {
31
+ cookies: {
32
+ getAll() { return cookieStore.getAll() },
33
+ },
34
+ })
35
+ }
36
+
37
+ // Route Handlers and Server Actions: a refreshed session goes back to the browser.
38
+ export async function createWritableClient() {
27
39
  const cookieStore = await cookies()
28
40
  return createServerClient<Database>(url, anonKey, {
29
41
  cookies: {
30
42
  getAll() { return cookieStore.getAll() },
31
43
  setAll(cookiesToSet) {
32
- try {
33
- cookiesToSet.forEach(({ name, value, options }) =>
34
- cookieStore.set(name, value, options ?? {})
35
- )
36
- } catch { /* no-op in read-only Server Component context */ }
44
+ cookiesToSet.forEach(({ name, value, options }) =>
45
+ cookieStore.set(name, value, options ?? {})
46
+ )
37
47
  },
38
48
  },
39
49
  })
@@ -58,7 +68,8 @@ Access the session in a Server Component or Route Handler:
58
68
  ```ts
59
69
  const supatype = await createClient()
60
70
  const { data: { session } } = await supatype.auth.getSession()
61
- // session is null if no valid cookie is present
71
+ // session is null if no valid cookie is present. Without `setAll` it is the cookie's session as it
72
+ // is: its access token may have expired, since that client never refreshes it.
62
73
  ```
63
74
 
64
75
  ### Cookie adapter interface
@@ -68,13 +79,28 @@ const { data: { session } } = await supatype.auth.getSession()
68
79
  ```ts
69
80
  interface CookieAdapter {
70
81
  getAll(): Array<{ name: string; value: string }>
71
- setAll(cookies: Array<{ name: string; value: string; options?: CookieOptions }>): void
82
+ setAll?(cookies: Array<{ name: string; value: string; options?: CookieOptions }>): void
72
83
  }
73
84
  ```
74
85
 
86
+ `setAll` is called whenever the session changes on the server: a refreshed access token, a sign-in
87
+ or a sign-out. It receives the session cookie (`<prefix>-auth-token`) in the format the browser
88
+ client writes, with `path: "/"`, `sameSite: "lax"` and a `maxAge` that ends with the access token;
89
+ a sign-out or a refused refresh sends an empty value with `maxAge: 0`. The value is not encoded:
90
+ pass it to your framework's cookie setter, which encodes it as it does any cookie. Add `secure` or
91
+ `httpOnly` in the adapter if you want them.
92
+
93
+ Leave `setAll` out where cookies are read-only, such as a Server Component. Without it the client
94
+ never refreshes the session: an expired access token is sent as it is, and the API refuses it. A
95
+ refresh spends the refresh token the browser holds and returns a new one, and a client that cannot
96
+ write cookies would keep that new one to itself, so the browser's own next refresh would be refused
97
+ and sign it out. Do not pass a `setAll` that swallows the failure there instead: the client then
98
+ refreshes as if the write had worked. Refresh in middleware, which can write cookies, before the
99
+ page renders, so a Server Component reads a session that is still valid.
100
+
75
101
  ### Cookie prefix
76
102
 
77
- Auth tokens are stored under `st-<project-ref>-auth-token` by default. If you've configured a custom prefix, pass it via `cookiePrefix`:
103
+ The browser client stores the session under `st-auth-token` by default. If you've configured a custom prefix (`auth.cookiePrefix` on `createClient`), pass the same one via `cookiePrefix`:
78
104
 
79
105
  ```ts
80
106
  createServerClient(url, anonKey, {
@@ -86,10 +112,11 @@ createServerClient(url, anonKey, {
86
112
  ## How it works
87
113
 
88
114
  1. Reads all cookies via the adapter's `getAll()`
89
- 2. Finds the auth token cookie matching `<prefix>-*-auth-token`
90
- 3. Parses the JSON session value and checks the JWT `exp` claim, expired tokens are discarded
91
- 4. Passes the session as `initialSession` to `createClient`, so all subsequent requests carry the user's JWT automatically
92
- 5. Signature verification is handled server-side by the gateway when the token is forwarded
115
+ 2. Finds the auth token cookie `<prefix>-auth-token`, or one matching `<prefix>-*-auth-token`
116
+ 3. Parses the JSON session value and checks the JWT `exp` claim. A session whose access token has expired is kept only when it has a refresh token
117
+ 4. Passes the session as `initialSession` to `createClient`, so all subsequent requests carry the user's JWT automatically. The client keeps no session of its own and runs no refresh timer. With `setAll`, an expired access token is refreshed only when a request the client makes finds it expired; without `setAll`, it is never refreshed and is sent as it is. Parsing uses `atob` and `TextDecoder`, not Node's `Buffer`, so it works on edge runtimes
118
+ 5. Writes every change to the session (a refresh, a sign-in, a sign-out) back through the adapter's `setAll`, so the browser holds the new tokens
119
+ 6. Signature verification is handled server-side by the gateway when the token is forwarded
93
120
 
94
121
  ## API
95
122
 
@@ -99,5 +126,5 @@ Returns a fully-typed `SupatypeClient` pre-loaded with the user's session from c
99
126
 
100
127
  | Option | Type | Default | Description |
101
128
  |--------|------|---------|-------------|
102
- | `cookies` | `CookieAdapter` | required | Read/write cookie adapter |
103
- | `cookiePrefix` | `string` | `"st"` | Cookie name prefix |
129
+ | `cookies` | `CookieAdapter` | required | `getAll()` reads the request's cookies; optional `setAll()` writes the session cookie when the session changes, and without it the client never refreshes the session |
130
+ | `cookiePrefix` | `string` | `"st"` | Cookie name prefix: the session cookie is `<prefix>-auth-token` |
@@ -1,6 +1,14 @@
1
1
  import type { Session } from "@supatype/client";
2
+ import type { CookieToSet } from "./types.js";
3
+ /** The prefix `@supatype/client` names its session cookie with: `st-auth-token`. */
4
+ export declare const DEFAULT_COOKIE_PREFIX = "st";
2
5
  export declare function parseSessionFromCookies(cookies: Array<{
3
6
  name: string;
4
7
  value: string;
5
8
  }>, prefix?: string): Session | null;
9
+ /**
10
+ * The cookie that holds `session`, named and shaped as `@supatype/client` writes it in the browser
11
+ * and `parseSessionFromCookies` reads it; a null session clears the cookie.
12
+ */
13
+ export declare function sessionCookie(session: Session | null, prefix?: string): CookieToSet;
6
14
  //# sourceMappingURL=cookie-parser.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cookie-parser.d.ts","sourceRoot":"","sources":["../src/cookie-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAQ,MAAM,kBAAkB,CAAA;AAErD,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,EAC/C,MAAM,GAAE,MAAa,GACpB,OAAO,GAAG,IAAI,CAoBhB"}
1
+ {"version":3,"file":"cookie-parser.d.ts","sourceRoot":"","sources":["../src/cookie-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAQ,MAAM,kBAAkB,CAAA;AACrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE7C,oFAAoF;AACpF,eAAO,MAAM,qBAAqB,OAAO,CAAA;AAEzC,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,EAC/C,MAAM,GAAE,MAA8B,GACrC,OAAO,GAAG,IAAI,CAoBhB;AA4ED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,EAAE,MAAM,GAAE,MAA8B,GAAG,WAAW,CAc1G"}
@@ -1,4 +1,6 @@
1
- export function parseSessionFromCookies(cookies, prefix = "st") {
1
+ /** The prefix `@supatype/client` names its session cookie with: `st-auth-token`. */
2
+ export const DEFAULT_COOKIE_PREFIX = "st";
3
+ export function parseSessionFromCookies(cookies, prefix = DEFAULT_COOKIE_PREFIX) {
2
4
  const candidates = cookies.filter((c) => c.name === `${prefix}-auth-token` ||
3
5
  (c.name.startsWith(`${prefix}-`) && c.name.endsWith("-auth-token")));
4
6
  if (candidates.length === 0)
@@ -16,33 +18,50 @@ export function parseSessionFromCookies(cookies, prefix = "st") {
16
18
  }
17
19
  return null;
18
20
  }
21
+ /** True for a JSON object: not null, not an array. */
22
+ function isJsonObject(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
19
25
  function parseSessionValue(value) {
20
26
  try {
21
27
  return normalizeSession(JSON.parse(decodeURIComponent(value)));
22
28
  }
23
29
  catch { /* not JSON */ }
24
30
  try {
25
- return normalizeSession(JSON.parse(Buffer.from(value, "base64").toString("utf-8")));
31
+ return normalizeSession(JSON.parse(decodeBase64(value)));
26
32
  }
27
33
  catch { /* not base64 JSON */ }
28
34
  return null;
29
35
  }
30
- function normalizeSession(raw) {
31
- if (typeof raw !== "object" || raw === null)
36
+ /**
37
+ * Base64 or base64url text decoded as UTF-8, with `atob` and `TextDecoder` rather than Node's
38
+ * `Buffer`: the server client also runs on edge runtimes, which have no `Buffer`. Throws on input
39
+ * that is not base64.
40
+ */
41
+ function decodeBase64(text) {
42
+ const standard = text.replace(/-/g, "+").replace(/_/g, "/");
43
+ const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4));
44
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
45
+ }
46
+ /**
47
+ * The session a cookie holds. One whose access token has expired is kept when it carries a refresh
48
+ * token: the first request the client makes refreshes it, and the server client writes the new
49
+ * tokens back through `setAll`.
50
+ */
51
+ function normalizeSession(r) {
52
+ if (!isJsonObject(r))
32
53
  return null;
33
- const r = raw;
34
54
  if (typeof r["access_token"] !== "string")
35
55
  return null;
36
- if (isJwtExpired(r["access_token"]))
56
+ const refreshToken = typeof r["refresh_token"] === "string" ? r["refresh_token"] : "";
57
+ if (isJwtExpired(r["access_token"]) && refreshToken.trim() === "")
37
58
  return null;
38
59
  return {
39
60
  accessToken: r["access_token"],
40
61
  tokenType: typeof r["token_type"] === "string" ? r["token_type"] : "bearer",
41
62
  expiresIn: typeof r["expires_in"] === "number" ? r["expires_in"] : 3600,
42
- refreshToken: typeof r["refresh_token"] === "string" ? r["refresh_token"] : "",
43
- user: normalizeUser(typeof r["user"] === "object" && r["user"] !== null
44
- ? r["user"]
45
- : {}),
63
+ refreshToken,
64
+ user: normalizeUser(isJsonObject(r["user"]) ? r["user"] : {}),
46
65
  ...(typeof r["expires_at"] === "number" && { expiresAt: r["expires_at"] }),
47
66
  };
48
67
  }
@@ -51,7 +70,10 @@ function isJwtExpired(token) {
51
70
  if (parts.length !== 3)
52
71
  return true;
53
72
  try {
54
- const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
73
+ const payload = JSON.parse(decodeBase64(parts[1]));
74
+ // A payload that is not an object reads as expired, as it did when reading it threw.
75
+ if (!isJsonObject(payload))
76
+ return true;
55
77
  const exp = typeof payload["exp"] === "number" ? payload["exp"] : null;
56
78
  if (exp === null)
57
79
  return false;
@@ -64,8 +86,8 @@ function isJwtExpired(token) {
64
86
  function normalizeUser(raw) {
65
87
  return {
66
88
  id: typeof raw["id"] === "string" ? raw["id"] : "",
67
- appMetadata: (raw["app_metadata"] ?? {}),
68
- userMetadata: (raw["user_metadata"] ?? {}),
89
+ appMetadata: isJsonObject(raw["app_metadata"]) ? raw["app_metadata"] : {},
90
+ userMetadata: isJsonObject(raw["user_metadata"]) ? raw["user_metadata"] : {},
69
91
  createdAt: typeof raw["created_at"] === "string" ? raw["created_at"] : "",
70
92
  updatedAt: typeof raw["updated_at"] === "string" ? raw["updated_at"] : "",
71
93
  ...(typeof raw["email"] === "string" && { email: raw["email"] }),
@@ -73,4 +95,36 @@ function normalizeUser(raw) {
73
95
  ...(typeof raw["role"] === "string" && { role: raw["role"] }),
74
96
  };
75
97
  }
98
+ /**
99
+ * The cookie that holds `session`, named and shaped as `@supatype/client` writes it in the browser
100
+ * and `parseSessionFromCookies` reads it; a null session clears the cookie.
101
+ */
102
+ export function sessionCookie(session, prefix = DEFAULT_COOKIE_PREFIX) {
103
+ const name = `${prefix}-auth-token`;
104
+ if (session === null)
105
+ return { name, value: "", options: { path: "/", maxAge: 0 } };
106
+ const value = JSON.stringify({
107
+ access_token: session.accessToken,
108
+ refresh_token: session.refreshToken,
109
+ token_type: session.tokenType,
110
+ expires_in: session.expiresIn,
111
+ ...(session.expiresAt !== undefined && { expires_at: session.expiresAt }),
112
+ user: serializeUser(session.user),
113
+ });
114
+ // The browser client's cookie expires with the access token; one without `expiresAt` lasts the session.
115
+ const maxAge = session.expiresAt !== undefined ? Math.max(0, session.expiresAt - Math.floor(Date.now() / 1000)) : undefined;
116
+ return { name, value, options: { path: "/", sameSite: "lax", ...(maxAge !== undefined && { maxAge }) } };
117
+ }
118
+ function serializeUser(user) {
119
+ return {
120
+ id: user.id,
121
+ ...(user.email !== undefined && { email: user.email }),
122
+ ...(user.phone !== undefined && { phone: user.phone }),
123
+ ...(user.role !== undefined && { role: user.role }),
124
+ app_metadata: user.appMetadata,
125
+ user_metadata: user.userMetadata,
126
+ created_at: user.createdAt,
127
+ updated_at: user.updatedAt,
128
+ };
129
+ }
76
130
  //# sourceMappingURL=cookie-parser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cookie-parser.js","sourceRoot":"","sources":["../src/cookie-parser.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,uBAAuB,CACrC,OAA+C,EAC/C,SAAiB,IAAI;IAErB,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAC/B,CAAC,CAAC,EAAE,EAAE,CACJ,CAAC,CAAC,IAAI,KAAK,GAAG,MAAM,aAAa;QACjC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CACtE,CAAA;IACD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IAExC,gEAAgE;IAChE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACvB,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,GAAG,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QACxD,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,GAAG,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QACxD,OAAO,MAAM,GAAG,MAAM,CAAA;IACxB,CAAC,CAAC,CAAA;IAEF,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE,CA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,CAAC,IAAI,EAAE,CAAC;QACnD,YAAY,EAAE,IAAI,CAAC,WAAW;QAC9B,aAAa,EAAE,IAAI,CAAC,YAAY;QAChC,UAAU,EAAE,IAAI,CAAC,SAAS;QAC1B,UAAU,EAAE,IAAI,CAAC,SAAS;KAC3B,CAAA;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { createServerClient } from "./server-client.js";
2
- export type { ServerClientOptions, CookieAdapter, CookieOptions } from "./types.js";
2
+ export type { ServerClientOptions, CookieAdapter, CookieOptions, CookieToSet } from "./types.js";
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AACvD,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AACvD,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA"}
@@ -1,4 +1,16 @@
1
1
  import type { SupatypeClient, AnyDatabase } from "@supatype/client";
2
2
  import type { ServerClientOptions } from "./types.js";
3
+ /**
4
+ * A client for one server request, signed in as the session the request's cookies carry.
5
+ *
6
+ * It keeps no session of its own and runs no refresh timer: the cookie is the only store, and the
7
+ * client lives as long as the request. With `setAll`, a refresh happens only when a request it
8
+ * makes finds the access token expired, and the rotated session goes back to the browser through
9
+ * `setAll`, so the browser holds the new refresh token rather than the one the refresh just spent.
10
+ *
11
+ * Without `setAll` (a Server Component) it never refreshes: an expired access token is sent as it
12
+ * is and refused. A refresh there would spend the browser's refresh token and return one the
13
+ * browser never receives, so the browser's own next refresh would be refused and sign it out.
14
+ */
3
15
  export declare function createServerClient<TDatabase extends AnyDatabase = AnyDatabase>(url: string, anonKey: string, options: ServerClientOptions): SupatypeClient<TDatabase>;
4
16
  //# sourceMappingURL=server-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-client.d.ts","sourceRoot":"","sources":["../src/server-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAEnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAErD,wBAAgB,kBAAkB,CAAC,SAAS,SAAS,WAAW,GAAG,WAAW,EAC5E,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,mBAAmB,GAC3B,cAAc,CAAC,SAAS,CAAC,CAO3B"}
1
+ {"version":3,"file":"server-client.d.ts","sourceRoot":"","sources":["../src/server-client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAEnE,OAAO,KAAK,EAAiB,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAEpE;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,SAAS,WAAW,GAAG,WAAW,EAC5E,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,mBAAmB,GAC3B,cAAc,CAAC,SAAS,CAAC,CAgB3B"}
@@ -1,11 +1,54 @@
1
1
  import { createClient } from "@supatype/client";
2
- import { parseSessionFromCookies } from "./cookie-parser.js";
2
+ import { DEFAULT_COOKIE_PREFIX, parseSessionFromCookies, sessionCookie } from "./cookie-parser.js";
3
+ /**
4
+ * A client for one server request, signed in as the session the request's cookies carry.
5
+ *
6
+ * It keeps no session of its own and runs no refresh timer: the cookie is the only store, and the
7
+ * client lives as long as the request. With `setAll`, a refresh happens only when a request it
8
+ * makes finds the access token expired, and the rotated session goes back to the browser through
9
+ * `setAll`, so the browser holds the new refresh token rather than the one the refresh just spent.
10
+ *
11
+ * Without `setAll` (a Server Component) it never refreshes: an expired access token is sent as it
12
+ * is and refused. A refresh there would spend the browser's refresh token and return one the
13
+ * browser never receives, so the browser's own next refresh would be refused and sign it out.
14
+ */
3
15
  export function createServerClient(url, anonKey, options) {
4
- const session = parseSessionFromCookies(options.cookies.getAll(), options.cookiePrefix);
5
- return createClient({
16
+ const prefix = options.cookiePrefix ?? DEFAULT_COOKIE_PREFIX;
17
+ const session = parseSessionFromCookies(options.cookies.getAll(), prefix);
18
+ const client = createClient({
6
19
  url,
7
20
  anonKey,
21
+ auth: {
22
+ persistSession: false,
23
+ autoRefreshToken: false,
24
+ refreshExpiredToken: options.cookies.setAll !== undefined,
25
+ detectSessionInUrl: false,
26
+ },
8
27
  ...(session !== null && { initialSession: session }),
9
28
  });
29
+ writeSessionChanges(client, options.cookies, prefix);
30
+ return client;
31
+ }
32
+ /**
33
+ * Send every change to the client's session (a refresh, a sign-in, a sign-out) back to the browser
34
+ * through the adapter's `setAll`, so the next request reads the new tokens rather than the old ones.
35
+ */
36
+ function writeSessionChanges(client, cookies, prefix) {
37
+ if (cookies.setAll === undefined)
38
+ return;
39
+ // `onAuthStateChange` reports the current state as it subscribes: that is the cookie just read.
40
+ let subscribed = false;
41
+ client.auth.onAuthStateChange((_event, next) => {
42
+ if (!subscribed)
43
+ return;
44
+ try {
45
+ cookies.setAll?.([sessionCookie(next, prefix)]);
46
+ }
47
+ catch {
48
+ // The cookie store refused the write; the session still works for this request. Where cookies
49
+ // are read-only (a Server Component), `setAll` is left out and the client does not refresh.
50
+ }
51
+ });
52
+ subscribed = true;
10
53
  }
11
54
  //# sourceMappingURL=server-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-client.js","sourceRoot":"","sources":["../src/server-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAE/C,OAAO,EAAE,uBAAuB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AAED;;;GAGG;AACH,SAAS,mBAAmB,CAC1B,MAAiC,EACjC,OAAsB,EACtB,MAAc;IAEd,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS;QAAE,OAAM;IACxC,gGAAgG;IAChG,IAAI,UAAU,GAAG,KAAK,CAAA;IACtB,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE;QAC7C,IAAI,CAAC,UAAU;YAAE,OAAM;QACvB,IAAI,CAAC;YACH,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAA;QACjD,CAAC;QAAC,MAAM,CAAC;YACP,8FAA8F;YAC9F,4FAA4F;QAC9F,CAAC;IACH,CAAC,CAAC,CAAA;IACF,UAAU,GAAG,IAAI,CAAA;AACnB,CAAC"}
package/dist/types.d.ts CHANGED
@@ -6,20 +6,29 @@ export interface CookieOptions {
6
6
  httpOnly?: boolean | undefined;
7
7
  sameSite?: "strict" | "lax" | "none" | undefined;
8
8
  }
9
+ /** One cookie to write: `value` is unencoded, for the framework to encode as it writes any cookie. */
10
+ export interface CookieToSet {
11
+ name: string;
12
+ value: string;
13
+ options?: CookieOptions | undefined;
14
+ }
9
15
  export interface CookieAdapter {
10
16
  getAll(): Array<{
11
17
  name: string;
12
18
  value: string;
13
19
  }>;
14
- setAll(cookies: Array<{
15
- name: string;
16
- value: string;
17
- options?: CookieOptions | undefined;
18
- }>): void;
20
+ /**
21
+ * Writes the session cookie whenever the session changes on the server: a refreshed token, a
22
+ * sign-in, or a sign-out (an empty value with `maxAge: 0`). Leave it out where cookies cannot be
23
+ * written, such as a Server Component: without it the client never refreshes, since the browser
24
+ * would never receive the refresh token a refresh returns, and an expired access token is sent as
25
+ * it is and refused.
26
+ */
27
+ setAll?(cookies: CookieToSet[]): void;
19
28
  }
20
29
  export interface ServerClientOptions {
21
30
  cookies: CookieAdapter;
22
- /** Cookie name prefix. Default: "st". Supatype sets cookies as `st-<ref>-auth-token`. */
31
+ /** Cookie name prefix. Default: "st". The browser client writes its session as `st-auth-token`. */
23
32
  cookiePrefix?: string | undefined;
24
33
  }
25
34
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACzB,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC5B,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC9B,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,SAAS,CAAA;CACjD;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAChD,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAA;KAAE,CAAC,GAAG,IAAI,CAAA;CACnG;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,aAAa,CAAA;IACtB,yFAAyF;IACzF,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAClC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACzB,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC5B,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC9B,QAAQ,CAAC,EAAE,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,SAAS,CAAA;CACjD;AAED,sGAAsG;AACtG,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAA;CACpC;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAChD;;;;;;OAMG;IACH,MAAM,CAAC,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG,IAAI,CAAA;CACtC;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,aAAa,CAAA;IACtB,mGAAmG;IACnG,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAClC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supatype/ssr",
3
- "version": "0.3.6",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "description": "Supatype server-side rendering utilities, create a client from cookie-based auth for Server Components, Route Handlers, and middleware",
6
6
  "type": "module",
@@ -13,15 +13,17 @@
13
13
  }
14
14
  },
15
15
  "dependencies": {
16
- "@supatype/client": "0.3.6"
16
+ "@supatype/client": "0.8.0"
17
17
  },
18
18
  "devDependencies": {
19
19
  "@types/node": "^22",
20
- "typescript": "^5"
20
+ "typescript": "^5",
21
+ "vitest": "^4.0.18"
21
22
  },
22
23
  "scripts": {
23
24
  "build": "tsc --project tsconfig.json",
24
- "typecheck": "tsc --project tsconfig.json --noEmit",
25
+ "typecheck": "tsc --project tests/tsconfig.json --noEmit",
26
+ "test": "vitest run",
25
27
  "clean": "rm -rf dist *.tsbuildinfo"
26
28
  }
27
29
  }
@@ -1,8 +1,12 @@
1
1
  import type { Session, User } from "@supatype/client"
2
+ import type { CookieToSet } from "./types.js"
3
+
4
+ /** The prefix `@supatype/client` names its session cookie with: `st-auth-token`. */
5
+ export const DEFAULT_COOKIE_PREFIX = "st"
2
6
 
3
7
  export function parseSessionFromCookies(
4
8
  cookies: Array<{ name: string; value: string }>,
5
- prefix: string = "st",
9
+ prefix: string = DEFAULT_COOKIE_PREFIX,
6
10
  ): Session | null {
7
11
  const candidates = cookies.filter(
8
12
  (c) =>
@@ -25,31 +29,48 @@ export function parseSessionFromCookies(
25
29
  return null
26
30
  }
27
31
 
32
+ /** True for a JSON object: not null, not an array. */
33
+ function isJsonObject(value: unknown): value is Record<string, unknown> {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value)
35
+ }
36
+
28
37
  function parseSessionValue(value: string): Session | null {
29
38
  try {
30
- return normalizeSession(JSON.parse(decodeURIComponent(value)) as unknown)
39
+ return normalizeSession(JSON.parse(decodeURIComponent(value)))
31
40
  } catch { /* not JSON */ }
32
41
  try {
33
- return normalizeSession(JSON.parse(Buffer.from(value, "base64").toString("utf-8")) as unknown)
42
+ return normalizeSession(JSON.parse(decodeBase64(value)))
34
43
  } catch { /* not base64 JSON */ }
35
44
  return null
36
45
  }
37
46
 
38
- function normalizeSession(raw: unknown): Session | null {
39
- if (typeof raw !== "object" || raw === null) return null
40
- const r = raw as Record<string, unknown>
47
+ /**
48
+ * Base64 or base64url text decoded as UTF-8, with `atob` and `TextDecoder` rather than Node's
49
+ * `Buffer`: the server client also runs on edge runtimes, which have no `Buffer`. Throws on input
50
+ * that is not base64.
51
+ */
52
+ function decodeBase64(text: string): string {
53
+ const standard = text.replace(/-/g, "+").replace(/_/g, "/")
54
+ const binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4))
55
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
56
+ }
57
+
58
+ /**
59
+ * The session a cookie holds. One whose access token has expired is kept when it carries a refresh
60
+ * token: the first request the client makes refreshes it, and the server client writes the new
61
+ * tokens back through `setAll`.
62
+ */
63
+ function normalizeSession(r: unknown): Session | null {
64
+ if (!isJsonObject(r)) return null
41
65
  if (typeof r["access_token"] !== "string") return null
42
- if (isJwtExpired(r["access_token"])) return null
66
+ const refreshToken = typeof r["refresh_token"] === "string" ? r["refresh_token"] : ""
67
+ if (isJwtExpired(r["access_token"]) && refreshToken.trim() === "") return null
43
68
  return {
44
69
  accessToken: r["access_token"],
45
70
  tokenType: typeof r["token_type"] === "string" ? r["token_type"] : "bearer",
46
71
  expiresIn: typeof r["expires_in"] === "number" ? r["expires_in"] : 3600,
47
- refreshToken: typeof r["refresh_token"] === "string" ? r["refresh_token"] : "",
48
- user: normalizeUser(
49
- typeof r["user"] === "object" && r["user"] !== null
50
- ? (r["user"] as Record<string, unknown>)
51
- : {},
52
- ),
72
+ refreshToken,
73
+ user: normalizeUser(isJsonObject(r["user"]) ? r["user"] : {}),
53
74
  ...(typeof r["expires_at"] === "number" && { expiresAt: r["expires_at"] }),
54
75
  }
55
76
  }
@@ -58,9 +79,9 @@ function isJwtExpired(token: string): boolean {
58
79
  const parts = token.split(".")
59
80
  if (parts.length !== 3) return true
60
81
  try {
61
- const payload = JSON.parse(
62
- Buffer.from(parts[1]!, "base64").toString("utf-8"),
63
- ) as Record<string, unknown>
82
+ const payload = JSON.parse(decodeBase64(parts[1]!))
83
+ // A payload that is not an object reads as expired, as it did when reading it threw.
84
+ if (!isJsonObject(payload)) return true
64
85
  const exp = typeof payload["exp"] === "number" ? payload["exp"] : null
65
86
  if (exp === null) return false
66
87
  return Date.now() / 1000 > exp
@@ -72,8 +93,8 @@ function isJwtExpired(token: string): boolean {
72
93
  function normalizeUser(raw: Record<string, unknown>): User {
73
94
  return {
74
95
  id: typeof raw["id"] === "string" ? raw["id"] : "",
75
- appMetadata: (raw["app_metadata"] ?? {}) as Record<string, unknown>,
76
- userMetadata: (raw["user_metadata"] ?? {}) as Record<string, unknown>,
96
+ appMetadata: isJsonObject(raw["app_metadata"]) ? raw["app_metadata"] : {},
97
+ userMetadata: isJsonObject(raw["user_metadata"]) ? raw["user_metadata"] : {},
77
98
  createdAt: typeof raw["created_at"] === "string" ? raw["created_at"] : "",
78
99
  updatedAt: typeof raw["updated_at"] === "string" ? raw["updated_at"] : "",
79
100
  ...(typeof raw["email"] === "string" && { email: raw["email"] }),
@@ -81,3 +102,36 @@ function normalizeUser(raw: Record<string, unknown>): User {
81
102
  ...(typeof raw["role"] === "string" && { role: raw["role"] }),
82
103
  }
83
104
  }
105
+
106
+ /**
107
+ * The cookie that holds `session`, named and shaped as `@supatype/client` writes it in the browser
108
+ * and `parseSessionFromCookies` reads it; a null session clears the cookie.
109
+ */
110
+ export function sessionCookie(session: Session | null, prefix: string = DEFAULT_COOKIE_PREFIX): CookieToSet {
111
+ const name = `${prefix}-auth-token`
112
+ if (session === null) return { name, value: "", options: { path: "/", maxAge: 0 } }
113
+ const value = JSON.stringify({
114
+ access_token: session.accessToken,
115
+ refresh_token: session.refreshToken,
116
+ token_type: session.tokenType,
117
+ expires_in: session.expiresIn,
118
+ ...(session.expiresAt !== undefined && { expires_at: session.expiresAt }),
119
+ user: serializeUser(session.user),
120
+ })
121
+ // The browser client's cookie expires with the access token; one without `expiresAt` lasts the session.
122
+ const maxAge = session.expiresAt !== undefined ? Math.max(0, session.expiresAt - Math.floor(Date.now() / 1000)) : undefined
123
+ return { name, value, options: { path: "/", sameSite: "lax", ...(maxAge !== undefined && { maxAge }) } }
124
+ }
125
+
126
+ function serializeUser(user: User): Record<string, unknown> {
127
+ return {
128
+ id: user.id,
129
+ ...(user.email !== undefined && { email: user.email }),
130
+ ...(user.phone !== undefined && { phone: user.phone }),
131
+ ...(user.role !== undefined && { role: user.role }),
132
+ app_metadata: user.appMetadata,
133
+ user_metadata: user.userMetadata,
134
+ created_at: user.createdAt,
135
+ updated_at: user.updatedAt,
136
+ }
137
+ }