create-usebecky 0.0.0-stage → 0.2.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.
Files changed (157) hide show
  1. package/README.md +80 -2
  2. package/dist/create.js +842 -0
  3. package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
  4. package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
  5. package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
  6. package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
  7. package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  8. package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
  9. package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  10. package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
  11. package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
  12. package/dist/index.js +10 -0
  13. package/dist/keys.js +72 -0
  14. package/dist/platform.js +104 -0
  15. package/dist/pm.js +69 -0
  16. package/dist/prompts.js +242 -0
  17. package/dist/scaffold.js +108 -0
  18. package/dist/setup.js +130 -0
  19. package/dist/shared/ai.js +203 -0
  20. package/dist/shared/extension-skill.js +107 -0
  21. package/dist/shared/framework.js +460 -0
  22. package/dist/shared/hosted.js +8 -0
  23. package/dist/shared/ui.js +141 -0
  24. package/dist/skill/usebecky/SKILL.md +339 -0
  25. package/dist/skill/usebecky/references/access-rules.md +307 -0
  26. package/dist/skill/usebecky/references/addons.md +68 -0
  27. package/dist/skill/usebecky/references/analytics.md +166 -0
  28. package/dist/skill/usebecky/references/android.md +434 -0
  29. package/dist/skill/usebecky/references/auth.md +379 -0
  30. package/dist/skill/usebecky/references/cache.md +51 -0
  31. package/dist/skill/usebecky/references/components.md +127 -0
  32. package/dist/skill/usebecky/references/emails.md +105 -0
  33. package/dist/skill/usebecky/references/expo.md +147 -0
  34. package/dist/skill/usebecky/references/functions.md +99 -0
  35. package/dist/skill/usebecky/references/hosting.md +119 -0
  36. package/dist/skill/usebecky/references/http-api.md +233 -0
  37. package/dist/skill/usebecky/references/ios.md +355 -0
  38. package/dist/skill/usebecky/references/payments.md +493 -0
  39. package/dist/skill/usebecky/references/realtime.md +143 -0
  40. package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
  41. package/dist/skill/usebecky/references/sdk.md +838 -0
  42. package/dist/skill/usebecky/references/storage.md +210 -0
  43. package/dist/skill/usebecky/references/templates.md +191 -0
  44. package/dist/skill/usebecky/references/wordpress.md +87 -0
  45. package/dist/templates.js +74 -0
  46. package/package.json +37 -4
  47. package/templates/expo/App.tsx +48 -0
  48. package/templates/expo/README.md +59 -0
  49. package/templates/expo/_env.example +4 -0
  50. package/templates/expo/_gitignore +12 -0
  51. package/templates/expo/app.json +25 -0
  52. package/templates/expo/assets/icon.png +0 -0
  53. package/templates/expo/brand.ts +7 -0
  54. package/templates/expo/components/Avatar.tsx +75 -0
  55. package/templates/expo/components/ui.tsx +57 -0
  56. package/templates/expo/index.ts +4 -0
  57. package/templates/expo/lib/theme.ts +43 -0
  58. package/templates/expo/lib/usebecky.ts +15 -0
  59. package/templates/expo/package.json +29 -0
  60. package/templates/expo/screens/Home.tsx +187 -0
  61. package/templates/expo/screens/SignIn.tsx +112 -0
  62. package/templates/expo/tsconfig.json +6 -0
  63. package/templates/expo/usebecky.template.json +36 -0
  64. package/templates/extension/README.md +128 -0
  65. package/templates/extension/_env.example +21 -0
  66. package/templates/extension/_gitignore +11 -0
  67. package/templates/extension/logo.svg +1 -0
  68. package/templates/extension/package.json +25 -0
  69. package/templates/extension/src/accounts.ts +90 -0
  70. package/templates/extension/src/app.ts +178 -0
  71. package/templates/extension/src/pages.ts +108 -0
  72. package/templates/extension/src/replay-guard.ts +17 -0
  73. package/templates/extension/src/server.ts +57 -0
  74. package/templates/extension/src/settings.ts +69 -0
  75. package/templates/extension/src/ui.ts +70 -0
  76. package/templates/extension/test/app.test.ts +222 -0
  77. package/templates/extension/tsconfig.json +16 -0
  78. package/templates/extension/usebecky-extension.json +36 -0
  79. package/templates/extension/usebecky.template.json +22 -0
  80. package/templates/landing/README.md +43 -0
  81. package/templates/landing/_env.example +4 -0
  82. package/templates/landing/_gitignore +9 -0
  83. package/templates/landing/index.html +16 -0
  84. package/templates/landing/package.json +28 -0
  85. package/templates/landing/public/icon.svg +1 -0
  86. package/templates/landing/src/App.tsx +97 -0
  87. package/templates/landing/src/components/Contact.tsx +43 -0
  88. package/templates/landing/src/components/Counter.tsx +34 -0
  89. package/templates/landing/src/components/Feedback.tsx +36 -0
  90. package/templates/landing/src/components/Logo.tsx +11 -0
  91. package/templates/landing/src/components/Receipt.tsx +128 -0
  92. package/templates/landing/src/components/Setup.tsx +20 -0
  93. package/templates/landing/src/components/fields.tsx +63 -0
  94. package/templates/landing/src/content.ts +22 -0
  95. package/templates/landing/src/index.css +119 -0
  96. package/templates/landing/src/lib/usebecky.ts +11 -0
  97. package/templates/landing/src/lib/waitlist.ts +46 -0
  98. package/templates/landing/src/main.tsx +12 -0
  99. package/templates/landing/src/vite-env.d.ts +6 -0
  100. package/templates/landing/tsconfig.json +19 -0
  101. package/templates/landing/usebecky.template.json +20 -0
  102. package/templates/landing/vite.config.ts +10 -0
  103. package/templates/notes/README.md +68 -0
  104. package/templates/notes/_env.example +4 -0
  105. package/templates/notes/_gitignore +9 -0
  106. package/templates/notes/index.html +15 -0
  107. package/templates/notes/package.json +28 -0
  108. package/templates/notes/public/icon.svg +1 -0
  109. package/templates/notes/src/App.tsx +35 -0
  110. package/templates/notes/src/brand.ts +7 -0
  111. package/templates/notes/src/components/Composer.tsx +113 -0
  112. package/templates/notes/src/components/NoteEntry.tsx +151 -0
  113. package/templates/notes/src/components/Notes.tsx +163 -0
  114. package/templates/notes/src/components/Setup.tsx +44 -0
  115. package/templates/notes/src/components/SignIn.tsx +112 -0
  116. package/templates/notes/src/components/icons.tsx +54 -0
  117. package/templates/notes/src/index.css +105 -0
  118. package/templates/notes/src/lib/notes.ts +68 -0
  119. package/templates/notes/src/lib/usebecky.ts +9 -0
  120. package/templates/notes/src/main.tsx +22 -0
  121. package/templates/notes/src/vite-env.d.ts +6 -0
  122. package/templates/notes/tsconfig.json +19 -0
  123. package/templates/notes/usebecky.template.json +34 -0
  124. package/templates/notes/vite.config.ts +10 -0
  125. package/templates/saas/README.md +69 -0
  126. package/templates/saas/_env.example +10 -0
  127. package/templates/saas/_gitignore +11 -0
  128. package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
  129. package/templates/saas/app/(app)/account/page.tsx +71 -0
  130. package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
  131. package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
  132. package/templates/saas/app/(app)/layout.tsx +29 -0
  133. package/templates/saas/app/(app)/premium/page.tsx +62 -0
  134. package/templates/saas/app/auth/callback/page.tsx +33 -0
  135. package/templates/saas/app/globals.css +143 -0
  136. package/templates/saas/app/icon.svg +1 -0
  137. package/templates/saas/app/layout.tsx +20 -0
  138. package/templates/saas/app/page.tsx +87 -0
  139. package/templates/saas/app/pricing/Plans.tsx +133 -0
  140. package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
  141. package/templates/saas/app/pricing/page.tsx +21 -0
  142. package/templates/saas/app/setup/page.tsx +34 -0
  143. package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
  144. package/templates/saas/app/sign-in/page.tsx +21 -0
  145. package/templates/saas/brand.ts +10 -0
  146. package/templates/saas/components/AppNav.tsx +45 -0
  147. package/templates/saas/components/Logo.tsx +22 -0
  148. package/templates/saas/components/SiteHeader.tsx +50 -0
  149. package/templates/saas/components/Status.tsx +15 -0
  150. package/templates/saas/lib/session.ts +26 -0
  151. package/templates/saas/lib/usebecky.ts +11 -0
  152. package/templates/saas/next-env.d.ts +5 -0
  153. package/templates/saas/next.config.ts +5 -0
  154. package/templates/saas/package.json +26 -0
  155. package/templates/saas/postcss.config.mjs +3 -0
  156. package/templates/saas/tsconfig.json +21 -0
  157. package/templates/saas/usebecky.template.json +31 -0
