@quickback-dev/cli 0.9.5

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.
Files changed (122) hide show
  1. package/README.md +7 -0
  2. package/dist/commands/claude.d.ts +13 -0
  3. package/dist/commands/claude.d.ts.map +1 -0
  4. package/dist/commands/claude.js +305 -0
  5. package/dist/commands/claude.js.map +1 -0
  6. package/dist/commands/compile.d.ts +18 -0
  7. package/dist/commands/compile.d.ts.map +1 -0
  8. package/dist/commands/compile.js +326 -0
  9. package/dist/commands/compile.js.map +1 -0
  10. package/dist/commands/create.d.ts +18 -0
  11. package/dist/commands/create.d.ts.map +1 -0
  12. package/dist/commands/create.js +798 -0
  13. package/dist/commands/create.js.map +1 -0
  14. package/dist/commands/cursor.d.ts +11 -0
  15. package/dist/commands/cursor.d.ts.map +1 -0
  16. package/dist/commands/cursor.js +156 -0
  17. package/dist/commands/cursor.js.map +1 -0
  18. package/dist/commands/docs.d.ts +10 -0
  19. package/dist/commands/docs.d.ts.map +1 -0
  20. package/dist/commands/docs.js +93 -0
  21. package/dist/commands/docs.js.map +1 -0
  22. package/dist/commands/example.d.ts +7 -0
  23. package/dist/commands/example.d.ts.map +1 -0
  24. package/dist/commands/example.js +153 -0
  25. package/dist/commands/example.js.map +1 -0
  26. package/dist/commands/init.d.ts +6 -0
  27. package/dist/commands/init.d.ts.map +1 -0
  28. package/dist/commands/init.js +383 -0
  29. package/dist/commands/init.js.map +1 -0
  30. package/dist/commands/login.d.ts +16 -0
  31. package/dist/commands/login.d.ts.map +1 -0
  32. package/dist/commands/login.js +287 -0
  33. package/dist/commands/login.js.map +1 -0
  34. package/dist/commands/logout.d.ts +7 -0
  35. package/dist/commands/logout.d.ts.map +1 -0
  36. package/dist/commands/logout.js +19 -0
  37. package/dist/commands/logout.js.map +1 -0
  38. package/dist/commands/mcp.d.ts +21 -0
  39. package/dist/commands/mcp.d.ts.map +1 -0
  40. package/dist/commands/mcp.js +331 -0
  41. package/dist/commands/mcp.js.map +1 -0
  42. package/dist/commands/whoami.d.ts +7 -0
  43. package/dist/commands/whoami.d.ts.map +1 -0
  44. package/dist/commands/whoami.js +37 -0
  45. package/dist/commands/whoami.js.map +1 -0
  46. package/dist/cursor/quickback.mdc +277 -0
  47. package/dist/docs/content.d.ts +7 -0
  48. package/dist/docs/content.d.ts.map +1 -0
  49. package/dist/docs/content.js +577 -0
  50. package/dist/docs/content.js.map +1 -0
  51. package/dist/examples/recruitment.tar.gz +0 -0
  52. package/dist/index.d.ts +12 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +188 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/lib/api-client.d.ts +103 -0
  57. package/dist/lib/api-client.d.ts.map +1 -0
  58. package/dist/lib/api-client.js +231 -0
  59. package/dist/lib/api-client.js.map +1 -0
  60. package/dist/lib/api-client.test.d.ts +2 -0
  61. package/dist/lib/api-client.test.d.ts.map +1 -0
  62. package/dist/lib/api-client.test.js +133 -0
  63. package/dist/lib/api-client.test.js.map +1 -0
  64. package/dist/lib/artifact-routing.d.ts +8 -0
  65. package/dist/lib/artifact-routing.d.ts.map +1 -0
  66. package/dist/lib/artifact-routing.js +34 -0
  67. package/dist/lib/artifact-routing.js.map +1 -0
  68. package/dist/lib/artifact-routing.test.d.ts +2 -0
  69. package/dist/lib/artifact-routing.test.d.ts.map +1 -0
  70. package/dist/lib/artifact-routing.test.js +37 -0
  71. package/dist/lib/artifact-routing.test.js.map +1 -0
  72. package/dist/lib/async-utils.d.ts +6 -0
  73. package/dist/lib/async-utils.d.ts.map +1 -0
  74. package/dist/lib/async-utils.js +26 -0
  75. package/dist/lib/async-utils.js.map +1 -0
  76. package/dist/lib/auth.d.ts +55 -0
  77. package/dist/lib/auth.d.ts.map +1 -0
  78. package/dist/lib/auth.js +102 -0
  79. package/dist/lib/auth.js.map +1 -0
  80. package/dist/lib/compiler-stubs.d.ts +108 -0
  81. package/dist/lib/compiler-stubs.d.ts.map +1 -0
  82. package/dist/lib/compiler-stubs.js +142 -0
  83. package/dist/lib/compiler-stubs.js.map +1 -0
  84. package/dist/lib/drizzle-meta-routing.test.d.ts +2 -0
  85. package/dist/lib/drizzle-meta-routing.test.d.ts.map +1 -0
  86. package/dist/lib/drizzle-meta-routing.test.js +123 -0
  87. package/dist/lib/drizzle-meta-routing.test.js.map +1 -0
  88. package/dist/lib/file-loader.d.ts +165 -0
  89. package/dist/lib/file-loader.d.ts.map +1 -0
  90. package/dist/lib/file-loader.js +577 -0
  91. package/dist/lib/file-loader.js.map +1 -0
  92. package/dist/lib/file-loader.test.d.ts +2 -0
  93. package/dist/lib/file-loader.test.d.ts.map +1 -0
  94. package/dist/lib/file-loader.test.js +75 -0
  95. package/dist/lib/file-loader.test.js.map +1 -0
  96. package/dist/lib/file-writer.d.ts +30 -0
  97. package/dist/lib/file-writer.d.ts.map +1 -0
  98. package/dist/lib/file-writer.js +122 -0
  99. package/dist/lib/file-writer.js.map +1 -0
  100. package/dist/lib/helpers.d.ts +39 -0
  101. package/dist/lib/helpers.d.ts.map +1 -0
  102. package/dist/lib/helpers.js +299 -0
  103. package/dist/lib/helpers.js.map +1 -0
  104. package/dist/lib/markdown-renderer.d.ts +8 -0
  105. package/dist/lib/markdown-renderer.d.ts.map +1 -0
  106. package/dist/lib/markdown-renderer.js +151 -0
  107. package/dist/lib/markdown-renderer.js.map +1 -0
  108. package/dist/lib/shell.d.ts +15 -0
  109. package/dist/lib/shell.d.ts.map +1 -0
  110. package/dist/lib/shell.js +32 -0
  111. package/dist/lib/shell.js.map +1 -0
  112. package/dist/skill/SKILL.md +887 -0
  113. package/dist/skill/agents/quickback-specialist/AGENT.md +298 -0
  114. package/dist/templates/registry.d.ts +36 -0
  115. package/dist/templates/registry.d.ts.map +1 -0
  116. package/dist/templates/registry.js +181 -0
  117. package/dist/templates/registry.js.map +1 -0
  118. package/package.json +55 -0
  119. package/src/cursor/quickback.mdc +277 -0
  120. package/src/examples/recruitment.tar.gz +0 -0
  121. package/src/skill/SKILL.md +887 -0
  122. package/src/skill/agents/quickback-specialist/AGENT.md +298 -0
