@kaidev-studio/cli-kit 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -25,6 +25,32 @@ await run(cli, [auth.command, ...myCommands]);
25
25
  - Commands are `command({ name, description, positionals, options, run })` and `group({ name, commands })`, with zod
26
26
  schemas; `.meta({ short: "x" })`, `.meta({ negatable: true })` and `.meta({ hidden: true })` tune options.
27
27
 
28
+ ## Scoped sessions, for daemons
29
+
30
+ A CLI that runs unattended (a runner, an agent) signs in with a scope instead of as the whole user:
31
+
32
+ ```ts
33
+ // The backend's Better Auth (`cliScopes` from `@kaidev-studio/cli-kit/server`):
34
+ plugins: [
35
+ deviceAuthorization({ ... }),
36
+ convex({ authConfig, jwt: { definePayload: ({ user, session }) => ({ name: user.name, email: user.email, scope: session.scope ?? "" }) } }),
37
+ cliScopes({ runner: { expiresIn: 90 * 24 * 60 * 60 } }),
38
+ ],
39
+
40
+ // The CLI:
41
+ export const auth = createAuth(cli, { clientId: "myapp-cli", server: "https://myapp.com", scope: "runner" });
42
+
43
+ // Convex functions: a runner's take `requireScope(ctx, "runner")`; everyone else's `requireScope(ctx)`, which
44
+ // refuses scoped sessions. Both refuse every identity while JWTs lack the `scope` claim.
45
+ ```
46
+
47
+ - A scoped session lasts its scope's `expiresIn` while unused, instead of Better Auth's, so a machine that was off
48
+ for weeks still signs in; every `auth.convex()` extends it. It must be at least Better Auth's `session.expiresIn`
49
+ plus `updateAge`.
50
+ - Better Auth's own routes refuse it, except `get-session`, `convex/token` and `sign-out`: it can't approve device
51
+ codes, change the user or revoke sessions.
52
+ - The plugin adds a `scope` field to the session table: regenerate the Better Auth schema.
53
+
28
54
  ## Releasing
29
55
 
30
56
  `npm version patch && git push --follow-tags`. The tag's workflow publishes with npm trusted publishing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaidev-studio/cli-kit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Boilerplate for a Bun CLI that signs in through its web app and updates itself",
5
5
  "type": "module",
6
6
  "repository": {
@@ -9,7 +9,8 @@
9
9
  },
10
10
  "exports": {
11
11
  ".": "./src/index.ts",
12
- "./auth": "./src/auth.ts"
12
+ "./auth": "./src/auth.ts",
13
+ "./server": "./src/server.ts"
13
14
  },
14
15
  "files": [
15
16
  "src",
@@ -27,7 +28,7 @@
27
28
  },
28
29
  "peerDependencies": {
29
30
  "@convex-dev/better-auth": ">=0.13.0",
30
- "better-auth": "^1.7.0",
31
+ "better-auth": ">=1.7.19 <1.8.0",
31
32
  "convex": "^1.31.0",
32
33
  "zod": "^4.0.0"
33
34
  },
package/src/auth.ts CHANGED
@@ -17,6 +17,11 @@ export type AuthConfig = {
17
17
  server: string;
18
18
  /** The web app the dev CLI signs in to, e.g. read from the app's .env; the installed CLI's `server` without it. */
19
19
  devServer?: () => Promise<string>;
20
+ /**
21
+ * The scope to sign in with, one the backend's `cliScopes` plugin defines, e.g. "runner" for a daemon: the session
22
+ * reaches only the Convex functions that `requireScope` it, and lasts as long as the scope says while unused.
23
+ */
24
+ scope?: string;
20
25
  /** Runs after `auth login` has stored the new session. */
21
26
  afterLogin?: () => Promise<unknown>;
22
27
  };