@@ -0,0 +1,112 @@
1
+ // Sign in with a 6-digit code sent by email. No password, and it works for new and returning people.
2
+ // (Links in emails open the phone's browser, not your app, so the code is the simplest way in.)
3
+ import { useRef, useState } from 'react'
4
+ import { KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputInstance } from 'react-native'
5
+ import { SafeAreaView } from 'react-native-safe-area-context'
6
+ import { brand } from '../brand'
7
+ import { Button, Field, Message } from '../components/ui'
8
+ import { baas } from '../lib/usebecky'
9
+ import { useTheme } from '../lib/theme'
10
+
11
+ export function SignInScreen() {
12
+ const t = useTheme()
13
+ const [email, setEmail] = useState('')
14
+ const [code, setCode] = useState('')
15
+ const [step, setStep] = useState<'email' | 'code'>('email')
16
+ const [busy, setBusy] = useState(false)
17
+ const [message, setMessage] = useState<{ tone: 'error' | 'info'; text: string } | null>(null)
18
+ const codeInput = useRef<TextInputInstance>(null)
19
+
20
+ async function sendCode() {
21
+ setBusy(true)
22
+ setMessage(null)
23
+ const { error } = await baas.auth.sendMagicLink(email.trim(), { createUser: true })
24
+ setBusy(false)
25
+ if (error) return setMessage({ tone: 'error', text: error.message })
26
+ setStep('code')
27
+ setMessage({ tone: 'info', text: `We sent a 6-digit code to ${email.trim()}.` })
28
+ setTimeout(() => codeInput.current?.focus(), 300)
29
+ }
30
+
31
+ async function verify(value = code) {
32
+ setBusy(true)
33
+ setMessage(null)
34
+ const { error } = await baas.auth.verifyCode(email.trim(), value)
35
+ setBusy(false)
36
+ // On success, App.tsx sees the new session and shows the home screen.
37
+ if (error) setMessage({ tone: 'error', text: error.code === 'otp_expired' ? 'That code is wrong or has expired. Use the newest email, or send a new code.' : error.message })
38
+ }
39
+
40
+ return (
41
+ <SafeAreaView style={[styles.screen, { backgroundColor: t.page }]}>
42
+ <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.fill}>
43
+ <View style={styles.top}>
44
+ <View style={[styles.mark, { backgroundColor: t.accent }]}>
45
+ <Text style={[styles.markText, { color: t.onAccent }]}>✓</Text>
46
+ </View>
47
+ <Text style={[styles.title, { color: t.ink }]} accessibilityRole="header">
48
+ {brand.name}
49
+ </Text>
50
+ <Text style={[styles.tagline, { color: t.muted }]}>{brand.tagline}</Text>
51
+ </View>
52
+
53
+ <View style={styles.form}>
54
+ {step === 'email' ? (
55
+ <>
56
+ <Field label="Your email" value={email} onChangeText={setEmail} placeholder="you@example.com" autoCapitalize="none" autoComplete="email" keyboardType="email-address" textContentType="emailAddress" returnKeyType="send" onSubmitEditing={sendCode} />
57
+ <View style={styles.gap} />
58
+ <Button title="Email me a code" onPress={sendCode} busy={busy} disabled={!/\S+@\S+\.\S+/.test(email)} />
59
+ </>
60
+ ) : (
61
+ <>
62
+ <Text style={[styles.label, { color: t.ink }]}>6-digit code</Text>
63
+ {/* One hidden input, drawn as six boxes. */}
64
+ <Pressable onPress={() => codeInput.current?.focus()} accessibilityLabel="6-digit code" style={styles.boxes}>
65
+ {Array.from({ length: 6 }, (_, i) => (
66
+ <View key={i} style={[styles.box, { backgroundColor: t.surface, borderColor: i === code.length ? t.accent : t.line }]}>
67
+ <Text style={[styles.boxText, { color: t.ink }]}>{code[i] ?? ''}</Text>
68
+ </View>
69
+ ))}
70
+ </Pressable>
71
+ <TextInput
72
+ ref={codeInput}
73
+ value={code}
74
+ onChangeText={(v) => {
75
+ const digits = v.replace(/\D/g, '').slice(0, 6)
76
+ setCode(digits)
77
+ if (digits.length === 6) verify(digits)
78
+ }}
79
+ keyboardType="number-pad"
80
+ textContentType="oneTimeCode"
81
+ autoComplete="one-time-code"
82
+ maxLength={6}
83
+ style={styles.hidden}
84
+ />
85
+ <View style={styles.gap} />
86
+ <Button title="Sign in" onPress={() => verify()} busy={busy} disabled={code.length !== 6} />
87
+ <Button title="Use a different email" variant="plain" onPress={() => (setStep('email'), setCode(''), setMessage(null))} />
88
+ </>
89
+ )}
90
+ {message && <Message tone={message.tone}>{message.text}</Message>}
91
+ </View>
92
+ </KeyboardAvoidingView>
93
+ </SafeAreaView>
94
+ )
95
+ }
96
+
97
+ const styles = StyleSheet.create({
98
+ screen: { flex: 1 },
99
+ fill: { flex: 1, paddingHorizontal: 24, justifyContent: 'space-between' },
100
+ top: { paddingTop: 56 },
101
+ mark: { width: 56, height: 56, borderRadius: 18, alignItems: 'center', justifyContent: 'center', marginBottom: 28 },
102
+ markText: { fontSize: 28, fontWeight: '800' },
103
+ title: { fontSize: 44, fontWeight: '800', letterSpacing: -1.2 },
104
+ tagline: { fontSize: 19, lineHeight: 26, marginTop: 8, maxWidth: 320 },
105
+ form: { paddingBottom: 28 },
106
+ label: { fontSize: 15, fontWeight: '600', marginBottom: 8 },
107
+ gap: { height: 14 },
108
+ boxes: { flexDirection: 'row', gap: 8 },
109
+ box: { flex: 1, height: 58, borderRadius: 14, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
110
+ boxText: { fontSize: 26, fontWeight: '700', fontVariant: ['tabular-nums'] },
111
+ hidden: { position: 'absolute', opacity: 0, width: 1, height: 1 },
112
+ })
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "expo/tsconfig.base",
3
+ "compilerOptions": {
4
+ "strict": true
5
+ }
6
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "id": "expo",
3
+ "name": "Mobile app",
4
+ "description": "iPhone and Android app in JavaScript: code sign-in, live to-dos, profile photo",
5
+ "stack": "Expo",
6
+ "kind": "node",
7
+ "framework": "expo",
8
+ "serverTemplate": "mobile",
9
+ "order": 4,
10
+ "brandName": "Daylist",
11
+ "brandSlug": "daylist",
12
+ "brandFiles": ["brand.ts", "app.json"],
13
+ "customize": { "name": "brand.ts and app.json", "colour": "brand.ts (accent)" },
14
+ "requires": { "tables": ["todos", "profiles"] },
15
+ "setup": {
16
+ "tables": [
17
+ {
18
+ "name": "todos",
19
+ "preset": "owner",
20
+ "comment": "Each user sees only their own todos. Realtime is on.",
21
+ "columns": [
22
+ { "name": "title", "type": "text", "nullable": false },
23
+ { "name": "done", "type": "bool", "nullable": false, "default": "false" }
24
+ ],
25
+ "realtime": true
26
+ }
27
+ ],
28
+ "buckets": [{ "id": "avatars", "public": true, "policies": ["user_folder"] }]
29
+ },
30
+ "run": {
31
+ "script": "dev",
32
+ "first": "Install Expo Go from the App Store / Google Play on your phone",
33
+ "note": "then scan the QR code with Expo Go (same Wi-Fi)"
34
+ },
35
+ "docs": [{ "title": "Expo guide", "path": "frameworks/expo" }]
36
+ }
@@ -0,0 +1,128 @@
1
+ # My Extension
2
+
3
+ An extension for the usebecky store, built with [`@usebecky/extension`](https://www.npmjs.com/package/@usebecky/extension). Customers install it on one of their usebecky projects; it creates their account automatically (no sign-up form), lets them open it from usebecky without a password ("Open in My Extension"), shows the project's name on its settings page, saves a greeting, and cleans up after itself when it is disconnected. Replace that with what your extension does.
4
+
5
+ ## 1. Try it on your computer (2 minutes)
6
+
7
+ ```bash
8
+ npm run dev
9
+ ```
10
+
11
+ This starts two things: **your extension** on http://localhost:3000 and a **pretend usebecky** on http://localhost:4400, with two fake projects and test credentials. No account needed.
12
+
13
+ 1. Open http://localhost:4400 and click **Install** next to Acme Shop. That is what a customer does in the store: usebecky opens your `/install` route.
14
+ 2. You see usebecky's consent screen. Keep **Acme Shop** and click **Allow**.
15
+ 3. You land on your extension's settings page, connected to "Acme Shop" and signed in: your account was created from the sign-in's id_token. Save a greeting. **Back to usebecky** returns to the extension's page in the project.
16
+ 4. Back on http://localhost:4400, click **Open in My Extension**: the settings page opens again, signed in by a launch token, without a password.
17
+ 5. Click **Greeting** next to Acme Shop: your page inside usebecky, with the project's websites. Its settings view (the greeting) is on the extension's page. usebecky draws both from the blocks `src/ui.ts` answers.
18
+ 6. Send an event (it arrives at `/webhooks/usebecky`, verified) or click **Disconnect** (the extension deletes what it stored).
19
+
20
+ Change any file in `src/` and the extension restarts by itself. Run the tests with `npm test`.
21
+
22
+ ## What's inside
23
+
24
+ | File | What it does |
25
+ |---|---|
26
+ | `usebecky-extension.json` | The store listing: name, summary, scopes, the data customers see on the consent screen, your addresses |
27
+ | `src/app.ts` | The routes: `/install`, `/oauth/callback` (creates the account), `/sso` ("Open in"), `/settings`, `/webhooks/usebecky`, `/privacy`, `/support` |
28
+ | `src/server.ts` | Starts the server; reads the environment variables |
29
+ | `src/settings.ts` | Stores each project's settings (a JSON file in `.data/`) |
30
+ | `src/replay-guard.ts` | Remembers the "Open in" links already used, so each works once (a SQLite file in `.data/`) |
31
+ | `src/pages.ts` | Your own web pages (install, settings, "Open in"), in usebecky's look with your name and logo |
32
+ | `src/ui.ts` | Your pages inside usebecky: a sidebar row and a settings view, as blocks usebecky draws |
33
+ | `test/app.test.ts` | Installs, saves, receives webhooks and disconnects against the pretend usebecky |
34
+ | `.claude/skills/usebecky-extension/` | Teaches Claude Code how to build on this (see "Build it with AI") |
35
+
36
+ Everything that talks to usebecky (OAuth with PKCE, the id_token and launch tokens, storing and refreshing tokens, verifying webhooks) is done by `@usebecky/extension`. Don't write it yourself.
37
+
38
+ ## Accounts: no sign-up form, ever
39
+
40
+ usebecky customers never sign up at your service by hand. `usebecky-extension.json` says so with `"account": { "required": true, "provision": "oauth", "sso_url": "…/sso" }`:
41
+
42
+ - **On install**, the consent screen tells the customer your extension creates their account with their name and email. `/oauth/callback` gets the verified id_token (`identity`) and creates the account, keyed by `identity.sub` (stable for this person and your extension).
43
+ - **"Open in My Extension"** in usebecky sends them to `/sso?launch=<token>`; `ext.ssoHandler()` checks it (signed by usebecky, 60 seconds, once) and the app signs them in with the same session cookie.
44
+
45
+ Your service needs no accounts? Remove `account` from the listing and the account code from `src/app.ts`. Using setup fields instead of OAuth? Use `"provision": "url"` and `ext.provisionHandler()`. Guide: https://usebecky.com/docs/extensions/accounts
46
+
47
+ ## Pages inside usebecky: blocks, never HTML
48
+
49
+ Like a WordPress plugin's menu page, My Extension adds a row to the customer's sidebar (`"ui"` in `usebecky-extension.json`). usebecky asks `POST /usebecky/ui` for the page and draws the blocks `src/ui.ts` answers with (stat tiles, charts, tables with paging, forms…) in its own design, light and dark, on phones too. Never write HTML, CSS or an iframe for usebecky. Your own web pages (`src/pages.ts`) use usebecky's look with your own name and logo. Guide: https://usebecky.com/docs/extensions/ui
50
+
51
+ ## 2. Make it yours (5 minutes)
52
+
53
+ 1. In `usebecky-extension.json`, change `name`, `summary`, `description`, `publisher` and `category`. Replace `logo.svg`.
54
+ 2. Ask only for the data you need in `scopes` (`project:read`, `analytics:read`, `events:read`), and say in `data_shared`, in plain words, what each one shows you.
55
+ 3. Check it (the same checks usebecky makes):
56
+
57
+ ```bash
58
+ npm run validate
59
+ ```
60
+
61
+ Errors must be fixed; warnings about `example.com` go away once you put in your real addresses.
62
+
63
+ ## 3. Run it on the real usebecky
64
+
65
+ 1. In usebecky, click **Build an extension** at the bottom of a project's Extensions page (or **New extension** under **Developer**, or open https://app.usebecky.com/developer/extensions/new). Give it the same id (slug) as in `usebecky-extension.json` (`my-extension`) and click **Create extension**.
66
+ 2. In the editor, click **Import usebecky-extension.json**, then upload the logo under **Store listing** and click **Save draft**.
67
+ 3. Under **Credentials and testing**, click **Create credentials**: the client id, client secret and webhook signing secret. The secrets are shown once.
68
+ 4. Put the extension on a server with an https address, and set these environment variables there (or in `.env` for `npm start`; `.env.example` lists them):
69
+
70
+ | Variable | Value |
71
+ |---|---|
72
+ | `USEBECKY_CLIENT_ID`, `USEBECKY_CLIENT_SECRET`, `USEBECKY_WEBHOOK_SECRET` | from **Create credentials** (`ub_ci_…`, `ub_cs_…`, `whsec_…`) |
73
+ | `PUBLIC_URL` | your https address; `PUBLIC_URL/oauth/callback` must be in `connect.redirect_uris` |
74
+ | `SESSION_SECRET` | a long random string: `openssl rand -hex 32` |
75
+ | `USEBECKY_API_URL`, `USEBECKY_DASHBOARD_URL` | leave unset: usebecky's API and dashboard (the consent screen) |
76
+
77
+ 5. Click **Open test project** (the Developer overview says **Create test project** the first time): a free usebecky project only you can see, where your own extension installs before review. Install it there, open the settings page, click **Open in My Extension** in Developer tools, simulate sign-ups and purchases, disconnect it. **Open demo site** opens the test project's demo shop, and **Send test event** (under Credentials and testing) sends a signed sample event to your webhook at any time.
78
+
79
+ ## 4. Submit it for review
80
+
81
+ When it works on the test project and `npm run validate` shows no warnings, click **Submit for review** in the editor. usebecky's team approves it or tells you what to change; once approved it is listed in the store.
82
+
83
+ Free, or a monthly price per project: usebecky bills customers, keeps 20% and pays the rest out to you through Stripe. Set up payouts in the Developer area before you submit a paid extension.
84
+
85
+ ## Use a real database
86
+
87
+ Everything lives in `.data/` on one server's disk: the tokens (`tokens.json`), the settings (`settings.json`), the accounts (`accounts.json`) and the "Open in" links already used (`replay.sqlite`, the **replay guard**: each link works once). The replay guard uses the kit's `sqlReplayGuard()` on Node's built-in SQLite (`src/replay-guard.ts`), so no extra package is needed. On Node 22, Node may print a one-time "SQLite is an experimental feature" warning at start; it is harmless.
88
+
89
+ With more than one server, or on serverless hosting, every server must see the same data: point the tokens and the replay guard at one shared Postgres database (`npm install pg`). The shared replay guard is required there: on its own disk, each server only knows the links it has seen, so a stolen link would work once on each.
90
+
91
+ ```ts
92
+ // src/database.ts
93
+ import { replayTableSql, sqlReplayGuard, sqlTokenStore, tokenTableSql } from '@usebecky/extension'
94
+ import pg from 'pg'
95
+
96
+ const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
97
+ const query = async (sql: string, params: unknown[]) => (await pool.query(sql, params)).rows
98
+
99
+ export const tokenStore = sqlTokenStore({ query })
100
+ export const replayGuard = sqlReplayGuard({ query })
101
+
102
+ /** Run once at start-up (or put the statements in a migration). */
103
+ export async function createTables() {
104
+ await pool.query(tokenTableSql())
105
+ await pool.query(replayTableSql())
106
+ }
107
+ ```
108
+
109
+ Then pass both to `createExtension` in `src/server.ts` instead of `fileTokenStore(...)` and `sqliteReplayGuard(...)`, and store settings and accounts in the same database.
110
+
111
+ ## Build it with AI
112
+
113
+ This folder includes the **usebecky-extension skill** in `.claude/skills/usebecky-extension/`. Claude Code reads it by itself; other assistants find it through `AGENTS.md`. Ask for what you want, for example:
114
+
115
+ - "Show the visitor numbers of the connected project on the settings page" (it will add the `analytics:read` scope and explain why)
116
+ - "Send me an email when someone installs the extension"
117
+ - "Store the settings in Postgres instead of a JSON file"
118
+
119
+ ## Security checklist
120
+
121
+ - Secrets only in environment variables; `.env` and `.data/` stay out of git (`.gitignore` already says so).
122
+ - Every webhook is verified by the kit before anything happens; never parse the body yourself first.
123
+ - Disconnecting deletes everything stored for the project (`src/app.ts`, `extension.uninstalled`).
124
+ - The settings page trusts only the signed session cookie set in `/oauth/callback` or `/sso`, never a project in the address.
125
+ - No sign-up or login form for usebecky customers: accounts come from the verified id_token, sign-ins from verified, single-use launch tokens. Each launch link works once (`src/replay-guard.ts`); with more than one server, the replay guard must be shared: `sqlReplayGuard()` on the same Postgres database as the tokens (see "Use a real database").
126
+ - Never log tokens or webhook bodies with personal data.
127
+
128
+ More: the "Build an extension" guide at https://usebecky.com/docs/guides/build-an-extension.
@@ -0,0 +1,21 @@
1
+ # Only for `npm start` (your extension against the real usebecky). Copy this file to .env and fill it in.
2
+ # `npm run dev` uses a pretend usebecky on your computer and needs none of this.
3
+
4
+ # usebecky: Developer → your extension → Credentials and testing → Create credentials. The secrets are shown once.
5
+ USEBECKY_CLIENT_ID=
6
+ USEBECKY_CLIENT_SECRET=
7
+ USEBECKY_WEBHOOK_SECRET=
8
+
9
+ # Your server's public https address. usebecky sends customers back to PUBLIC_URL/oauth/callback,
10
+ # which must be listed in usebecky-extension.json (connect.redirect_uris).
11
+ PUBLIC_URL=https://my-extension.example.com
12
+
13
+ # Signs the settings page cookie. Make one with: openssl rand -hex 32
14
+ SESSION_SECRET=
15
+
16
+ PORT=3000
17
+
18
+ # usebecky's addresses. Leave both unset for usebecky (https://api.usebecky.com, consent screen on
19
+ # https://app.usebecky.com). Only to test against another usebecky, for example usebecky's own local one:
20
+ # USEBECKY_API_URL=http://localhost:4300
21
+ # USEBECKY_DASHBOARD_URL=http://localhost:5300
@@ -0,0 +1,11 @@
1
+ node_modules
2
+ *.log
3
+ .DS_Store
4
+
5
+ # Tokens and settings of your customers' installs (src/server.ts). Never commit these.
6
+ .data/
7
+
8
+ # Your credentials. Never commit these.
9
+ .env
10
+ .env.local
11
+ .env.*.local
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><rect width="64" height="64" rx="8" fill="#3352f5"/><path d="M20 22h24v6H28v4h12v6H28v4h16v6H20z" fill="#fff"/></svg>
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "my-extension",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "usebecky-extension dev -- node --watch --env-file-if-exists=.env src/server.ts",
8
+ "start": "node --env-file-if-exists=.env src/server.ts",
9
+ "test": "node --test test/app.test.ts",
10
+ "typecheck": "tsc --noEmit",
11
+ "validate": "usebecky-extension validate"
12
+ },
13
+ "dependencies": {
14
+ "@hono/node-server": "2.1.8",
15
+ "@usebecky/extension": "^0.2.0",
16
+ "hono": "4.13.18"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "26.6.6",
20
+ "typescript": "5.9.3"
21
+ },
22
+ "engines": {
23
+ "node": ">=22.18"
24
+ }
25
+ }
@@ -0,0 +1,90 @@
1
+ // The customers' accounts at this extension. Nobody signs up here by hand: usebecky tells us who the customer is
2
+ // (the OpenID id_token when they install, a launch token when they click "Open in My Extension"), and the account is
3
+ // created or found by `sub`: usebecky's id for this person, stable for this extension only (never their usebecky id).
4
+ //
5
+ // Link accounts by `sub`, not by email: two extensions never get the same `sub` for the same person, and an email
6
+ // address is only proven when `email_verified` is true.
7
+ import fs from 'node:fs/promises'
8
+ import path from 'node:path'
9
+
10
+ export interface Account {
11
+ /** usebecky's pairwise subject: the key. */
12
+ sub: string
13
+ email: string
14
+ name: string | null
15
+ /** The usebecky projects this person installed us on (one install per project). */
16
+ projects: string[]
17
+ createdAt: string
18
+ }
19
+
20
+ export interface AccountStore {
21
+ get(sub: string): Promise<Account | null>
22
+ /** Create the account, or update its email and name and add the project. */
23
+ upsert(input: { sub: string; email: string; name?: string | null; project: string }): Promise<Account>
24
+ /** Forget a project (on uninstall); an account left with no project is deleted. */
25
+ removeProject(project: string): Promise<void>
26
+ }
27
+
28
+ function merge(existing: Account | undefined, input: { sub: string; email: string; name?: string | null; project: string }): Account {
29
+ return {
30
+ sub: input.sub,
31
+ email: input.email,
32
+ name: input.name ?? existing?.name ?? null,
33
+ projects: [...new Set([...(existing?.projects ?? []), input.project])],
34
+ createdAt: existing?.createdAt ?? new Date().toISOString(),
35
+ }
36
+ }
37
+
38
+ function withoutProject(all: Record<string, Account>, project: string) {
39
+ for (const [sub, a] of Object.entries(all)) {
40
+ a.projects = a.projects.filter((p) => p !== project)
41
+ if (!a.projects.length) delete all[sub]
42
+ }
43
+ }
44
+
45
+ export function memoryAccountStore(): AccountStore {
46
+ const all: Record<string, Account> = {}
47
+ return {
48
+ get: async (sub) => (all[sub] ? structuredClone(all[sub]) : null),
49
+ upsert: async (input) => structuredClone((all[input.sub] = merge(all[input.sub], input))),
50
+ removeProject: async (project) => withoutProject(all, project),
51
+ }
52
+ }
53
+
54
+ /** Accounts in a JSON file: fine on one small server. Use your database everywhere else (keyed by sub). */
55
+ export function fileAccountStore(file: string): AccountStore {
56
+ const target = path.resolve(file)
57
+ let queue: Promise<unknown> = Promise.resolve()
58
+
59
+ async function read(): Promise<Record<string, Account>> {
60
+ try {
61
+ return JSON.parse(await fs.readFile(target, 'utf8'))
62
+ } catch (err) {
63
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {}
64
+ throw err
65
+ }
66
+ }
67
+
68
+ function change<T>(fn: (all: Record<string, Account>) => T): Promise<T> {
69
+ const next = queue.then(async () => {
70
+ const all = await read()
71
+ const out = fn(all)
72
+ await fs.mkdir(path.dirname(target), { recursive: true })
73
+ const tmp = `${target}.tmp`
74
+ await fs.writeFile(tmp, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 })
75
+ await fs.rename(tmp, target)
76
+ return out
77
+ })
78
+ queue = next.catch(() => {})
79
+ return next
80
+ }
81
+
82
+ return {
83
+ async get(sub) {
84
+ await queue
85
+ return (await read())[sub] ?? null
86
+ },
87
+ upsert: (input) => change((all) => (all[input.sub] = merge(all[input.sub], input))),
88
+ removeProject: (project) => change((all) => withoutProject(all, project)),
89
+ }
90
+ }
@@ -0,0 +1,178 @@
1
+ // The extension's routes. usebecky's side of every flow is handled by @usebecky/extension:
2
+ //
3
+ // GET /install usebecky's Install opens this (install_url, with ?project and ?return_url) → the consent screen
4
+ // GET /oauth/callback back from the consent screen: tokens stored, the account created, settings cookie set
5
+ // GET /sso "Open in <your extension>" from usebecky (sso_url): signed in without a password
6
+ // GET /settings the customer's settings (needs the cookie)
7
+ // POST /webhooks/usebecky extension.installed / extension.uninstalled (+ the events you list)
8
+ // POST /usebecky/ui its pages inside usebecky (ui in the listing): the sidebar row and the settings view (src/ui.ts)
9
+ //
10
+ // Customers never sign up here by hand. The account is created from what usebecky says about them (the id_token in
11
+ // the callback, the launch token on /sso), keyed by `sub`. Don't add a sign-up or password form: usebecky's review
12
+ // rejects extensions that ask customers to create an account themselves.
13
+ import fs from 'node:fs'
14
+ import { ExtensionError, InstallationRevokedError, STATE_COOKIE, type Extension } from '@usebecky/extension'
15
+ import { Hono, type Context } from 'hono'
16
+ import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie'
17
+ import { errorPage, homePage, NAME, privacyPage, settingsPage, signInPage, supportPage } from './pages.ts'
18
+ import { uiHandler } from './ui.ts'
19
+ import type { AccountStore } from './accounts.ts'
20
+ import type { SettingsStore } from './settings.ts'
21
+
22
+ export interface AppOptions {
23
+ ext: Extension
24
+ settings: SettingsStore
25
+ /** The customers' accounts, created automatically (never a sign-up form). */
26
+ accounts: AccountStore
27
+ /** Signs the session cookie (SESSION_SECRET). */
28
+ sessionSecret: string
29
+ /** Mark cookies Secure (true whenever the site runs on https). */
30
+ secureCookies?: boolean
31
+ }
32
+
33
+ /** The cookie holds the project ref, its install id and the person's sub, signed so nobody can change them. */
34
+ const SESSION = 'session'
35
+ /** The extension's page in the customer's project in usebecky (install_url's return_url), for "Back to usebecky". */
36
+ const BACK = 'back_to_usebecky'
37
+ const HOURS_12 = 12 * 60 * 60
38
+
39
+ export function createApp({ ext, settings, accounts, sessionSecret, secureCookies = false }: AppOptions): Hono {
40
+ const app = new Hono()
41
+ const { install } = ext.oauthHandlers()
42
+ const cookie = { httpOnly: true, secure: secureCookies, sameSite: 'Lax' as const, path: '/', maxAge: HOURS_12 }
43
+
44
+ /**
45
+ * The project of the signed-in customer, or null. Only while the install the cookie was made for is still
46
+ * connected: after an uninstall (or a reinstall) an old cookie opens nothing.
47
+ */
48
+ async function session(c: Context): Promise<{ project: string; sub: string | null } | null> {
49
+ const value = await getSignedCookie(c, sessionSecret, SESSION)
50
+ if (typeof value !== 'string') return null
51
+ const [project, installationId, sub] = value.split(':')
52
+ if (!project || !installationId) return null
53
+ const tokens = await ext.tokenStore.get(project)
54
+ return tokens?.installationId === installationId ? { project, sub: sub || null } : null
55
+ }
56
+ const sessionProject = async (c: Context) => (await session(c))?.project ?? null
57
+ const startSession = (c: Context, project: string, installationId: string, sub: string | null) => setSignedCookie(c, SESSION, `${project}:${installationId}:${sub ?? ''}`, sessionSecret, cookie)
58
+
59
+ /** "Back to usebecky": only an address on usebecky's dashboard (the kit checked it in the callback). */
60
+ async function backUrl(c: Context): Promise<string | undefined> {
61
+ const value = await getSignedCookie(c, sessionSecret, BACK)
62
+ return typeof value === 'string' && value.startsWith(`${ext.dashboardUrl}/`) ? value : undefined
63
+ }
64
+
65
+ app.get('/', async (c) => c.html(homePage({ signedIn: !!(await sessionProject(c)), notice: c.req.query('disconnected') ? 'Disconnected. Everything stored for that project was deleted.' : undefined })))
66
+
67
+ // 1. Install: straight to usebecky's consent screen (PKCE, state and return_url are handled by the kit).
68
+ app.get('/install', (c) => install(c.req.raw))
69
+
70
+ // 2. Back from the consent screen.
71
+ app.get('/oauth/callback', async (c) => {
72
+ try {
73
+ const { project, installation, returnUrl, identity } = await ext.handleCallback(c.req.raw)
74
+ deleteCookie(c, STATE_COOKIE, { path: '/' })
75
+ // The account: created (or found) from the verified id_token. No sign-up form, no password.
76
+ if (identity) await accounts.upsert({ sub: identity.sub, email: identity.email ?? '', name: identity.name, project })
77
+ await startSession(c, project, installation.id, identity?.sub ?? null)
78
+ if (returnUrl) await setSignedCookie(c, BACK, returnUrl, sessionSecret, cookie)
79
+ else deleteCookie(c, BACK, { path: '/' })
80
+ return c.redirect('/settings')
81
+ } catch (err) {
82
+ if (!(err instanceof ExtensionError)) throw err
83
+ deleteCookie(c, STATE_COOKIE, { path: '/' })
84
+ const title = err.code === 'access_denied' ? 'Not connected' : 'Could not connect'
85
+ return c.html(errorPage(title, `${err.message}${err.hint ? ` ${err.hint}` : ''}`), 400)
86
+ }
87
+ })
88
+
89
+ // 3. "Open in <your extension>" in usebecky: the kit checks the launch token (signature, audience, 60 seconds, single
90
+ // use); we find the account by sub and start the session. Only for an install that is still connected here.
91
+ app.get('/sso', (c) =>
92
+ ext.ssoHandler({
93
+ serviceName: NAME,
94
+ createSession: async (claims) => {
95
+ const tokens = await ext.tokenStore.get(claims.usebecky_project)
96
+ if (tokens?.installationId !== claims.usebecky_install) return c.html(signInPage(`${NAME} is not connected to that project any more. Install it again from usebecky.`), 401)
97
+ await accounts.upsert({ sub: claims.sub, email: claims.email ?? '', name: claims.name, project: claims.usebecky_project })
98
+ await startSession(c, claims.usebecky_project, claims.usebecky_install, claims.sub)
99
+ deleteCookie(c, BACK, { path: '/' })
100
+ return c.redirect('/settings', 303)
101
+ },
102
+ })(c.req.raw),
103
+ )
104
+
105
+ // 4. Settings for the signed-in customer's project.
106
+ app.get('/settings', async (c) => {
107
+ const s = await session(c)
108
+ const project = s?.project
109
+ if (!project) return c.html(signInPage(c.req.header('cookie')?.includes(`${SESSION}=`) ? 'Your session ended, or the extension was removed from that project. Sign in again.' : undefined), 401)
110
+ try {
111
+ const info = await ext.api(project).project()
112
+ const saved = await settings.get(project)
113
+ const person = s.sub ? await accounts.get(s.sub) : null
114
+ return c.html(settingsPage({ projectName: info.name, websites: info.allowed_hosts, greeting: saved?.greeting ?? '', saved: c.req.query('saved') === '1', backUrl: await backUrl(c), person: person ? { name: person.name, email: person.email } : undefined }))
115
+ } catch (err) {
116
+ if (err instanceof InstallationRevokedError) {
117
+ deleteCookie(c, SESSION, { path: '/' })
118
+ return c.html(signInPage('This extension is no longer connected to that project. Install it again from usebecky.'), 401)
119
+ }
120
+ throw err
121
+ }
122
+ })
123
+
124
+ app.post('/settings', async (c) => {
125
+ const project = await sessionProject(c)
126
+ if (!project) return c.html(signInPage(), 401)
127
+ const form = await c.req.parseBody()
128
+ const greeting = typeof form.greeting === 'string' ? form.greeting.trim() : ''
129
+ if (greeting.length > 120) return c.html(errorPage('Too long', 'Keep the greeting under 120 characters.'), 400)
130
+ await settings.set(project, { greeting })
131
+ return c.redirect('/settings?saved=1', 303)
132
+ })
133
+
134
+ // Disconnect: revoke the tokens at usebecky and delete what we stored.
135
+ app.post('/disconnect', async (c) => {
136
+ const project = await sessionProject(c)
137
+ if (project) {
138
+ await ext.revoke(project)
139
+ await settings.delete(project)
140
+ await accounts.removeProject(project)
141
+ }
142
+ deleteCookie(c, SESSION, { path: '/' })
143
+ return c.redirect('/?disconnected=1', 303)
144
+ })
145
+
146
+ // 5. Webhooks: verified by the kit before any handler runs. Tokens of an uninstalled project are
147
+ // deleted by the kit; delete your own data for it here.
148
+ const webhook = ext.webhookHandler({
149
+ 'extension.installed': (event) => {
150
+ console.log(`Installed on ${event.data.project.name} (${event.project})${event.test ? ' [test event]' : ''}`)
151
+ },
152
+ 'extension.uninstalled': async (event) => {
153
+ // The kit deleted the tokens of the install this event is about. Tokens still there belong to a newer
154
+ // install (a late retry of an old uninstall): keep that install's settings.
155
+ if (await ext.tokenStore.get(event.project)) return
156
+ await settings.delete(event.project)
157
+ await accounts.removeProject(event.project)
158
+ console.log(`Uninstalled from ${event.project}: its data is deleted`)
159
+ },
160
+ })
161
+ app.post('/webhooks/usebecky', (c) => webhook(c.req.raw))
162
+
163
+ // 6. Pages inside usebecky: usebecky asks for them as blocks and draws them in its own design. The kit verifies
164
+ // each request (signed with the webhook secret); viewers can look, only developers and up can save.
165
+ const ui = uiHandler(ext, settings)
166
+ app.post('/usebecky/ui', (c) => ui(c.req.raw))
167
+
168
+ app.get('/privacy', (c) => c.html(privacyPage()))
169
+ app.get('/support', (c) => c.html(supportPage()))
170
+ app.get('/logo.svg', (c) => c.body(fs.readFileSync(new URL('../logo.svg', import.meta.url)), 200, { 'content-type': 'image/svg+xml' }))
171
+ app.get('/healthz', (c) => c.json({ ok: true }))
172
+
173
+ app.onError((err, c) => {
174
+ console.error(`${c.req.method} ${c.req.path} failed: ${err.message}`)
175
+ return c.html(errorPage('Something went wrong', 'Please try again in a moment.'), 500)
176
+ })
177
+ return app
178
+ }