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.
- package/README.md +80 -2
- package/dist/create.js +842 -0
- package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
- package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
- package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
- package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
- package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
- package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
- package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
- package/dist/index.js +10 -0
- package/dist/keys.js +72 -0
- package/dist/platform.js +104 -0
- package/dist/pm.js +69 -0
- package/dist/prompts.js +242 -0
- package/dist/scaffold.js +108 -0
- package/dist/setup.js +130 -0
- package/dist/shared/ai.js +203 -0
- package/dist/shared/extension-skill.js +107 -0
- package/dist/shared/framework.js +460 -0
- package/dist/shared/hosted.js +8 -0
- package/dist/shared/ui.js +141 -0
- package/dist/skill/usebecky/SKILL.md +339 -0
- package/dist/skill/usebecky/references/access-rules.md +307 -0
- package/dist/skill/usebecky/references/addons.md +68 -0
- package/dist/skill/usebecky/references/analytics.md +166 -0
- package/dist/skill/usebecky/references/android.md +434 -0
- package/dist/skill/usebecky/references/auth.md +379 -0
- package/dist/skill/usebecky/references/cache.md +51 -0
- package/dist/skill/usebecky/references/components.md +127 -0
- package/dist/skill/usebecky/references/emails.md +105 -0
- package/dist/skill/usebecky/references/expo.md +147 -0
- package/dist/skill/usebecky/references/functions.md +99 -0
- package/dist/skill/usebecky/references/hosting.md +119 -0
- package/dist/skill/usebecky/references/http-api.md +233 -0
- package/dist/skill/usebecky/references/ios.md +355 -0
- package/dist/skill/usebecky/references/payments.md +493 -0
- package/dist/skill/usebecky/references/realtime.md +143 -0
- package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/dist/skill/usebecky/references/sdk.md +838 -0
- package/dist/skill/usebecky/references/storage.md +210 -0
- package/dist/skill/usebecky/references/templates.md +191 -0
- package/dist/skill/usebecky/references/wordpress.md +87 -0
- package/dist/templates.js +74 -0
- package/package.json +37 -4
- package/templates/expo/App.tsx +48 -0
- package/templates/expo/README.md +59 -0
- package/templates/expo/_env.example +4 -0
- package/templates/expo/_gitignore +12 -0
- package/templates/expo/app.json +25 -0
- package/templates/expo/assets/icon.png +0 -0
- package/templates/expo/brand.ts +7 -0
- package/templates/expo/components/Avatar.tsx +75 -0
- package/templates/expo/components/ui.tsx +57 -0
- package/templates/expo/index.ts +4 -0
- package/templates/expo/lib/theme.ts +43 -0
- package/templates/expo/lib/usebecky.ts +15 -0
- package/templates/expo/package.json +29 -0
- package/templates/expo/screens/Home.tsx +187 -0
- package/templates/expo/screens/SignIn.tsx +112 -0
- package/templates/expo/tsconfig.json +6 -0
- package/templates/expo/usebecky.template.json +36 -0
- package/templates/extension/README.md +128 -0
- package/templates/extension/_env.example +21 -0
- package/templates/extension/_gitignore +11 -0
- package/templates/extension/logo.svg +1 -0
- package/templates/extension/package.json +25 -0
- package/templates/extension/src/accounts.ts +90 -0
- package/templates/extension/src/app.ts +178 -0
- package/templates/extension/src/pages.ts +108 -0
- package/templates/extension/src/replay-guard.ts +17 -0
- package/templates/extension/src/server.ts +57 -0
- package/templates/extension/src/settings.ts +69 -0
- package/templates/extension/src/ui.ts +70 -0
- package/templates/extension/test/app.test.ts +222 -0
- package/templates/extension/tsconfig.json +16 -0
- package/templates/extension/usebecky-extension.json +36 -0
- package/templates/extension/usebecky.template.json +22 -0
- package/templates/landing/README.md +43 -0
- package/templates/landing/_env.example +4 -0
- package/templates/landing/_gitignore +9 -0
- package/templates/landing/index.html +16 -0
- package/templates/landing/package.json +28 -0
- package/templates/landing/public/icon.svg +1 -0
- package/templates/landing/src/App.tsx +97 -0
- package/templates/landing/src/components/Contact.tsx +43 -0
- package/templates/landing/src/components/Counter.tsx +34 -0
- package/templates/landing/src/components/Feedback.tsx +36 -0
- package/templates/landing/src/components/Logo.tsx +11 -0
- package/templates/landing/src/components/Receipt.tsx +128 -0
- package/templates/landing/src/components/Setup.tsx +20 -0
- package/templates/landing/src/components/fields.tsx +63 -0
- package/templates/landing/src/content.ts +22 -0
- package/templates/landing/src/index.css +119 -0
- package/templates/landing/src/lib/usebecky.ts +11 -0
- package/templates/landing/src/lib/waitlist.ts +46 -0
- package/templates/landing/src/main.tsx +12 -0
- package/templates/landing/src/vite-env.d.ts +6 -0
- package/templates/landing/tsconfig.json +19 -0
- package/templates/landing/usebecky.template.json +20 -0
- package/templates/landing/vite.config.ts +10 -0
- package/templates/notes/README.md +68 -0
- package/templates/notes/_env.example +4 -0
- package/templates/notes/_gitignore +9 -0
- package/templates/notes/index.html +15 -0
- package/templates/notes/package.json +28 -0
- package/templates/notes/public/icon.svg +1 -0
- package/templates/notes/src/App.tsx +35 -0
- package/templates/notes/src/brand.ts +7 -0
- package/templates/notes/src/components/Composer.tsx +113 -0
- package/templates/notes/src/components/NoteEntry.tsx +151 -0
- package/templates/notes/src/components/Notes.tsx +163 -0
- package/templates/notes/src/components/Setup.tsx +44 -0
- package/templates/notes/src/components/SignIn.tsx +112 -0
- package/templates/notes/src/components/icons.tsx +54 -0
- package/templates/notes/src/index.css +105 -0
- package/templates/notes/src/lib/notes.ts +68 -0
- package/templates/notes/src/lib/usebecky.ts +9 -0
- package/templates/notes/src/main.tsx +22 -0
- package/templates/notes/src/vite-env.d.ts +6 -0
- package/templates/notes/tsconfig.json +19 -0
- package/templates/notes/usebecky.template.json +34 -0
- package/templates/notes/vite.config.ts +10 -0
- package/templates/saas/README.md +69 -0
- package/templates/saas/_env.example +10 -0
- package/templates/saas/_gitignore +11 -0
- package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
- package/templates/saas/app/(app)/account/page.tsx +71 -0
- package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
- package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
- package/templates/saas/app/(app)/layout.tsx +29 -0
- package/templates/saas/app/(app)/premium/page.tsx +62 -0
- package/templates/saas/app/auth/callback/page.tsx +33 -0
- package/templates/saas/app/globals.css +143 -0
- package/templates/saas/app/icon.svg +1 -0
- package/templates/saas/app/layout.tsx +20 -0
- package/templates/saas/app/page.tsx +87 -0
- package/templates/saas/app/pricing/Plans.tsx +133 -0
- package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
- package/templates/saas/app/pricing/page.tsx +21 -0
- package/templates/saas/app/setup/page.tsx +34 -0
- package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
- package/templates/saas/app/sign-in/page.tsx +21 -0
- package/templates/saas/brand.ts +10 -0
- package/templates/saas/components/AppNav.tsx +45 -0
- package/templates/saas/components/Logo.tsx +22 -0
- package/templates/saas/components/SiteHeader.tsx +50 -0
- package/templates/saas/components/Status.tsx +15 -0
- package/templates/saas/lib/session.ts +26 -0
- package/templates/saas/lib/usebecky.ts +11 -0
- package/templates/saas/next-env.d.ts +5 -0
- package/templates/saas/next.config.ts +5 -0
- package/templates/saas/package.json +26 -0
- package/templates/saas/postcss.config.mjs +3 -0
- package/templates/saas/tsconfig.json +21 -0
- package/templates/saas/usebecky.template.json +31 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The extension's pages. Plain HTML from template strings: every value goes through `html`, which
|
|
2
|
+
// escapes it, so nothing a customer types can turn into markup.
|
|
3
|
+
export const NAME = 'My Extension'
|
|
4
|
+
|
|
5
|
+
/** Escapes values placed in it (strings, numbers, arrays of `html` results). */
|
|
6
|
+
export function html(strings: TemplateStringsArray, ...values: unknown[]): Safe {
|
|
7
|
+
let out = strings[0]
|
|
8
|
+
values.forEach((v, i) => {
|
|
9
|
+
out += render(v) + strings[i + 1]
|
|
10
|
+
})
|
|
11
|
+
return new Safe(out)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class Safe {
|
|
15
|
+
readonly value: string
|
|
16
|
+
constructor(value: string) {
|
|
17
|
+
this.value = value
|
|
18
|
+
}
|
|
19
|
+
toString() {
|
|
20
|
+
return this.value
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function render(v: unknown): string {
|
|
25
|
+
if (v instanceof Safe) return v.value
|
|
26
|
+
if (Array.isArray(v)) return v.map(render).join('')
|
|
27
|
+
if (v === null || v === undefined || v === false) return ''
|
|
28
|
+
return String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// usebecky's look, so customers coming from usebecky don't feel they left it: an aubergine bar with YOUR logo and name
|
|
32
|
+
// (never usebecky's wordmark or logo), square controls, the main button in usebecky orange with aubergine text (white on
|
|
33
|
+
// that orange is too faint), burnt-orange links and focus rings, light and dark, fine at 390 px. Your pages inside
|
|
34
|
+
// usebecky (src/ui.ts) get the real thing: usebecky draws them itself.
|
|
35
|
+
const CSS = `
|
|
36
|
+
:root{--bar:#2c001e;--fill:#ff6a2c;--fill-hover:#ff8450;--on-fill:#2c001e;--accent:#b8420f;--paper:#f6f7fa;--surface:#fff;--sunken:#eef0f5;--ink:#141b33;--ink-2:#333c55;--muted:#4f5970;--line:#e0e4ec;--line-strong:#cbd2de;--ok:#e5f6ef;--bad:#fdecec;color-scheme:light}
|
|
37
|
+
@media (prefers-color-scheme:dark){:root{--accent:#ff6a2c;--paper:#0e121b;--surface:#151b28;--sunken:#111621;--ink:#eceef5;--ink-2:#c9cfdc;--muted:#a6aec0;--line:#232b3b;--line-strong:#333d52;--ok:#10302a;--bad:#3a1a1f;color-scheme:dark}}
|
|
38
|
+
*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.55 Figtree,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
39
|
+
header{background:var(--bar);color:#fff;min-height:64px;padding:0 20px;display:flex;align-items:center;gap:12px}
|
|
40
|
+
header img{width:32px;height:32px;border-radius:6px;background:#fff;object-fit:contain}header strong{font-size:18px;font-weight:800;letter-spacing:-.01em}
|
|
41
|
+
main{max-width:640px;margin:0 auto;padding:32px 20px 64px}h1{font-size:30px;font-weight:800;line-height:1.15;letter-spacing:-.03em;margin:0 0 8px}p{margin:0 0 14px;color:var(--ink-2)}.muted{color:var(--muted)}
|
|
42
|
+
a{color:var(--accent)}label{display:block;font-weight:600;margin:20px 0 6px}.box label:first-child{margin-top:0}
|
|
43
|
+
input[type=text]{width:100%;font:inherit;padding:9px 12px;border:1px solid var(--line-strong);border-radius:4px;background:var(--surface);color:var(--ink)}
|
|
44
|
+
button,.button{font:inherit;font-weight:600;padding:9px 16px;border-radius:4px;border:1px solid var(--line-strong);background:var(--surface);color:var(--ink);cursor:pointer;text-decoration:none;display:inline-block}
|
|
45
|
+
.primary{background:var(--fill);border-color:var(--fill);color:var(--on-fill);font-weight:700}.primary:hover{background:var(--fill-hover);border-color:var(--fill-hover)}.row{display:flex;flex-wrap:wrap;gap:10px;margin-top:20px}
|
|
46
|
+
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
47
|
+
.box{background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:16px;margin:20px 0}
|
|
48
|
+
.note{background:var(--ok);border-radius:4px;padding:12px 16px;margin-bottom:20px;color:var(--ink)}.note.bad{background:var(--bad)}
|
|
49
|
+
`
|
|
50
|
+
|
|
51
|
+
export function layout(title: string, body: Safe): string {
|
|
52
|
+
return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style>${new Safe(CSS)}</style></head>
|
|
53
|
+
<body><header><img src="/logo.svg" alt=""><strong>${NAME}</strong></header><main>${body}</main></body></html>`.value
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function homePage(opts: { signedIn: boolean; notice?: string }): string {
|
|
57
|
+
return layout(
|
|
58
|
+
NAME,
|
|
59
|
+
html`${opts.notice ? html`<p class="note">${opts.notice}</p>` : ''}
|
|
60
|
+
<h1>${NAME}</h1>
|
|
61
|
+
<p>An extension for usebecky. Add it to your project in usebecky: <strong>Extensions</strong>, then <strong>${NAME}</strong> and <strong>Install</strong>.</p>
|
|
62
|
+
${opts.signedIn ? html`<p><a class="button primary" href="/settings">Open settings</a></p>` : ''}`,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function settingsPage(opts: { projectName: string; websites: string[]; greeting: string; saved: boolean; backUrl?: string; error?: string; person?: { name: string | null; email: string } }): string {
|
|
67
|
+
return layout(
|
|
68
|
+
`Settings · ${NAME}`,
|
|
69
|
+
html`${opts.saved ? html`<p class="note">Saved.</p>` : ''}${opts.error ? html`<p class="note bad">${opts.error}</p>` : ''}
|
|
70
|
+
<h1>Settings</h1>
|
|
71
|
+
<p class="muted">Connected to <strong>${opts.projectName}</strong>${opts.websites.length ? html` (${opts.websites.join(', ')})` : ''}.${opts.backUrl ? html` <a href="${opts.backUrl}">Back to usebecky</a>` : ''}</p>
|
|
72
|
+
${opts.person ? html`<p class="muted">Signed in as <strong>${opts.person.name ?? opts.person.email}</strong> (${opts.person.email}), through usebecky.</p>` : ''}
|
|
73
|
+
<form method="post" action="/settings" class="box">
|
|
74
|
+
<label for="greeting">Greeting</label>
|
|
75
|
+
<input id="greeting" name="greeting" type="text" maxlength="120" value="${opts.greeting}" placeholder="Hello from ${NAME}">
|
|
76
|
+
<div class="row"><button class="primary" type="submit">Save</button></div>
|
|
77
|
+
</form>
|
|
78
|
+
<form method="post" action="/disconnect"><button type="submit">Disconnect from ${opts.projectName}</button></form>`,
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function signInPage(reason?: string): string {
|
|
83
|
+
return layout(
|
|
84
|
+
`Sign in · ${NAME}`,
|
|
85
|
+
html`${reason ? html`<p class="note bad">${reason}</p>` : ''}
|
|
86
|
+
<h1>Open your settings</h1>
|
|
87
|
+
<p>Open ${NAME} from usebecky: in your project, <strong>Extensions</strong>, then <strong>${NAME}</strong> and <strong>Open in ${NAME}</strong>. No password needed.</p>
|
|
88
|
+
<p><a class="button primary" href="/install">Sign in with usebecky</a></p>`,
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function errorPage(title: string, message: string): string {
|
|
93
|
+
return layout(title, html`<h1>${title}</h1><p>${message}</p><p><a href="/install">Try again</a></p>`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Replace with your own policy before you submit: say what you store, why, and that uninstalling deletes it. */
|
|
97
|
+
export function privacyPage(): string {
|
|
98
|
+
return layout(
|
|
99
|
+
`Privacy · ${NAME}`,
|
|
100
|
+
html`<h1>Privacy</h1>
|
|
101
|
+
<p>${NAME} stores, for each usebecky project it is installed on: the project's id, access tokens from usebecky, the settings you save, and your account: the name and email address usebecky shares when you install (so you never sign up here). It reads your project's name and the websites it allows from usebecky when you open the settings.</p>
|
|
102
|
+
<p>When you uninstall ${NAME}, it deletes all of this.</p>`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function supportPage(): string {
|
|
107
|
+
return layout(`Support · ${NAME}`, html`<h1>Support</h1><p>Questions about ${NAME}? Write to <a href="mailto:you@example.com">you@example.com</a>.</p>`)
|
|
108
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// "Open in" links already used: usebecky's launch tokens work once, so the app remembers each one until it expires
|
|
2
|
+
// (about two minutes). They live in a small SQLite file next to the token file, with Node's built-in node:sqlite (no
|
|
3
|
+
// extra package): a restart forgets nothing, and every process on this server shares them.
|
|
4
|
+
// More than one server? Point this and the token store at one shared Postgres database: see the README.
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
8
|
+
import { replayTableSql, sqlReplayGuard, type ReplayGuard } from '@usebecky/extension'
|
|
9
|
+
|
|
10
|
+
export function sqliteReplayGuard(file: string): ReplayGuard {
|
|
11
|
+
fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
|
|
12
|
+
const db = new DatabaseSync(file)
|
|
13
|
+
// Two processes may write at the same moment: wait for the other one instead of failing.
|
|
14
|
+
db.exec('pragma busy_timeout = 5000')
|
|
15
|
+
db.exec(replayTableSql())
|
|
16
|
+
return sqlReplayGuard({ dialect: 'sqlite', query: (sql, params) => db.prepare(sql).all(...(params as Array<string | number>)) })
|
|
17
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Starts My Extension. `npm run dev` runs it next to a pretend usebecky (the variables below are set for
|
|
2
|
+
// you); `npm start` runs it against the real usebecky with the values from .env.
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import { serve } from '@hono/node-server'
|
|
6
|
+
import { ConfigError, createExtension } from '@usebecky/extension'
|
|
7
|
+
import { fileTokenStore } from '@usebecky/extension/node'
|
|
8
|
+
import { fileAccountStore } from './accounts.ts'
|
|
9
|
+
import { createApp } from './app.ts'
|
|
10
|
+
import { sqliteReplayGuard } from './replay-guard.ts'
|
|
11
|
+
import { fileSettingsStore } from './settings.ts'
|
|
12
|
+
|
|
13
|
+
const env = process.env
|
|
14
|
+
const publicUrl = (env.PUBLIC_URL || 'http://localhost:3000').replace(/\/+$/, '')
|
|
15
|
+
const port = Number(env.PORT || 3000)
|
|
16
|
+
const onHttps = publicUrl.startsWith('https://')
|
|
17
|
+
|
|
18
|
+
let sessionSecret = env.SESSION_SECRET
|
|
19
|
+
if (!sessionSecret) {
|
|
20
|
+
if (onHttps) {
|
|
21
|
+
console.error('✖ SESSION_SECRET is missing. Make one with `openssl rand -hex 32` and add it to your environment.')
|
|
22
|
+
process.exit(1)
|
|
23
|
+
}
|
|
24
|
+
// On your computer: a random one, kept in .data/ so you stay signed in when the server restarts.
|
|
25
|
+
const file = '.data/dev-session-secret'
|
|
26
|
+
if (!fs.existsSync(file)) {
|
|
27
|
+
fs.mkdirSync('.data', { recursive: true })
|
|
28
|
+
fs.writeFileSync(file, crypto.randomBytes(32).toString('hex'), { mode: 0o600 })
|
|
29
|
+
}
|
|
30
|
+
sessionSecret = fs.readFileSync(file, 'utf8').trim()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const ext = createExtension({
|
|
35
|
+
clientId: env.USEBECKY_CLIENT_ID ?? '',
|
|
36
|
+
clientSecret: env.USEBECKY_CLIENT_SECRET ?? '',
|
|
37
|
+
webhookSecret: env.USEBECKY_WEBHOOK_SECRET,
|
|
38
|
+
redirectUri: `${publicUrl}/oauth/callback`,
|
|
39
|
+
// Unset: usebecky (https://api.usebecky.com, consent screen on https://app.usebecky.com). `npm run dev` sets both
|
|
40
|
+
// to the pretend usebecky.
|
|
41
|
+
apiUrl: env.USEBECKY_API_URL,
|
|
42
|
+
dashboardUrl: env.USEBECKY_DASHBOARD_URL,
|
|
43
|
+
// Tokens of every install. A file is fine on one server; see the README to use a database.
|
|
44
|
+
tokenStore: fileTokenStore('.data/tokens.json'),
|
|
45
|
+
// "Open in" links already used (each works once), in a SQLite file next to the tokens. More than one server:
|
|
46
|
+
// keep both in a shared Postgres database instead (see the README).
|
|
47
|
+
replayGuard: sqliteReplayGuard('.data/replay.sqlite'),
|
|
48
|
+
})
|
|
49
|
+
// The customers' accounts, created from what usebecky says about them (never a sign-up form).
|
|
50
|
+
const app = createApp({ ext, settings: fileSettingsStore('.data/settings.json'), accounts: fileAccountStore('.data/accounts.json'), sessionSecret, secureCookies: onHttps })
|
|
51
|
+
serve({ fetch: app.fetch, port }, () => console.log(`My Extension is running on ${publicUrl} (usebecky: ${ext.apiUrl}, consent screen: ${ext.authorizeEndpoint})`))
|
|
52
|
+
} catch (err) {
|
|
53
|
+
if (!(err instanceof ConfigError)) throw err
|
|
54
|
+
console.error(`✖ ${err.message}${err.hint ? `\n ${err.hint}` : ''}`)
|
|
55
|
+
console.error(' To try it without credentials, run: npm run dev')
|
|
56
|
+
process.exit(1)
|
|
57
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// What this extension stores per project: the customer's settings. Keep it to what you need, and delete
|
|
2
|
+
// it on uninstall (src/app.ts does, on extension.uninstalled).
|
|
3
|
+
//
|
|
4
|
+
// A JSON file is fine while you build and for one small server. With more than one server, or a host
|
|
5
|
+
// without a disk (serverless), store settings in a database, next to the tokens (see the README).
|
|
6
|
+
import fs from 'node:fs/promises'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
|
|
9
|
+
export interface Settings {
|
|
10
|
+
greeting: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SettingsStore {
|
|
14
|
+
get(project: string): Promise<Settings | null>
|
|
15
|
+
set(project: string, settings: Settings): Promise<void>
|
|
16
|
+
delete(project: string): Promise<void>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function memorySettingsStore(): SettingsStore {
|
|
20
|
+
const map = new Map<string, Settings>()
|
|
21
|
+
return {
|
|
22
|
+
get: async (project) => map.get(project) ?? null,
|
|
23
|
+
set: async (project, settings) => void map.set(project, { ...settings }),
|
|
24
|
+
delete: async (project) => void map.delete(project),
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function fileSettingsStore(file: string): SettingsStore {
|
|
29
|
+
const target = path.resolve(file)
|
|
30
|
+
let queue: Promise<unknown> = Promise.resolve()
|
|
31
|
+
|
|
32
|
+
async function read(): Promise<Record<string, Settings>> {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(await fs.readFile(target, 'utf8'))
|
|
35
|
+
} catch (err) {
|
|
36
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {}
|
|
37
|
+
throw err
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One change at a time; written to a temporary file first, so a crash never leaves half a file. */
|
|
42
|
+
function change(fn: (all: Record<string, Settings>) => void): Promise<void> {
|
|
43
|
+
const next = queue.then(async () => {
|
|
44
|
+
const all = await read()
|
|
45
|
+
fn(all)
|
|
46
|
+
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
47
|
+
const tmp = `${target}.tmp`
|
|
48
|
+
await fs.writeFile(tmp, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 })
|
|
49
|
+
await fs.rename(tmp, target)
|
|
50
|
+
})
|
|
51
|
+
queue = next.catch(() => {})
|
|
52
|
+
return next
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
async get(project) {
|
|
57
|
+
await queue
|
|
58
|
+
return (await read())[project] ?? null
|
|
59
|
+
},
|
|
60
|
+
set: (project, settings) =>
|
|
61
|
+
change((all) => {
|
|
62
|
+
all[project] = { ...settings }
|
|
63
|
+
}),
|
|
64
|
+
delete: (project) =>
|
|
65
|
+
change((all) => {
|
|
66
|
+
delete all[project]
|
|
67
|
+
}),
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// My Extension's pages inside usebecky (`ui` in usebecky-extension.json): a row in the customer's sidebar and a settings
|
|
2
|
+
// view on the extension's page under Extensions. usebecky asks POST /usebecky/ui for them and draws the blocks this
|
|
3
|
+
// answers with in its own design (light, dark, phones): no HTML, no CSS, no iframe. Every block: the skill's
|
|
4
|
+
// references/ui.md.
|
|
5
|
+
//
|
|
6
|
+
// greeting the sidebar row "Greeting" (Website & sales): the project's websites and whether they show the greeting
|
|
7
|
+
// settings the greeting, as a form (the same setting as /settings on this extension's own website)
|
|
8
|
+
import { InstallationRevokedError, type Extension, type View } from '@usebecky/extension'
|
|
9
|
+
import { NAME } from './pages.ts'
|
|
10
|
+
import type { SettingsStore } from './settings.ts'
|
|
11
|
+
|
|
12
|
+
export function uiHandler(ext: Extension, settings: SettingsStore) {
|
|
13
|
+
return ext.uiHandler({
|
|
14
|
+
pages: {
|
|
15
|
+
greeting: async (ctx): Promise<View> => {
|
|
16
|
+
const saved = await settings.get(ctx.project.ref)
|
|
17
|
+
let websites: string[] = []
|
|
18
|
+
try {
|
|
19
|
+
websites = (await ctx.api.project()).allowed_hosts
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if (!(err instanceof InstallationRevokedError)) throw err
|
|
22
|
+
return { blocks: [{ type: 'notice', tone: 'warning', title: 'Not connected', text: `Connect ${NAME} again under Extensions to see your project here.` }] }
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
description: `What ${NAME} does for ${ctx.project.name}.`,
|
|
26
|
+
actions: [{ label: 'Change the greeting', page: 'settings' }],
|
|
27
|
+
blocks: [
|
|
28
|
+
{
|
|
29
|
+
type: 'stats',
|
|
30
|
+
items: [
|
|
31
|
+
{ label: 'Websites', value: websites.length.toLocaleString('en') },
|
|
32
|
+
{ label: 'Greeting', value: saved?.greeting ? 'On' : 'Off', hint: saved?.greeting ? `“${saved.greeting.slice(0, 40)}”` : 'Not set yet' },
|
|
33
|
+
],
|
|
34
|
+
},
|
|
35
|
+
websites.length
|
|
36
|
+
? {
|
|
37
|
+
type: 'table',
|
|
38
|
+
columns: [{ key: 'host', label: 'Website' }, { key: 'status', label: 'Greeting' }],
|
|
39
|
+
// A wildcard (*.example.com) is a pattern, not an address: shown, not linked.
|
|
40
|
+
rows: websites.map((host) => ({ id: host, cells: { host: host.includes('*') ? host : { text: host, url: `https://${host}` }, status: saved?.greeting ? { text: 'Shown', tone: 'success' } : { text: 'Not set', tone: 'neutral' } } })),
|
|
41
|
+
}
|
|
42
|
+
: { type: 'empty', title: 'No websites yet', text: 'Add a website to your project in usebecky, and it shows up here.' },
|
|
43
|
+
],
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
settings: async (ctx): Promise<View> => {
|
|
47
|
+
const saved = await settings.get(ctx.project.ref)
|
|
48
|
+
return {
|
|
49
|
+
blocks: [
|
|
50
|
+
{
|
|
51
|
+
type: 'form',
|
|
52
|
+
action: 'save',
|
|
53
|
+
submit: 'Save',
|
|
54
|
+
fields: [{ key: 'greeting', label: 'Greeting', type: 'text', placeholder: `Hello from ${NAME}`, max_length: 120, help: 'Shown on your websites.' }],
|
|
55
|
+
values: { greeting: saved?.greeting ?? '' },
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
actions: {
|
|
62
|
+
save: async (ctx) => {
|
|
63
|
+
const greeting = String(ctx.action.values.greeting ?? '').trim()
|
|
64
|
+
if (greeting.length > 120) return { errors: { greeting: 'Keep the greeting under 120 characters.' } }
|
|
65
|
+
await settings.set(ctx.project.ref, { greeting })
|
|
66
|
+
return { toast: greeting ? 'Saved.' : 'Greeting removed.' }
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// The whole extension against the pretend usebecky (the same dev server `npm run dev` starts):
|
|
2
|
+
// install → consent screen → callback (the account is created from the id_token) → settings page → "Open in"
|
|
3
|
+
// (single sign-on) → webhooks → uninstall.
|
|
4
|
+
// npm test
|
|
5
|
+
import assert from 'node:assert/strict'
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import type { AddressInfo } from 'node:net'
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { after, before, describe, it } from 'node:test'
|
|
11
|
+
import { serve } from '@hono/node-server'
|
|
12
|
+
import { createExtension, memoryTokenStore, signWebhook, type ReplayGuard } from '@usebecky/extension'
|
|
13
|
+
import { DEV_CREDENTIALS, startDevServer, type DevServer } from '@usebecky/extension/dev'
|
|
14
|
+
import { createApp } from '../src/app.ts'
|
|
15
|
+
import { memoryAccountStore } from '../src/accounts.ts'
|
|
16
|
+
import { sqliteReplayGuard } from '../src/replay-guard.ts'
|
|
17
|
+
import { memorySettingsStore } from '../src/settings.ts'
|
|
18
|
+
|
|
19
|
+
let dev: DevServer
|
|
20
|
+
let appUrl = ''
|
|
21
|
+
let closeApp: () => void
|
|
22
|
+
const tokens = memoryTokenStore()
|
|
23
|
+
const settings = memorySettingsStore()
|
|
24
|
+
const accounts = memoryAccountStore()
|
|
25
|
+
// The used "Open in" links, in a SQLite file like src/server.ts keeps them (in a temporary folder here).
|
|
26
|
+
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'my-extension-test-'))
|
|
27
|
+
const replayFile = path.join(dataDir, 'replay.sqlite')
|
|
28
|
+
const SESSION_SECRET = 'test-secret-0123456789abcdef'
|
|
29
|
+
/** One server of the extension: its own process in real life, sharing the tokens and the replay file. */
|
|
30
|
+
const appWith = (replayGuard: ReplayGuard) => createApp({ ext: createExtension({ ...DEV_CREDENTIALS, redirectUri: `${appUrl}/oauth/callback`, apiUrl: dev.url, tokenStore: tokens, replayGuard }), settings, accounts, sessionSecret: SESSION_SECRET })
|
|
31
|
+
/** The customer's `sub` (from the launch token), to check their account goes on uninstall. */
|
|
32
|
+
let personSub = ''
|
|
33
|
+
let cookie = ''
|
|
34
|
+
const manifestPath = new URL('../usebecky-extension.json', import.meta.url)
|
|
35
|
+
const listing = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as { name: string; slug: string; ui: { pages: Array<{ id: string; label: string }> } }
|
|
36
|
+
const escaped = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')
|
|
37
|
+
|
|
38
|
+
before(async () => {
|
|
39
|
+
// The app's server starts first (the dev server needs its address), then gets its routes.
|
|
40
|
+
let handler: (req: Request) => Response | Promise<Response> = () => new Response('starting', { status: 503 })
|
|
41
|
+
const server = serve({ fetch: (req) => handler(req), port: 0 })
|
|
42
|
+
await new Promise((r) => server.once('listening', r))
|
|
43
|
+
appUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
|
|
44
|
+
closeApp = () => server.close()
|
|
45
|
+
dev = await startDevServer({ port: 0, appUrl, manifestPath: decodeURIComponent(manifestPath.pathname), log: () => {} })
|
|
46
|
+
handler = appWith(sqliteReplayGuard(replayFile)).fetch
|
|
47
|
+
})
|
|
48
|
+
after(async () => {
|
|
49
|
+
await dev.close()
|
|
50
|
+
closeApp()
|
|
51
|
+
fs.rmSync(dataDir, { recursive: true, force: true })
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
const get = (path: string, withCookie = true) => fetch(`${appUrl}${path}`, { redirect: 'manual', headers: withCookie && cookie ? { cookie } : {} })
|
|
55
|
+
const until = async (check: () => boolean | Promise<boolean>) => {
|
|
56
|
+
for (let i = 0; i < 300 && !(await check()); i++) await new Promise((r) => setTimeout(r, 10))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe(listing.name, () => {
|
|
60
|
+
it('installs like a customer would: Install in the store → install_url → consent screen → callback → settings', async () => {
|
|
61
|
+
// The store's Install opens install_url with ?project=<ref>&return_url=<the extension's page in the project>.
|
|
62
|
+
const store = await (await fetch(dev.url)).text()
|
|
63
|
+
const install = [...store.matchAll(/<a class="button primary" href="([^"]+)">Install<\/a>/g)].map((m) => m[1].replace(/&/g, '&')).find((l) => l.includes('project=devshop00001'))!
|
|
64
|
+
assert.ok(install.startsWith(`${appUrl}/install?`), install)
|
|
65
|
+
const toConsent = await fetch(install, { redirect: 'manual' })
|
|
66
|
+
assert.equal(toConsent.status, 302)
|
|
67
|
+
const consent = await fetch(toConsent.headers.get('location')!)
|
|
68
|
+
const page = await consent.text()
|
|
69
|
+
assert.ok(page.includes(`Connect ${escaped(listing.name)}`), 'the consent screen shows the listing name')
|
|
70
|
+
const fields = Object.fromEntries([...page.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)].map((m) => [m[1], m[2].replace(/&/g, '&')]))
|
|
71
|
+
const back = await fetch(`${dev.url}/oauth/authorize`, { method: 'POST', body: new URLSearchParams({ ...fields, project: 'devshop00001', decision: 'allow' }), redirect: 'manual' })
|
|
72
|
+
// The browser sends back the state cookie /install set: the sign-in only finishes where it started.
|
|
73
|
+
const stateCookie = toConsent.headers.getSetCookie().map((c) => c.split(';')[0]).join('; ')
|
|
74
|
+
const callback = await fetch(back.headers.get('location')!, { redirect: 'manual', headers: { cookie: stateCookie } })
|
|
75
|
+
assert.equal(callback.status, 302)
|
|
76
|
+
assert.equal(callback.headers.get('location'), '/settings')
|
|
77
|
+
const session = callback.headers.getSetCookie().find((c) => c.startsWith('session='))!
|
|
78
|
+
// The browser keeps every cookie the callback set (the session and "Back to usebecky"), not the cleared state cookie.
|
|
79
|
+
cookie = callback.headers
|
|
80
|
+
.getSetCookie()
|
|
81
|
+
.map((c) => c.split(';')[0])
|
|
82
|
+
.filter((c) => !c.endsWith('='))
|
|
83
|
+
.join('; ')
|
|
84
|
+
assert.match(session, /HttpOnly/i)
|
|
85
|
+
assert.ok(callback.headers.getSetCookie().some((c) => /^usebecky_oauth_state=;/.test(c)), 'the state cookie is cleared')
|
|
86
|
+
assert.ok(await tokens.get('devshop00001'), 'tokens stored')
|
|
87
|
+
|
|
88
|
+
const settingsPage = await get('/settings')
|
|
89
|
+
assert.equal(settingsPage.status, 200)
|
|
90
|
+
const html = await settingsPage.text()
|
|
91
|
+
assert.match(html, /Connected to <strong>Acme Shop<\/strong> \(shop\.example\.com, www\.shop\.example\.com\)/)
|
|
92
|
+
assert.ok(html.includes(`<a href="${dev.url}/project/devshop00001/extensions/${listing.slug}">Back to usebecky</a>`), 'back to the extension’s page in usebecky')
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it('the account was created automatically from the id_token: no sign-up form', async () => {
|
|
96
|
+
const html = await (await get('/settings')).text()
|
|
97
|
+
assert.match(html, /Signed in as <strong>Ada Lovelace<\/strong> \(ada@example\.com\), through usebecky\./)
|
|
98
|
+
const consent = await (await fetch(`${dev.url}/oauth/authorize?${new URL((await get('/install', false)).headers.get('location')!).searchParams}`)).text()
|
|
99
|
+
assert.match(consent, /creates your account with your name and email, no password needed/)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('"Open in" from usebecky signs the customer in without a password, once per link', async () => {
|
|
103
|
+
const launch = await dev.launchUrl('devshop00001')
|
|
104
|
+
assert.ok(launch.startsWith(`${appUrl}/sso?launch=`), launch)
|
|
105
|
+
personSub = JSON.parse(Buffer.from(new URL(launch).searchParams.get('launch')!.split('.')[1], 'base64url').toString('utf8')).sub
|
|
106
|
+
assert.ok(await accounts.get(personSub), 'the account made at install is the one "Open in" signs into')
|
|
107
|
+
const res = await fetch(launch, { redirect: 'manual' })
|
|
108
|
+
assert.equal(res.status, 303)
|
|
109
|
+
assert.equal(res.headers.get('location'), '/settings')
|
|
110
|
+
const session = res.headers.getSetCookie().find((c) => c.startsWith('session='))!
|
|
111
|
+
assert.match(session, /HttpOnly/i)
|
|
112
|
+
const page = await fetch(`${appUrl}/settings`, { headers: { cookie: session.split(';')[0] } })
|
|
113
|
+
assert.equal(page.status, 200)
|
|
114
|
+
assert.match(await page.text(), /Signed in as <strong>Ada Lovelace<\/strong>/)
|
|
115
|
+
const again = await fetch(launch, { redirect: 'manual' })
|
|
116
|
+
assert.equal(again.status, 401)
|
|
117
|
+
assert.match(await again.text(), /already used/)
|
|
118
|
+
assert.ok(!again.headers.getSetCookie().some((c) => c.startsWith('session=')))
|
|
119
|
+
const forged = await fetch(`${appUrl}/sso?launch=not-a-token`, { redirect: 'manual' })
|
|
120
|
+
assert.equal(forged.status, 401)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('a second server sharing the replay file refuses a link the first one used', async () => {
|
|
124
|
+
// Its own connection to the same SQLite file, like a second process would open.
|
|
125
|
+
const second = appWith(sqliteReplayGuard(replayFile))
|
|
126
|
+
const launch = await dev.launchUrl('devshop00001')
|
|
127
|
+
assert.equal((await fetch(launch, { redirect: 'manual' })).status, 303, 'the first server signs the customer in')
|
|
128
|
+
const replay = await second.fetch(new Request(launch))
|
|
129
|
+
assert.equal(replay.status, 401, 'the second server knows the link was used')
|
|
130
|
+
assert.match(await replay.text(), /already used/)
|
|
131
|
+
assert.equal((await second.fetch(new Request(await dev.launchUrl('devshop00001')))).status, 303, 'a new link works on either server')
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('saves a setting, escaped on the page', async () => {
|
|
135
|
+
const save = await fetch(`${appUrl}/settings`, { method: 'POST', headers: { cookie, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ greeting: 'Hi <there>' }), redirect: 'manual' })
|
|
136
|
+
assert.equal(save.status, 303)
|
|
137
|
+
assert.deepEqual(await settings.get('devshop00001'), { greeting: 'Hi <there>' })
|
|
138
|
+
const html = await (await get('/settings?saved=1')).text()
|
|
139
|
+
assert.match(html, /value="Hi <there>"/)
|
|
140
|
+
assert.match(html, /Saved\./)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('its pages inside usebecky: the sidebar row and the settings view, drawn by the dev server from src/ui.ts', async () => {
|
|
144
|
+
const row = listing.ui.pages[0]
|
|
145
|
+
const overview = await fetch(`${dev.url}/project/devshop00001/x/${row.id}`)
|
|
146
|
+
assert.equal(overview.status, 200, await overview.clone().text())
|
|
147
|
+
const html = await overview.text()
|
|
148
|
+
assert.ok(html.includes(`<h1>${escaped(row.label)}</h1>`), 'the sidebar row\'s label is the title')
|
|
149
|
+
assert.match(html, /<div class="l">Websites<\/div>/)
|
|
150
|
+
assert.match(html, /“Hi <there>”|“Hi <there>”/, 'the greeting saved on the settings page, escaped')
|
|
151
|
+
const ext = await (await fetch(`${dev.url}/project/devshop00001/extensions/${listing.slug}`)).text()
|
|
152
|
+
assert.match(ext, /<h2>Settings view<\/h2>/)
|
|
153
|
+
const types = JSON.stringify({ greeting: 'text' })
|
|
154
|
+
const tooLong = await fetch(`${dev.url}/project/devshop00001/x/settings`, { method: 'POST', body: new URLSearchParams({ _action: 'save', _params: '{}', _types: types, 'f.greeting': 'x'.repeat(121) }), redirect: 'manual' })
|
|
155
|
+
assert.match(await tooLong.text(), /Keep the greeting under 120 characters\./)
|
|
156
|
+
const saved = await fetch(`${dev.url}/project/devshop00001/x/settings`, { method: 'POST', body: new URLSearchParams({ _action: 'save', _params: '{}', _types: types, 'f.greeting': 'Hello from usebecky' }), redirect: 'manual' })
|
|
157
|
+
assert.equal(saved.status, 302)
|
|
158
|
+
assert.deepEqual(await settings.get('devshop00001'), { greeting: 'Hello from usebecky' })
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
it('a callback link opened in another browser does not sign anyone in', async () => {
|
|
162
|
+
const toConsent = await get('/install?project=devblog00002', false)
|
|
163
|
+
const page = await (await fetch(toConsent.headers.get('location')!)).text()
|
|
164
|
+
const fields = Object.fromEntries([...page.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)].map((m) => [m[1], m[2].replace(/&/g, '&')]))
|
|
165
|
+
const back = await fetch(`${dev.url}/oauth/authorize`, { method: 'POST', body: new URLSearchParams({ ...fields, project: 'devblog00002', decision: 'allow' }), redirect: 'manual' })
|
|
166
|
+
const res = await fetch(back.headers.get('location')!, { redirect: 'manual' }) // no state cookie
|
|
167
|
+
assert.equal(res.status, 400)
|
|
168
|
+
assert.ok(!res.headers.getSetCookie().some((c) => c.startsWith('session=')))
|
|
169
|
+
assert.equal(await tokens.get('devblog00002'), null)
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it('without the cookie, or with a forged one, the settings page asks to sign in', async () => {
|
|
173
|
+
assert.equal((await get('/settings', false)).status, 401)
|
|
174
|
+
const forged = await fetch(`${appUrl}/settings`, { headers: { cookie: 'session=devblog00002.forged' } })
|
|
175
|
+
assert.equal(forged.status, 401)
|
|
176
|
+
assert.match(await forged.text(), /Sign in with usebecky/)
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
it('accepts signed events and refuses unsigned ones', async () => {
|
|
180
|
+
const d = await dev.sendEvent('test.ping', 'devshop00001')
|
|
181
|
+
assert.equal(d.status, 200, d.error ?? "")
|
|
182
|
+
const body = JSON.stringify({ id: 'evt_x', type: 'extension.uninstalled', created_at: new Date().toISOString(), project: 'devshop00001', data: {} })
|
|
183
|
+
const forged = await fetch(`${appUrl}/webhooks/usebecky`, { method: 'POST', body, headers: { 'usebecky-signature': await signWebhook(body, 'whsec_wrong') } })
|
|
184
|
+
assert.equal(forged.status, 400)
|
|
185
|
+
assert.ok(await settings.get('devshop00001'), 'a forged uninstall deletes nothing')
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('a late retry of an older uninstall keeps the current install and its settings', async () => {
|
|
189
|
+
const current = (await tokens.get('devshop00001'))!
|
|
190
|
+
const body = JSON.stringify({ id: 'evt_old', type: 'extension.uninstalled', created_at: new Date().toISOString(), project: 'devshop00001', data: { extension: listing.slug, installation_id: 'an-older-install', project: { ref: 'devshop00001', name: 'Acme Shop' }, scopes: ['project:read'], reason: 'customer' } })
|
|
191
|
+
const res = await fetch(`${appUrl}/webhooks/usebecky`, { method: 'POST', body, headers: { 'usebecky-signature': await signWebhook(body, DEV_CREDENTIALS.webhookSecret) } })
|
|
192
|
+
assert.equal(res.status, 200)
|
|
193
|
+
assert.equal((await tokens.get('devshop00001'))?.installationId, current.installationId)
|
|
194
|
+
assert.ok(await settings.get('devshop00001'))
|
|
195
|
+
assert.equal((await get('/settings')).status, 200)
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
it('uninstall deletes the tokens and the settings of that project', async () => {
|
|
199
|
+
await fetch(`${dev.url}/dev/uninstall`, { method: 'POST', body: new URLSearchParams({ project: 'devshop00001' }), redirect: 'manual' })
|
|
200
|
+
await until(async () => (await settings.get('devshop00001')) === null)
|
|
201
|
+
assert.equal(await settings.get('devshop00001'), null)
|
|
202
|
+
assert.equal(await tokens.get('devshop00001'), null)
|
|
203
|
+
await until(async () => (await accounts.get(personSub)) === null)
|
|
204
|
+
assert.equal(await accounts.get(personSub), null, 'the account goes with its last project')
|
|
205
|
+
const page = await get('/settings')
|
|
206
|
+
assert.equal(page.status, 401)
|
|
207
|
+
assert.match(await page.text(), /removed from that project/, 'the old session cookie opens nothing')
|
|
208
|
+
const save = await fetch(`${appUrl}/settings`, { method: 'POST', headers: { cookie, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ greeting: 'too late' }), redirect: 'manual' })
|
|
209
|
+
assert.equal(save.status, 401)
|
|
210
|
+
assert.equal(await settings.get('devshop00001'), null, 'nothing written after the uninstall')
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
it('Cancel on the consent screen shows "Not connected"', async () => {
|
|
214
|
+
const consentUrl = (await get('/install')).headers.get('location')!
|
|
215
|
+
const page = await (await fetch(consentUrl)).text()
|
|
216
|
+
const fields = Object.fromEntries([...page.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)].map((m) => [m[1], m[2].replace(/&/g, '&')]))
|
|
217
|
+
const back = await fetch(`${dev.url}/oauth/authorize`, { method: 'POST', body: new URLSearchParams({ ...fields, project: 'devshop00001', decision: 'deny' }), redirect: 'manual' })
|
|
218
|
+
const res = await fetch(back.headers.get('location')!)
|
|
219
|
+
assert.equal(res.status, 400)
|
|
220
|
+
assert.match(await res.text(), /Not connected/)
|
|
221
|
+
})
|
|
222
|
+
})
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2023",
|
|
4
|
+
"lib": ["ES2023"],
|
|
5
|
+
"module": "NodeNext",
|
|
6
|
+
"moduleResolution": "NodeNext",
|
|
7
|
+
"types": ["node"],
|
|
8
|
+
"strict": true,
|
|
9
|
+
"noEmit": true,
|
|
10
|
+
"allowImportingTsExtensions": true,
|
|
11
|
+
"verbatimModuleSyntax": true,
|
|
12
|
+
"erasableSyntaxOnly": true,
|
|
13
|
+
"skipLibCheck": true
|
|
14
|
+
},
|
|
15
|
+
"include": ["src", "test"]
|
|
16
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"slug": "my-extension",
|
|
3
|
+
"name": "My Extension",
|
|
4
|
+
"publisher": {
|
|
5
|
+
"name": "Your company",
|
|
6
|
+
"website": "https://my-extension.example.com",
|
|
7
|
+
"email": "you@example.com"
|
|
8
|
+
},
|
|
9
|
+
"logo_url": "logo.svg",
|
|
10
|
+
"summary": "Greets every project it is installed on. Say here what yours does.",
|
|
11
|
+
"description": "My Extension is a starting point for your own extension. After you install it, it adds a page to your project's sidebar with your websites, and lets you save a greeting.\n\n**Your account** is created automatically with your name and email when you install it, and you open My Extension from usebecky without signing in.\n\n**What it needs:** your project's name and the websites it allows, nothing else.\n\n**When you uninstall it**, it deletes everything it stored about your project.",
|
|
12
|
+
"category": "other",
|
|
13
|
+
"pricing": { "model": "free" },
|
|
14
|
+
"links": {
|
|
15
|
+
"privacy": "https://my-extension.example.com/privacy",
|
|
16
|
+
"support": "https://my-extension.example.com/support"
|
|
17
|
+
},
|
|
18
|
+
"connect": {
|
|
19
|
+
"mode": "oauth",
|
|
20
|
+
"install_url": "https://my-extension.example.com/install",
|
|
21
|
+
"redirect_uris": ["https://my-extension.example.com/oauth/callback"]
|
|
22
|
+
},
|
|
23
|
+
"scopes": ["project:read"],
|
|
24
|
+
"webhook_url": "https://my-extension.example.com/webhooks/usebecky",
|
|
25
|
+
"data_shared": ["Your project's name and the websites it allows", "Your name and email address, to create your account"],
|
|
26
|
+
"account": {
|
|
27
|
+
"required": true,
|
|
28
|
+
"provision": "oauth",
|
|
29
|
+
"sso_url": "https://my-extension.example.com/sso"
|
|
30
|
+
},
|
|
31
|
+
"ui": {
|
|
32
|
+
"url": "https://my-extension.example.com/usebecky/ui",
|
|
33
|
+
"pages": [{ "id": "greeting", "label": "Greeting", "section": "website" }],
|
|
34
|
+
"settings": true
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "extension",
|
|
3
|
+
"name": "Extension",
|
|
4
|
+
"description": "An extension for the usebecky store: install, a page inside usebecky, settings, webhooks",
|
|
5
|
+
"stack": "Hono + @usebecky/extension",
|
|
6
|
+
"kind": "node",
|
|
7
|
+
"framework": "node",
|
|
8
|
+
"project": false,
|
|
9
|
+
"skill": "usebecky-extension",
|
|
10
|
+
"order": 5,
|
|
11
|
+
"defaultName": "my-extension",
|
|
12
|
+
"brandName": "My Extension",
|
|
13
|
+
"brandSlug": "my-extension",
|
|
14
|
+
"brandFiles": ["usebecky-extension.json", "src/pages.ts", "src/server.ts", "README.md"],
|
|
15
|
+
"customize": { "name": "usebecky-extension.json (name, summary, description)", "colour": "logo.svg (your pages use usebecky's look with it)" },
|
|
16
|
+
"run": {
|
|
17
|
+
"script": "dev",
|
|
18
|
+
"url": "http://localhost:4400",
|
|
19
|
+
"note": "That is a pretend usebecky on your computer: click Install to try your extension."
|
|
20
|
+
},
|
|
21
|
+
"docs": [{ "title": "Build an extension", "path": "guides/build-an-extension" }]
|
|
22
|
+
}
|