@@ -0,0 +1,383 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
2
+ import { join, resolve } from "path";
3
+ import pc from "picocolors";
4
+ export async function init(options) {
5
+ const targetPath = resolve(options?.path || ".");
6
+ const quickbackPath = join(targetPath, "quickback");
7
+ // Check if quickback folder already exists
8
+ if (existsSync(quickbackPath)) {
9
+ console.error(pc.red("Error: quickback folder already exists in this directory"));
10
+ process.exit(1);
11
+ }
12
+ console.log(pc.cyan("Creating quickback project structure..."));
13
+ try {
14
+ // Create folder structure
15
+ mkdirSync(quickbackPath, { recursive: true });
16
+ mkdirSync(join(quickbackPath, "definitions"), { recursive: true });
17
+ mkdirSync(join(quickbackPath, "definitions", "auth"), { recursive: true });
18
+ mkdirSync(join(quickbackPath, "definitions", "features"), { recursive: true });
19
+ mkdirSync(join(quickbackPath, "definitions", "features", "todos"), { recursive: true });
20
+ mkdirSync(join(quickbackPath, "output"), { recursive: true });
21
+ // Create quickback.config.ts with new provider-based format
22
+ const configContent = `/**
23
+ * Quickback Configuration
24
+ *
25
+ * This file defines your backend configuration using the provider system.
26
+ * Use presets for quick setup, or define individual providers for customization.
27
+ */
28
+ import { defineConfig } from "@quickback/compiler";
29
+ import { cloudflare } from "@quickback/compiler/presets";
30
+
31
+ export default defineConfig({
32
+ // Project settings
33
+ name: "my-quickback-app",
34
+ template: "hono", // "hono" | "nextjs"
35
+
36
+ // Use a preset for quick setup (includes runtime, database, storage, auth)
37
+ providers: cloudflare({
38
+ // Optional customization:
39
+ // databaseBinding: "DATABASE",
40
+ // kvBinding: "KV",
41
+ }),
42
+
43
+ // Build settings
44
+ build: {
45
+ outputDir: "./output",
46
+ },
47
+ });
48
+
49
+ /**
50
+ * Alternative: For local development with Bun and SQLite, use:
51
+ *
52
+ * import { bun } from "@quickback/compiler/presets";
53
+ *
54
+ * providers: bun({
55
+ * databasePath: "./data/app.db",
56
+ * }),
57
+ */
58
+ `;
59
+ writeFileSync(join(quickbackPath, "quickback.config.ts"), configContent);
60
+ // Create auth definition
61
+ const authConfigContent = `/**
62
+ * Better Auth Configuration
63
+ *
64
+ * This file defines your authentication configuration for Better Auth.
65
+ * Modify this to customize authentication behavior in your application.
66
+ */
67
+
68
+ export const authConfig = {
69
+ // Core settings
70
+ autoDetectIpAddress: true,
71
+ geolocationTracking: true,
72
+
73
+ // Authentication methods
74
+ emailAndPassword: {
75
+ enabled: true,
76
+ requireEmailVerification: false
77
+ },
78
+
79
+ // Plugins - Add or remove based on your needs
80
+ // Available plugins: "anonymous", "openAPI", "twoFactor", "passkey", "magicLink"
81
+ plugins: ["anonymous"],
82
+
83
+ // Rate limiting configuration
84
+ rateLimit: {
85
+ enabled: true,
86
+ window: 60, // seconds (minimum for KV is 60s)
87
+ max: 100, // requests per window
88
+ customRules: {
89
+ // Add custom rate limit rules for specific endpoints
90
+ "/sign-in/email": {
91
+ window: 60,
92
+ max: 10
93
+ },
94
+ "/sign-in/social": {
95
+ window: 60,
96
+ max: 10
97
+ }
98
+ }
99
+ },
100
+
101
+ // Social providers - Enable and configure as needed
102
+ socialProviders: {
103
+ google: {
104
+ enabled: false,
105
+ // clientId and clientSecret will be read from environment variables
106
+ },
107
+ github: {
108
+ enabled: false,
109
+ },
110
+ discord: {
111
+ enabled: false,
112
+ }
113
+ },
114
+
115
+ // Session configuration
116
+ session: {
117
+ expiresInDays: 30,
118
+ updateAgeInDays: 1
119
+ },
120
+
121
+ // Database configuration
122
+ database: {
123
+ // Additional database-specific options
124
+ usePlural: true, // Use plural table names (users, sessions, etc.)
125
+ debugLogs: true // Enable debug logging for database operations
126
+ }
127
+ };
128
+ `;
129
+ writeFileSync(join(quickbackPath, "definitions", "auth", "better-auth.ts"), authConfigContent);
130
+ // Create example todos feature
131
+ const todosSchemaContent = `/**
132
+ * Todos Feature Schema
133
+ *
134
+ * Example feature definition showing how to create database schemas
135
+ * and API endpoints for your application features.
136
+ */
137
+
138
+ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
139
+ import { sql } from "drizzle-orm";
140
+
141
+ export const todos = sqliteTable("todos", {
142
+ id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
143
+ userId: text("user_id").notNull(),
144
+ title: text("title").notNull(),
145
+ description: text("description"),
146
+ completed: integer("completed", { mode: "boolean" }).default(false).notNull(),
147
+ createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
148
+ updatedAt: integer("updated_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
149
+ });
150
+
151
+ export type Todo = typeof todos.$inferSelect;
152
+ export type NewTodo = typeof todos.$inferInsert;
153
+ `;
154
+ writeFileSync(join(quickbackPath, "definitions", "features", "todos", "schema.ts"), todosSchemaContent);
155
+ // Create todos API routes
156
+ const todosRoutesContent = `/**
157
+ * Todos API Routes
158
+ *
159
+ * Example API implementation for the todos feature.
160
+ * Shows how to create authenticated CRUD endpoints.
161
+ */
162
+
163
+ import { Hono } from "hono";
164
+ import { eq, and } from "drizzle-orm";
165
+ import type { Todo, NewTodo } from "./schema";
166
+
167
+ export function createTodosRoutes(auth: any, db: any, todos: any) {
168
+ const app = new Hono();
169
+
170
+ // Get all todos for the authenticated user
171
+ app.get("/", async (c) => {
172
+ const session = await auth.api.getSession({
173
+ headers: c.req.raw.headers,
174
+ });
175
+
176
+ if (!session) {
177
+ return c.json({ error: "Unauthorized" }, 401);
178
+ }
179
+
180
+ const userTodos = await db
181
+ .select()
182
+ .from(todos)
183
+ .where(eq(todos.userId, session.user.id));
184
+
185
+ return c.json(userTodos);
186
+ });
187
+
188
+ // Create a new todo
189
+ app.post("/", async (c) => {
190
+ const session = await auth.api.getSession({
191
+ headers: c.req.raw.headers,
192
+ });
193
+
194
+ if (!session) {
195
+ return c.json({ error: "Unauthorized" }, 401);
196
+ }
197
+
198
+ const body = await c.req.json<{ title: string; description?: string }>();
199
+
200
+ if (!body.title) {
201
+ return c.json({ error: "Title is required" }, 400);
202
+ }
203
+
204
+ const newTodo: NewTodo = {
205
+ userId: session.user.id,
206
+ title: body.title,
207
+ description: body.description,
208
+ };
209
+
210
+ const [todo] = await db.insert(todos).values(newTodo).returning();
211
+ return c.json(todo, 201);
212
+ });
213
+
214
+ // Update a todo
215
+ app.patch("/:id", async (c) => {
216
+ const session = await auth.api.getSession({
217
+ headers: c.req.raw.headers,
218
+ });
219
+
220
+ if (!session) {
221
+ return c.json({ error: "Unauthorized" }, 401);
222
+ }
223
+
224
+ const id = c.req.param("id");
225
+ const body = await c.req.json<{ title?: string; description?: string; completed?: boolean }>();
226
+
227
+ const [updatedTodo] = await db
228
+ .update(todos)
229
+ .set({
230
+ ...body,
231
+ updatedAt: new Date(),
232
+ })
233
+ .where(and(eq(todos.id, id), eq(todos.userId, session.user.id)))
234
+ .returning();
235
+
236
+ if (!updatedTodo) {
237
+ return c.json({ error: "Todo not found" }, 404);
238
+ }
239
+
240
+ return c.json(updatedTodo);
241
+ });
242
+
243
+ // Delete a todo
244
+ app.delete("/:id", async (c) => {
245
+ const session = await auth.api.getSession({
246
+ headers: c.req.raw.headers,
247
+ });
248
+
249
+ if (!session) {
250
+ return c.json({ error: "Unauthorized" }, 401);
251
+ }
252
+
253
+ const id = c.req.param("id");
254
+
255
+ const [deletedTodo] = await db
256
+ .delete(todos)
257
+ .where(and(eq(todos.id, id), eq(todos.userId, session.user.id)))
258
+ .returning();
259
+
260
+ if (!deletedTodo) {
261
+ return c.json({ error: "Todo not found" }, 404);
262
+ }
263
+
264
+ return c.json({ message: "Todo deleted successfully" });
265
+ });
266
+
267
+ return app;
268
+ }
269
+ `;
270
+ writeFileSync(join(quickbackPath, "definitions", "features", "todos", "routes.ts"), todosRoutesContent);
271
+ // Create todos README
272
+ const todosReadmeContent = `# Todos Feature
273
+
274
+ This is an example feature showing how to structure your application features in Quickback.
275
+
276
+ ## Structure
277
+
278
+ - **schema.ts** - Defines the database schema using Drizzle ORM
279
+ - **routes.ts** - Implements the API endpoints for CRUD operations
280
+
281
+ ## Usage
282
+
283
+ This feature will be automatically integrated into your application when you run the Quickback compiler. The routes will be mounted at \`/api/todos\`.
284
+
285
+ ## Endpoints
286
+
287
+ - \`GET /api/todos\` - Get all todos for the authenticated user
288
+ - \`POST /api/todos\` - Create a new todo
289
+ - \`PATCH /api/todos/:id\` - Update a todo
290
+ - \`DELETE /api/todos/:id\` - Delete a todo
291
+
292
+ All endpoints require authentication via Better Auth sessions.
293
+ `;
294
+ writeFileSync(join(quickbackPath, "definitions", "features", "todos", "README.md"), todosReadmeContent);
295
+ // Create .gitignore
296
+ const gitignoreContent = `# Output directory
297
+ output/
298
+
299
+ # Dependencies
300
+ node_modules/
301
+
302
+ # Environment files
303
+ .env
304
+ .env.local
305
+ .env.*.local
306
+
307
+ # IDE
308
+ .vscode/
309
+ .idea/
310
+
311
+ # OS
312
+ .DS_Store
313
+ Thumbs.db
314
+
315
+ # Logs
316
+ *.log
317
+
318
+ # Build artifacts
319
+ dist/
320
+ build/
321
+ .next/
322
+ `;
323
+ writeFileSync(join(quickbackPath, ".gitignore"), gitignoreContent);
324
+ // Create README
325
+ const readmeContent = `# Quickback Project
326
+
327
+ This is a Quickback project structure for building Cloudflare Workers applications with authentication.
328
+
329
+ ## Structure
330
+
331
+ - **quickback.config.ts** - Main configuration file for your project
332
+ - **definitions/** - Contains all your feature and configuration definitions
333
+ - **auth/** - Authentication configuration (Better Auth)
334
+ - **features/** - Your application features (APIs, schemas, etc.)
335
+ - **output/** - Generated code output (gitignored)
336
+
337
+ ## Getting Started
338
+
339
+ 1. Customize \`quickback.config.ts\` with your project settings
340
+ 2. Modify \`definitions/auth/better-auth.ts\` for authentication configuration
341
+ 3. Add your own features in \`definitions/features/\`
342
+ 4. Run the Quickback compiler to generate your application:
343
+
344
+ \`\`\`bash
345
+ npx @quickback/compiler generate
346
+ \`\`\`
347
+
348
+ ## Adding Features
349
+
350
+ Create a new directory under \`definitions/features/\` with:
351
+ - \`schema.ts\` - Database schema definitions
352
+ - \`routes.ts\` - API route implementations
353
+ - Any other files needed for your feature
354
+
355
+ ## Environment Variables
356
+
357
+ Configure the following in your \`.env\` file:
358
+ - \`CLOUDFLARE_ACCOUNT_ID\` - Your Cloudflare account ID
359
+ - Social provider credentials (if using social auth)
360
+ - Database connection strings (for Hyperdrive)
361
+
362
+ ## Learn More
363
+
364
+ - [Quickback Documentation](https://github.com/quickback/quickback-compiler)
365
+ - [Better Auth Documentation](https://www.better-auth.com)
366
+ - [Cloudflare Workers Documentation](https://developers.cloudflare.com/workers)
367
+ `;
368
+ writeFileSync(join(quickbackPath, "README.md"), readmeContent);
369
+ console.log(pc.green("\n✅ Quickback project structure created successfully!"));
370
+ console.log(pc.cyan("\nNext steps:"));
371
+ console.log(pc.white(` 1. cd ${quickbackPath}`));
372
+ console.log(pc.white(" 2. Customize quickback.config.ts"));
373
+ console.log(pc.white(" 3. Modify auth configuration in definitions/auth/"));
374
+ console.log(pc.white(" 4. Add your features in definitions/features/"));
375
+ console.log(pc.white(" 5. Run: npx @quickback/compiler generate"));
376
+ console.log(pc.cyan("\nFor more information, see the README.md file in the quickback folder."));
377
+ }
378
+ catch (error) {
379
+ console.error(pc.red("Error creating quickback structure:"), error);
380
+ process.exit(1);
381
+ }
382
+ }
383
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../../src/commands/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,MAAM,YAAY,CAAC;AAM5B,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,OAAqB;IAC5C,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,EAAE,IAAI,IAAI,GAAG,CAAC,CAAC;IACjD,MAAM,aAAa,GAAG,IAAI,CAAC,UAAU,E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AAG,CAAC,EAAE,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAC,CAAC;QAC/E,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,WAAW,aAAa,EAAE,CAAC,CAAC,CAAC;QAClD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC,CAAC;QAC5D,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,qDAAqD,CAAC,CAAC,CAAC;QAC7E,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,iDAAiD,CAAC,CAAC,CAAC;QACzE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,4CAA4C,CAAC,CAAC,CAAC;QACpE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,yEAAyE,CAAC,CAAC,CAAC;IAEpG,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,qCAAqC,CAAC,EAAE,KAAK,CAAC,CAAC;QACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Login Command
3
+ *
4
+ * Uses OAuth 2.0 Device Authorization Grant (RFC 8628) for CLI authentication.
5
+ * Works in headless environments (SSH, containers) and is more secure than URL-based tokens.
6
+ *
7
+ * After authentication, the CLI:
8
+ * 1. Lists user's organizations
9
+ * 2. Prompts to select one (or auto-selects if only one)
10
+ * 3. Sets the active organization on the session
11
+ *
12
+ * The session is stored in Better Auth's sessions table and appears
13
+ * in the Manage Devices page where users can revoke it.
14
+ */
15
+ export declare function login(): Promise<void>;
16
+ //# sourceMappingURL=login.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../src/commands/login.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAkDH,wBAAsB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CA4G3C"}
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Login Command
3
+ *
4
+ * Uses OAuth 2.0 Device Authorization Grant (RFC 8628) for CLI authentication.
5
+ * Works in headless environments (SSH, containers) and is more secure than URL-based tokens.
6
+ *
7
+ * After authentication, the CLI:
8
+ * 1. Lists user's organizations
9
+ * 2. Prompts to select one (or auto-selects if only one)
10
+ * 3. Sets the active organization on the session
11
+ *
12
+ * The session is stored in Better Auth's sessions table and appears
13
+ * in the Manage Devices page where users can revoke it.
14
+ */
15
+ import { exec } from 'child_process';
16
+ import pc from 'picocolors';
17
+ import ora from 'ora';
18
+ import prompts from 'prompts';
19
+ import { storeCredentials } from '../lib/auth.js';
20
+ const AUTH_URL = process.env.QUICKBACK_AUTH_URL || 'https://api.quickback.dev';
21
+ const CLIENT_ID = 'quickback-cli';
22
+ export async function login() {
23
+ console.log(pc.bold('\n🔐 Quickback Login\n'));
24
+ const spinner = ora('Requesting device authorization...').start();
25
+ try {
26
+ // Step 1: Request device code
27
+ const deviceCode = await requestDeviceCode();
28
+ spinner.stop();
29
+ // Step 2: Display user code and open browser
30
+ console.log(pc.cyan('━'.repeat(50)));
31
+ console.log();
32
+ console.log(` ${pc.bold('Your code:')} ${pc.green(pc.bold(formatUserCode(deviceCode.user_code)))}`);
33
+ console.log();
34
+ console.log(` Visit: ${pc.underline(deviceCode.verification_uri)}`);
35
+ console.log();
36
+ console.log(pc.cyan('━'.repeat(50)));
37
+ console.log();
38
+ // Try to open browser
39
+ const verificationUrl = deviceCode.verification_uri_complete || deviceCode.verification_uri;
40
+ openBrowser(verificationUrl);
41
+ // Step 3: Poll for Better Auth token
42
+ const pollSpinner = ora('Waiting for authorization...').start();
43
+ const betterAuthToken = await pollForToken(deviceCode.device_code, deviceCode.interval);
44
+ // Step 4: Exchange for session token (stored in DB, appears in Manage Devices)
45
+ pollSpinner.text = 'Completing authentication...';
46
+ const sessionToken = await exchangeToken(betterAuthToken.access_token);
47
+ pollSpinner.stop();
48
+ console.log(pc.green('\n✓ Login successful!'));
49
+ console.log(pc.gray(`Welcome, ${sessionToken.user?.name || sessionToken.user?.email || 'user'}!`));
50
+ // Step 5: List and select organization
51
+ let activeOrganization;
52
+ const orgSpinner = ora('Loading organizations...').start();
53
+ try {
54
+ const organizations = await listOrganizations(sessionToken.access_token);
55
+ orgSpinner.stop();
56
+ if (organizations.length > 0) {
57
+ if (organizations.length === 1) {
58
+ // Auto-select if only one organization
59
+ activeOrganization = organizations[0];
60
+ console.log(pc.gray(`\nUsing organization: ${pc.bold(activeOrganization.name)}`));
61
+ }
62
+ else {
63
+ // Prompt user to select
64
+ console.log();
65
+ const response = await prompts({
66
+ type: 'select',
67
+ name: 'organization',
68
+ message: 'Select an organization:',
69
+ choices: organizations.map(org => ({
70
+ title: org.name,
71
+ description: org.slug,
72
+ value: org,
73
+ })),
74
+ });
75
+ if (response.organization) {
76
+ activeOrganization = response.organization;
77
+ }
78
+ }
79
+ // Set active organization on the session
80
+ if (activeOrganization) {
81
+ const setOrgSpinner = ora('Setting active organization...').start();
82
+ await setActiveOrganization(sessionToken.access_token, activeOrganization.id);
83
+ setOrgSpinner.stop();
84
+ console.log(pc.green(`✓ Active organization: ${activeOrganization.name}`));
85
+ }
86
+ }
87
+ }
88
+ catch (orgError) {
89
+ orgSpinner.stop();
90
+ // Don't fail login if org listing fails - user can still use CLI
91
+ console.log(pc.yellow('\nCould not load organizations. You can set one later with: quickback org use <slug>'));
92
+ }
93
+ // Step 6: Store credentials with organization info
94
+ await storeCredentials({
95
+ token: sessionToken.access_token,
96
+ user: sessionToken.user,
97
+ expiresAt: sessionToken.session?.expiresAt || new Date(Date.now() + sessionToken.expires_in * 1000).toISOString(),
98
+ organization: activeOrganization ? {
99
+ id: activeOrganization.id,
100
+ name: activeOrganization.name,
101
+ slug: activeOrganization.slug,
102
+ } : undefined,
103
+ });
104
+ if (sessionToken.user?.tier === 'pro') {
105
+ console.log(pc.cyan('\nYou have access to Pro templates.'));
106
+ }
107
+ else {
108
+ console.log(pc.gray('\nUpgrade to Pro for premium templates: https://quickback.dev/pricing'));
109
+ }
110
+ console.log();
111
+ }
112
+ catch (error) {
113
+ spinner.stop();
114
+ if (error instanceof Error) {
115
+ console.error(pc.red('\n✗ Login failed:'), error.message);
116
+ }
117
+ process.exit(1);
118
+ }
119
+ }
120
+ /**
121
+ * Request a device code from the auth server
122
+ */
123
+ async function requestDeviceCode() {
124
+ const response = await fetch(`${AUTH_URL}/auth/v1/device/code`, {
125
+ method: 'POST',
126
+ headers: {
127
+ 'Content-Type': 'application/json',
128
+ 'User-Agent': 'quickback-cli',
129
+ },
130
+ body: JSON.stringify({
131
+ client_id: CLIENT_ID,
132
+ scope: 'openid profile email',
133
+ }),
134
+ });
135
+ if (!response.ok) {
136
+ const error = await response.json().catch(() => ({}));
137
+ throw new Error(error.error_description || 'Failed to request device code');
138
+ }
139
+ return response.json();
140
+ }
141
+ /**
142
+ * Poll for access token
143
+ */
144
+ async function pollForToken(deviceCode, interval) {
145
+ let pollingInterval = interval;
146
+ const maxAttempts = 120; // 10 minutes max at 5s intervals
147
+ let attempts = 0;
148
+ return new Promise((resolve, reject) => {
149
+ const poll = async () => {
150
+ attempts++;
151
+ if (attempts > maxAttempts) {
152
+ reject(new Error('Authorization timed out. Please try again.'));
153
+ return;
154
+ }
155
+ try {
156
+ const response = await fetch(`${AUTH_URL}/auth/v1/device/token`, {
157
+ method: 'POST',
158
+ headers: {
159
+ 'Content-Type': 'application/json',
160
+ 'User-Agent': 'quickback-cli',
161
+ },
162
+ body: JSON.stringify({
163
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
164
+ device_code: deviceCode,
165
+ client_id: CLIENT_ID,
166
+ }),
167
+ });
168
+ if (response.ok) {
169
+ const token = await response.json();
170
+ resolve(token);
171
+ return;
172
+ }
173
+ const error = await response.json();
174
+ switch (error.error) {
175
+ case 'authorization_pending':
176
+ // Continue polling
177
+ break;
178
+ case 'slow_down':
179
+ // Increase polling interval
180
+ pollingInterval += 5;
181
+ break;
182
+ case 'access_denied':
183
+ reject(new Error('Authorization was denied'));
184
+ return;
185
+ case 'expired_token':
186
+ reject(new Error('Device code expired. Please try again.'));
187
+ return;
188
+ default:
189
+ reject(new Error(error.error_description || error.error || 'Unknown error'));
190
+ return;
191
+ }
192
+ // Schedule next poll
193
+ setTimeout(poll, pollingInterval * 1000);
194
+ }
195
+ catch (err) {
196
+ // Network error - retry
197
+ setTimeout(poll, pollingInterval * 1000);
198
+ }
199
+ };
200
+ // Start polling after initial interval
201
+ setTimeout(poll, pollingInterval * 1000);
202
+ });
203
+ }
204
+ /**
205
+ * Exchange Better Auth access token for session info
206
+ *
207
+ * The device authorization flow creates a session in the database.
208
+ * This endpoint returns that session token so it appears in Manage Devices.
209
+ */
210
+ async function exchangeToken(accessToken) {
211
+ const response = await fetch(`${AUTH_URL}/cli/exchange`, {
212
+ method: 'POST',
213
+ headers: {
214
+ 'Authorization': `Bearer ${accessToken}`,
215
+ 'Content-Type': 'application/json',
216
+ 'User-Agent': 'quickback-cli',
217
+ },
218
+ });
219
+ if (!response.ok) {
220
+ const error = await response.json().catch(() => ({}));
221
+ throw new Error(error.error_description || 'Failed to exchange token');
222
+ }
223
+ return response.json();
224
+ }
225
+ /**
226
+ * List user's organizations
227
+ */
228
+ async function listOrganizations(sessionToken) {
229
+ const response = await fetch(`${AUTH_URL}/auth/v1/organization/list`, {
230
+ method: 'GET',
231
+ headers: {
232
+ 'Authorization': `Bearer ${sessionToken}`,
233
+ 'Content-Type': 'application/json',
234
+ 'User-Agent': 'quickback-cli',
235
+ },
236
+ });
237
+ if (!response.ok) {
238
+ throw new Error('Failed to list organizations');
239
+ }
240
+ const data = await response.json();
241
+ // Better Auth returns a plain array; handle both formats
242
+ return Array.isArray(data) ? data : (data.organizations || []);
243
+ }
244
+ /**
245
+ * Set the active organization for the session
246
+ */
247
+ async function setActiveOrganization(sessionToken, organizationId) {
248
+ const response = await fetch(`${AUTH_URL}/auth/v1/organization/set-active`, {
249
+ method: 'POST',
250
+ headers: {
251
+ 'Authorization': `Bearer ${sessionToken}`,
252
+ 'Content-Type': 'application/json',
253
+ 'User-Agent': 'quickback-cli',
254
+ },
255
+ body: JSON.stringify({ organizationId }),
256
+ });
257
+ if (!response.ok) {
258
+ const error = await response.json().catch(() => ({}));
259
+ throw new Error(error.message || 'Failed to set active organization');
260
+ }
261
+ }
262
+ /**
263
+ * Format user code with dash for readability (e.g., ABCD-1234)
264
+ */
265
+ function formatUserCode(code) {
266
+ if (code.length === 8) {
267
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
268
+ }
269
+ return code;
270
+ }
271
+ /**
272
+ * Try to open browser to verification URL
273
+ */
274
+ function openBrowser(url) {
275
+ const platform = process.platform;
276
+ const openCmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'start' : 'xdg-open';
277
+ exec(`${openCmd} "${url}"`, (error) => {
278
+ if (error) {
279
+ console.log(pc.yellow('Could not open browser automatically.'));
280
+ console.log(`Open this URL in your browser: ${pc.cyan(url)}\n`);
281
+ }
282
+ else {
283
+ console.log(pc.gray('Opening browser...\n'));
284
+ }
285
+ });
286
+ }
287
+ //# sourceMappingURL=login.js.map