@@ -33,6 +38,9 @@ export const createCliAuthClient = ({ convexSiteUrl, token }: { convexSiteUrl: s
33
38
 
34
39
  type CliAuthClient = ReturnType<typeof createCliAuthClient>;
35
40
 
41
+ /** The scope `cliScopes` stamped on a session, which the client's types don't know about. */
42
+ const scopeOf = (session: object) => (session as { scope?: string | null }).scope ?? undefined;
43
+
36
44
  /** The device routes carry OAuth's `error_description` instead of a `message`. */
37
45
  const authError = (
38
46
  error: { message?: string | undefined; error_description?: string | undefined } | null | undefined,
@@ -90,7 +98,7 @@ export const createAuth = (cli: Cli, config: AuthConfig) => {
90
98
  const { convexUrl, convexSiteUrl } = await discover(server);
91
99
  const auth = createCliAuthClient({ convexSiteUrl });
92
100
 
93
- const { data: code, error } = await auth.device.code({ client_id: config.clientId });
101
+ const { data: code, error } = await auth.device.code({ client_id: config.clientId, scope: config.scope });
94
102
  if (error || !code) throw authError(error, "Couldn't start device sign-in");
95
103
  const userCode =
96
104
  code.user_code.length > 4 ? `${code.user_code.slice(0, 4)}-${code.user_code.slice(4)}` : code.user_code;
@@ -100,9 +108,10 @@ export const createAuth = (cli: Cli, config: AuthConfig) => {
100
108
 
101
109
  const signedIn = createCliAuthClient({ convexSiteUrl, token });
102
110
  const { data: session, error: sessionError } = await signedIn.getSession();
103
- if (sessionError || !session) {
111
+ if (sessionError || !session || scopeOf(session.session) !== config.scope) {
104
112
  // A session nobody stored would stay valid until it expired.
105
113
  await signedIn.signOut().catch(() => undefined);
114
+ if (session) throw new Error(`The app didn't grant the "${config.scope}" scope: does it use cliScopes?`);
106
115
  throw authError(sessionError, "Couldn't read the new session");
107
116
  }
108
117
  const previous = credentials.read();
@@ -162,6 +171,10 @@ export const createAuth = (cli: Cli, config: AuthConfig) => {
162
171
  const { data, error } = await createCliAuthClient(current).getSession();
163
172
  if (error) throw authError(error, "Couldn't read the session");
164
173
  if (!data) return undefined;
174
+ if (scopeOf(data.session) !== config.scope)
175
+ throw new Error(
176
+ `This machine isn't signed in with the "${config.scope}" scope. Run '${cli.program} auth login'.`,
177
+ );
165
178
  const expiresAt = new Date(data.session.expiresAt).getTime();
166
179
  if (expiresAt === current.expiresAt) return current;
167
180
  const refreshed = { ...current, expiresAt };
package/src/server.ts ADDED
@@ -0,0 +1,150 @@
1
+ import type { BetterAuthPlugin } from "better-auth";
2
+ import { APIError, createAuthMiddleware } from "better-auth/api";
3
+ import type { Auth, UserIdentity } from "convex/server";
4
+ import { ConvexError } from "convex/values";
5
+
6
+ /**
7
+ * How long a session of this scope lasts unused, in seconds; each use extends it, like Better Auth's `expiresIn`, and
8
+ * it's at least Better Auth's own `expiresIn` + `updateAge`, so Better Auth's own refresh can't stretch or shorten it.
9
+ */
10
+ export type ScopeConfig = { expiresIn: number };
11
+
12
+ /** The routes a scoped session may call: enough to stay signed in, get Convex tokens and sign out. */
13
+ const SCOPED_ROUTES = new Set(["/get-session", "/convex/token", "/sign-out"]);
14
+
15
+ /**
16
+ * Every session token a request carries, signed or not: a Bearer token, and the session cookie in `cookie` or in the
17
+ * Convex crossDomain plugin's `better-auth-cookie`. Those plugins turn theirs into the route's session cookie only for
18
+ * the route, not for the hooks after it, so this plugin reads them all itself.
19
+ */
20
+ const sessionTokens = (headers: Headers | undefined, cookieName: string) => {
21
+ const authorization = headers?.get("authorization");
22
+ const values = authorization?.slice(0, 7).toLowerCase() === "bearer " ? [authorization.slice(7).trim()] : [];
23
+ for (const cookies of [headers?.get("cookie"), headers?.get("better-auth-cookie")])
24
+ for (const cookie of cookies?.split(";") ?? []) {
25
+ const [name, ...rest] = cookie.split("=");
26
+ const value = rest.join("=").trim();
27
+ // Like better-call, which reads the route's cookies: a leading quote and the last character are dropped.
28
+ if (name?.trim() === cookieName) values.push(value.startsWith('"') ? value.slice(1, -1) : value);
29
+ }
30
+ return values.flatMap((value) => {
31
+ try {
32
+ return decodeURIComponent(value).split(".")[0] || [];
33
+ } catch {
34
+ return [];
35
+ }
36
+ });
37
+ };
38
+
39
+ type ReturnedSession = { session: { token: string; expiresAt: Date | string; scope?: string | null } } | null;
40
+
41
+ /**
42
+ * Scoped device sessions: a CLI that asks for a `scope` at device sign-in gets a session stamped with it, which lasts
43
+ * the scope's own `expiresIn` while unused (so a machine that was off for weeks still signs in), and which Better
44
+ * Auth's own routes refuse beyond SCOPED_ROUTES. The scope reaches Convex functions through the JWT: add
45
+ * `scope: session.scope ?? ""` in the Convex plugin's `jwt.definePayload`, and check it with `requireScope`.
46
+ */
47
+ export const cliScopes = (scopes: Record<string, ScopeConfig>) => {
48
+ const scopeOf = (name: string | null | undefined) =>
49
+ name && Object.hasOwn(scopes, name) ? (scopes[name] as ScopeConfig) : undefined;
50
+
51
+ return {
52
+ id: "cli-scopes",
53
+ init: (ctx) => {
54
+ for (const [name, { expiresIn }] of Object.entries(scopes))
55
+ if (expiresIn < ctx.sessionConfig.expiresIn + ctx.sessionConfig.updateAge)
56
+ throw new Error(`cliScopes: "${name}" must last at least Better Auth's session.expiresIn + updateAge`);
57
+ },
58
+ schema: { session: { fields: { scope: { type: "string", required: false, input: false } } } },
59
+ hooks: {
60
+ before: [
61
+ {
62
+ matcher: (ctx) => ctx.path === "/device/code",
63
+ handler: createAuthMiddleware(async (ctx) => {
64
+ const scope = ctx.body?.scope;
65
+ if (scope !== undefined && !scopeOf(scope))
66
+ throw new APIError("BAD_REQUEST", {
67
+ error: "invalid_scope",
68
+ error_description: `Unknown scope: ${scope}`,
69
+ });
70
+ }),
71
+ },
72
+ {
73
+ matcher: (ctx) => !SCOPED_ROUTES.has(ctx.path ?? ""),
74
+ handler: createAuthMiddleware(async (ctx) => {
75
+ // All of them: which one the route uses depends on which are valid.
76
+ for (const token of sessionTokens(ctx.headers, ctx.context.authCookies.sessionToken.name)) {
77
+ const current = await ctx.context.internalAdapter.findSession(token);
78
+ if (current?.session.scope)
79
+ throw new APIError("FORBIDDEN", {
80
+ message: `A "${current.session.scope}" session can't call ${ctx.path}`,
81
+ });
82
+ }
83
+ }),
84
+ },
85
+ ],
86
+ after: [
87
+ {
88
+ // The session the device code was redeemed for takes the code's scope and that scope's lifetime.
89
+ matcher: (ctx) => ctx.path === "/device/token",
90
+ handler: createAuthMiddleware(async (ctx) => {
91
+ const returned = ctx.context.returned as { access_token?: string; scope?: string } | undefined;
92
+ if (!returned?.access_token || !returned.scope) return;
93
+ const config = scopeOf(returned.scope);
94
+ const stamped =
95
+ config &&
96
+ (await ctx.context.internalAdapter.updateSession(returned.access_token, {
97
+ scope: returned.scope,
98
+ expiresAt: new Date(Date.now() + config.expiresIn * 1000),
99
+ }));
100
+ if (stamped) return;
101
+ // A scope removed since the code was approved: never hand out the full session instead.
102
+ await ctx.context.internalAdapter.deleteSession(returned.access_token);
103
+ throw new APIError("BAD_REQUEST", {
104
+ error: "invalid_scope",
105
+ error_description: `Unknown scope: ${returned.scope}`,
106
+ });
107
+ }),
108
+ },
109
+ {
110
+ // Better Auth extends sessions by its own `expiresIn` on both routes; scoped ones get their scope's instead.
111
+ matcher: (ctx) => ctx.path === "/get-session" || ctx.path === "/convex/token",
112
+ handler: createAuthMiddleware(async (ctx) => {
113
+ const returned = ctx.context.returned as ReturnedSession;
114
+ // /get-session answers the live session (null once expired); /convex/token signs a JWT only for one.
115
+ const session =
116
+ ctx.path === "/get-session"
117
+ ? returned?.session
118
+ : (returned as { token?: unknown } | undefined)?.token
119
+ ? (ctx.context.session?.session as NonNullable<ReturnedSession>["session"] | undefined)
120
+ : undefined;
121
+ const config = scopeOf(session?.scope);
122
+ if (!session || !config) return;
123
+ const updateAge = ctx.context.sessionConfig.updateAge * 1000;
124
+ const extended = Date.now() + config.expiresIn * 1000;
125
+ if (extended - new Date(session.expiresAt).getTime() < updateAge) return;
126
+ const expiresAt = new Date(extended);
127
+ await ctx.context.internalAdapter.updateSession(session.token, { expiresAt });
128
+ if (ctx.path === "/get-session") return ctx.json({ ...returned, session: { ...session, expiresAt } });
129
+ }),
130
+ },
131
+ ],
132
+ },
133
+ } satisfies BetterAuthPlugin;
134
+ };
135
+
136
+ /**
137
+ * A Convex function's signed-in identity, when its session has exactly `scope`; no `scope` means an unscoped session,
138
+ * whose JWT carries `scope: ""`.
139
+ * Call it without one in every function a person uses, so scoped sessions reach only the functions written for them.
140
+ */
141
+ export const requireScope = async (ctx: { auth: Auth }, scope?: string): Promise<UserIdentity> => {
142
+ const identity = await ctx.auth.getUserIdentity();
143
+ if (!identity) throw new ConvexError("Not signed in");
144
+ // Without the claim, a scoped session would pass as a person's: refuse every identity until it's configured.
145
+ if (typeof identity.scope !== "string")
146
+ throw new ConvexError('Convex JWTs have no scope claim: add `scope: session.scope ?? ""` to jwt.definePayload');
147
+ if ((identity.scope || undefined) !== scope)
148
+ throw new ConvexError(scope ? `This needs a "${scope}" session` : "A scoped session can't call this");
149
+ return identity;
150
+ };