@usebecky/extension 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 (65) hide show
  1. package/README.md +223 -2
  2. package/dist/accounts.d.ts +85 -0
  3. package/dist/accounts.js +149 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli/run.d.ts +25 -0
  7. package/dist/cli/run.js +330 -0
  8. package/dist/cli/skill.d.ts +16 -0
  9. package/dist/cli/skill.js +106 -0
  10. package/dist/crypto.d.ts +12 -0
  11. package/dist/crypto.js +56 -0
  12. package/dist/dev/pages.d.ts +155 -0
  13. package/dist/dev/pages.js +243 -0
  14. package/dist/dev/plans.d.ts +45 -0
  15. package/dist/dev/plans.js +135 -0
  16. package/dist/dev/samples.d.ts +61 -0
  17. package/dist/dev/samples.js +191 -0
  18. package/dist/dev/server.d.ts +120 -0
  19. package/dist/dev/server.js +1657 -0
  20. package/dist/dev/tagging.d.ts +16 -0
  21. package/dist/dev/tagging.js +81 -0
  22. package/dist/dev/ui-render.d.ts +25 -0
  23. package/dist/dev/ui-render.js +256 -0
  24. package/dist/dev/wordmark.d.ts +1 -0
  25. package/dist/dev/wordmark.js +2 -0
  26. package/dist/errors.d.ts +98 -0
  27. package/dist/errors.js +110 -0
  28. package/dist/events.d.ts +92 -0
  29. package/dist/events.js +54 -0
  30. package/dist/extension.d.ts +214 -0
  31. package/dist/extension.js +497 -0
  32. package/dist/handlers.d.ts +39 -0
  33. package/dist/handlers.js +113 -0
  34. package/dist/identity.d.ts +99 -0
  35. package/dist/identity.js +134 -0
  36. package/dist/index.d.ts +14 -0
  37. package/dist/index.js +17 -0
  38. package/dist/jwt.d.ts +62 -0
  39. package/dist/jwt.js +152 -0
  40. package/dist/manifest.d.ts +42 -0
  41. package/dist/manifest.js +785 -0
  42. package/dist/node.d.ts +10 -0
  43. package/dist/node.js +56 -0
  44. package/dist/pkce.d.ts +9 -0
  45. package/dist/pkce.js +16 -0
  46. package/dist/stores.d.ts +100 -0
  47. package/dist/stores.js +159 -0
  48. package/dist/types.d.ts +346 -0
  49. package/dist/types.js +70 -0
  50. package/dist/ui/handler.d.ts +66 -0
  51. package/dist/ui/handler.js +105 -0
  52. package/dist/ui/schema.d.ts +423 -0
  53. package/dist/ui/schema.js +666 -0
  54. package/dist/webhooks.d.ts +26 -0
  55. package/dist/webhooks.js +99 -0
  56. package/package.json +57 -4
  57. package/skill/usebecky-extension/SKILL.md +181 -0
  58. package/skill/usebecky-extension/references/accounts.md +125 -0
  59. package/skill/usebecky-extension/references/dev-server.md +102 -0
  60. package/skill/usebecky-extension/references/manifest.md +104 -0
  61. package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  62. package/skill/usebecky-extension/references/partner-api.md +87 -0
  63. package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  64. package/skill/usebecky-extension/references/ui.md +172 -0
  65. package/skill/usebecky-extension/references/webhooks.md +97 -0
@@ -0,0 +1,330 @@
1
+ // `npx @usebecky/extension <command>` (the bin is called usebecky-extension).
2
+ import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { DEV_CREDENTIALS, DEV_PORT, DEV_PROJECTS, mapToApp, startDevServer } from "../dev/server.js";
6
+ import { SAMPLE_PROJECT, testEvent } from "../dev/samples.js";
7
+ import { ALL_EVENT_TYPES } from "../events.js";
8
+ import { EXTENSION_CAPABILITIES, EXTENSION_SCOPES } from "../types.js";
9
+ import { MANIFEST_FILE, parseManifestJson, validateManifest } from "../manifest.js";
10
+ import { signWebhook } from "../webhooks.js";
11
+ import { findExtensionSkill, installExtensionSkill, writeExtensionAgents, EXTENSION_SKILL_TARGET } from "./skill.js";
12
+ export const VERSION = '0.2.0';
13
+ export const STARTER_COMMAND = 'npx create-usebecky@latest my-extension --template extension';
14
+ const DEFAULT_APP = 'http://localhost:3000';
15
+ const VALUE_FLAGS = new Set(['--port', '--app', '--manifest', '--url', '--secret', '--project', '--token-ttl', '--dev-url', '--capability']);
16
+ export function parseArgs(argv) {
17
+ const dash = argv.indexOf('--');
18
+ const own = dash >= 0 ? argv.slice(0, dash) : argv;
19
+ const rest = dash >= 0 ? argv.slice(dash + 1) : [];
20
+ const flags = {};
21
+ const positionals = [];
22
+ for (let i = 0; i < own.length; i++) {
23
+ const a = own[i];
24
+ if (a.startsWith('-')) {
25
+ const eq = a.indexOf('=');
26
+ const name = eq > 0 ? a.slice(0, eq) : a;
27
+ if (VALUE_FLAGS.has(name)) {
28
+ const v = eq > 0 ? a.slice(eq + 1) : own[++i];
29
+ if (v === undefined || v === '')
30
+ throw new Error(`${name} needs a value.`);
31
+ flags[name] = v;
32
+ }
33
+ else
34
+ flags[name] = true;
35
+ }
36
+ else
37
+ positionals.push(a);
38
+ }
39
+ return { command: positionals.shift(), positionals, flags, rest };
40
+ }
41
+ export async function run(argv, ctx = {}) {
42
+ const cwd = ctx.cwd ?? process.cwd();
43
+ const env = ctx.env ?? process.env;
44
+ const out = ctx.out ?? process.stdout;
45
+ const errOut = ctx.err ?? process.stderr;
46
+ const tty = !ctx.out && !!process.stdout.isTTY && !env.NO_COLOR;
47
+ const paint = (code) => (s) => (tty ? `\u001b[${code}m${s}\u001b[0m` : s);
48
+ const c = { bold: paint('1'), dim: paint('2'), red: paint('31'), green: paint('32'), yellow: paint('33'), cyan: paint('36'), magenta: paint('35') };
49
+ const say = (s = '') => out.write(`${s}\n`);
50
+ const fail = (s, hint) => {
51
+ errOut.write(`${c.red('✖')} ${s}\n`);
52
+ if (hint)
53
+ errOut.write(` ${c.dim(hint)}\n`);
54
+ return 1;
55
+ };
56
+ let args;
57
+ try {
58
+ args = parseArgs(argv);
59
+ }
60
+ catch (e) {
61
+ return fail(e.message, 'Run npx @usebecky/extension help to see the options.');
62
+ }
63
+ const { command, positionals, flags, rest } = args;
64
+ if (flags['--version'] || flags['-v']) {
65
+ say(VERSION);
66
+ return 0;
67
+ }
68
+ const manifestPath = path.resolve(cwd, typeof flags['--manifest'] === 'string' ? flags['--manifest'] : positionals[0] && command === 'validate' ? positionals[0] : MANIFEST_FILE);
69
+ switch (command) {
70
+ case undefined:
71
+ case 'help':
72
+ say(help());
73
+ return 0;
74
+ case 'validate':
75
+ return validate();
76
+ case 'dev':
77
+ return dev();
78
+ case 'send':
79
+ return send();
80
+ case 'init':
81
+ say(`Start a new extension from the starter (a small Hono server with install, callback, settings page, webhooks, tests and the AI skill):\n\n ${c.cyan(STARTER_COMMAND)}\n\nThen: cd my-extension && npm run dev`);
82
+ return 0;
83
+ case 'ai':
84
+ case 'skill':
85
+ return ai();
86
+ default:
87
+ return fail(`Unknown command "${command}".`, 'Commands: validate, dev, send, init, ai. Run npx @usebecky/extension help for details.');
88
+ }
89
+ function help() {
90
+ return `
91
+ ${c.bold(c.magenta('@usebecky/extension'))} ${c.dim(`v${VERSION}`)}: build extensions for the usebecky store.
92
+
93
+ ${c.bold('Usage:')} npx @usebecky/extension <command> ${c.dim('[options]')}
94
+
95
+ ${c.bold('Commands:')}
96
+ ${c.cyan('validate')} [file] Check usebecky-extension.json like usebecky does (default: the one in this folder)
97
+ ${c.cyan('dev')} Run a pretend usebecky on http://localhost:${DEV_PORT}: the store, the consent screen,
98
+ tokens, the partner API with fake data, webhooks. Add ${c.dim('-- <command>')} to start your extension too
99
+ ${c.cyan('send')} <event> Send a signed event (e.g. extension.installed, user.created, test.ping)
100
+ ${c.cyan('init')} How to start a new extension from the starter
101
+ ${c.cyan('ai')} Add the usebecky-extension skill for Claude Code (and AGENTS.md for other assistants)
102
+
103
+ ${c.bold('Options:')}
104
+ --manifest <file> usebecky-extension.json somewhere else
105
+ --local validate: allow an http or local webhook_url, like a usebecky on your computer does
106
+ --port <n> dev: port of the dev server (default ${DEV_PORT})
107
+ --app <url> dev, send: where your extension runs (default ${DEFAULT_APP}); the manifest's
108
+ install_url, redirect_uris and webhook_url are mapped onto it
109
+ --token-ttl <s> dev: access token lifetime in seconds (default 3600; try 120 to watch refreshes)
110
+ --test-project dev: the fake projects act as test projects: "test": true on the installation
111
+ and on every event (default: like real projects)
112
+ --capability <name> dev: act as if usebecky gave your extension this capability (comma-separated), e.g.
113
+ sgtm_forwarding: PUT /extensions/v1/installation/settings then works
114
+ --url <url> send: the webhook address (default: webhook_url mapped onto --app)
115
+ --secret <whsec> send: sign with this secret (default USEBECKY_WEBHOOK_SECRET, else the dev secret)
116
+ --project <ref> send: the project the event is about (default: like the Developer area, sampleproject)
117
+ --force ai: replace skill files you changed
118
+ -v, --version Print the version
119
+ `;
120
+ }
121
+ function readManifest() {
122
+ if (!fs.existsSync(manifestPath))
123
+ return { value: null, problem: `${path.relative(cwd, manifestPath) || manifestPath} does not exist.` };
124
+ const parsed = parseManifestJson(fs.readFileSync(manifestPath, 'utf8'));
125
+ if (parsed.error !== null)
126
+ return { value: null, problem: `${path.basename(manifestPath)}: ${parsed.error}` };
127
+ return { value: parsed.value };
128
+ }
129
+ function validate() {
130
+ const shown = path.relative(cwd, manifestPath) || path.basename(manifestPath);
131
+ if (!fs.existsSync(manifestPath))
132
+ return fail(`${shown} does not exist.`, `Create it in your extension's folder (the starter has one: ${STARTER_COMMAND}).`);
133
+ const parsed = parseManifestJson(fs.readFileSync(manifestPath, 'utf8'));
134
+ if (parsed.error !== null)
135
+ return fail(`${shown}: ${parsed.error}`);
136
+ const dir = path.dirname(manifestPath);
137
+ const local = !!flags['--local'];
138
+ const result = validateManifest(parsed.value, {
139
+ allowPrivateWebhookUrl: local,
140
+ fileInfo: (rel) => {
141
+ try {
142
+ const st = fs.statSync(path.join(dir, rel));
143
+ return st.isFile() ? { size: st.size } : null;
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ },
149
+ });
150
+ const n = (k, word) => `${k} ${word}${k === 1 ? '' : 's'}`;
151
+ const line = (mark, i) => {
152
+ say(` ${mark} ${i.path ? `${c.bold(i.path)}: ` : ''}${i.message}`);
153
+ if (i.hint)
154
+ say(` ${c.dim(i.hint)}`);
155
+ };
156
+ for (const e of result.errors)
157
+ line(c.red('✖'), e);
158
+ for (const w of result.warnings)
159
+ line(c.yellow('!'), w);
160
+ const webhook = parsed.value?.webhook_url;
161
+ if (!local && typeof webhook === 'string' && result.errors.some((e) => e.path === 'webhook_url') && /^http:\/\/(localhost|127\.0\.0\.1|\[::1\])[:/]/i.test(webhook)) {
162
+ say(` ${c.dim('Testing against usebecky on your computer? It allows that address: npx @usebecky/extension validate --local')}`);
163
+ }
164
+ if (result.ok) {
165
+ say(`${c.green('✔')} ${shown} is a valid listing${local ? ' for a local usebecky' : ''}${result.warnings.length ? ` ${c.dim(`(${n(result.warnings.length, 'warning')}: worth fixing before you submit)`)}` : ''}.`);
166
+ return 0;
167
+ }
168
+ say(`\n${c.red('✖')} ${shown}: ${n(result.errors.length, 'problem')} to fix${result.warnings.length ? `, ${n(result.warnings.length, 'warning')}` : ''}.`);
169
+ return 1;
170
+ }
171
+ async function dev() {
172
+ const port = flags['--port'] !== undefined ? Number(flags['--port']) : DEV_PORT;
173
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
174
+ return fail(`--port must be a port number, got "${flags['--port']}".`);
175
+ const appUrl = typeof flags['--app'] === 'string' ? flags['--app'].replace(/\/+$/, '') : DEFAULT_APP;
176
+ try {
177
+ new URL(appUrl);
178
+ }
179
+ catch {
180
+ return fail(`--app must be an address like ${DEFAULT_APP}, got "${appUrl}".`);
181
+ }
182
+ const ttl = flags['--token-ttl'] !== undefined ? Number(flags['--token-ttl']) : undefined;
183
+ if (ttl !== undefined && (!Number.isInteger(ttl) || ttl < 5))
184
+ return fail('--token-ttl is a number of seconds, at least 5.');
185
+ const capabilities = typeof flags['--capability'] === 'string' ? flags['--capability'].split(',').map((x) => x.trim()).filter(Boolean) : [];
186
+ const unknownCap = capabilities.find((x) => !EXTENSION_CAPABILITIES.includes(x));
187
+ if (unknownCap)
188
+ return fail(`--capability: there is no capability "${unknownCap}".`, `Capabilities: ${EXTENSION_CAPABILITIES.join(', ')}.`);
189
+ let server;
190
+ try {
191
+ server = await startDevServer({ port, appUrl, manifestPath, accessTokenTtl: ttl, testProject: !!flags['--test-project'], capabilities: capabilities, log: (l) => say(c.dim(l)), fetch: ctx.fetch });
192
+ }
193
+ catch (e) {
194
+ if (e.code === 'EADDRINUSE')
195
+ return fail(`Port ${port} is already in use (another dev server?).`, `Stop the other program, or pick another port: npx @usebecky/extension dev --port ${port + 1}`);
196
+ throw e;
197
+ }
198
+ const m = readManifest();
199
+ say(`\n${c.bold(c.magenta('usebecky'))} ${c.dim('dev server')} ${c.cyan(server.url)}${flags['--test-project'] ? c.dim(' (test projects: "test": true)') : ''}`);
200
+ if (m.problem)
201
+ say(` ${c.yellow('!')} ${m.problem} ${c.dim('(the dev server works without it, with every scope)')}`);
202
+ else {
203
+ const check = validateManifest(m.value, { allowPrivateWebhookUrl: true });
204
+ if (!check.ok)
205
+ say(` ${c.yellow('!')} usebecky-extension.json has ${check.errors.length} problem${check.errors.length === 1 ? '' : 's'}: run npx @usebecky/extension validate`);
206
+ }
207
+ say(` Your extension ${c.cyan(appUrl)}${rest.length ? c.dim(` (started with: ${rest.join(' ')})`) : c.dim(' (start it with the variables below)')}`);
208
+ if (!rest.length) {
209
+ say(c.dim(` USEBECKY_API_URL=${server.url} USEBECKY_DASHBOARD_URL=${server.url} USEBECKY_CLIENT_ID=${server.credentials.clientId} USEBECKY_CLIENT_SECRET=${server.credentials.clientSecret} USEBECKY_WEBHOOK_SECRET=${server.credentials.webhookSecret}`));
210
+ }
211
+ say(`\n ${c.bold(`Open ${server.url} and click Install.`)} ${c.dim('Press Ctrl+C to stop.')}\n`);
212
+ let child = null;
213
+ const stop = async (code) => {
214
+ if (child && child.exitCode === null)
215
+ child.kill('SIGTERM');
216
+ await server.close();
217
+ return code;
218
+ };
219
+ if (rest.length) {
220
+ const appPort = new URL(appUrl).port || (appUrl.startsWith('https:') ? '443' : '80');
221
+ child = spawn(rest[0], rest.slice(1), {
222
+ cwd,
223
+ stdio: 'inherit',
224
+ env: {
225
+ ...env,
226
+ // The dev server is the API and the dashboard (consent screen) at once; these win over a .env file.
227
+ USEBECKY_API_URL: server.url,
228
+ USEBECKY_DASHBOARD_URL: server.url,
229
+ USEBECKY_CLIENT_ID: server.credentials.clientId,
230
+ USEBECKY_CLIENT_SECRET: server.credentials.clientSecret,
231
+ USEBECKY_WEBHOOK_SECRET: server.credentials.webhookSecret,
232
+ PUBLIC_URL: appUrl,
233
+ PORT: appPort,
234
+ },
235
+ });
236
+ }
237
+ if (ctx.onDevStarted) {
238
+ await ctx.onDevStarted(server);
239
+ return stop(0);
240
+ }
241
+ return new Promise((resolve) => {
242
+ const onSignal = () => void stop(0).then(resolve);
243
+ process.once('SIGINT', onSignal);
244
+ process.once('SIGTERM', onSignal);
245
+ child?.once('error', (e) => {
246
+ fail(`Could not start "${rest[0]}": ${e.message}`);
247
+ void stop(1).then(resolve);
248
+ });
249
+ child?.once('exit', (code) => void stop(code ?? 0).then(resolve));
250
+ });
251
+ }
252
+ async function send() {
253
+ const type = positionals[0];
254
+ if (!type)
255
+ return fail('Which event? For example: npx @usebecky/extension send test.ping', `Events: ${ALL_EVENT_TYPES.join(', ')}`);
256
+ if (!ALL_EVENT_TYPES.includes(type))
257
+ return fail(`"${type}" is not an event usebecky sends.`, `Events: ${ALL_EVENT_TYPES.join(', ')}`);
258
+ const doFetch = ctx.fetch ?? fetch;
259
+ const explicitUrl = typeof flags['--url'] === 'string' ? flags['--url'] : undefined;
260
+ const project = typeof flags['--project'] === 'string' ? flags['--project'] : undefined;
261
+ // A dev server running? It sends with its own install data and secret.
262
+ if (!explicitUrl && !flags['--secret']) {
263
+ const devUrl = (typeof flags['--dev-url'] === 'string' ? flags['--dev-url'] : `http://localhost:${DEV_PORT}`).replace(/\/+$/, '');
264
+ const up = await doFetch(`${devUrl}/healthz`, { signal: AbortSignal.timeout(800) }).then((r) => r.ok, () => false);
265
+ if (up) {
266
+ const r = await doFetch(`${devUrl}/dev/send`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ type, project }) });
267
+ const d = (await r.json().catch(() => null));
268
+ if (!d)
269
+ return fail(`The dev server at ${devUrl} did not answer.`);
270
+ if (d.error)
271
+ return fail(`${type} was not delivered: ${d.error}`);
272
+ say(`${c.green('✔')} Sent ${c.bold(type)} to ${d.url} through the dev server ${c.dim(`(HTTP ${d.status}, ${d.ms} ms)`)}`);
273
+ return 0;
274
+ }
275
+ }
276
+ // No dev server: exactly what the Developer area's "Send test event" sends (project sampleproject, "test": true).
277
+ const m = readManifest();
278
+ const appUrl = typeof flags['--app'] === 'string' ? flags['--app'] : DEFAULT_APP;
279
+ const url = explicitUrl ?? mapToApp(m.value?.webhook_url, appUrl);
280
+ if (!url)
281
+ return fail('Where to? Add webhook_url to usebecky-extension.json, or pass --url http://localhost:3000/webhooks/usebecky');
282
+ const secret = typeof flags['--secret'] === 'string' ? flags['--secret'] : env.USEBECKY_WEBHOOK_SECRET || DEV_CREDENTIALS.webhookSecret;
283
+ const p = project ? (DEV_PROJECTS.find((x) => x.ref === project) ?? { ref: project, name: 'Your project' }) : SAMPLE_PROJECT;
284
+ const slug = typeof m.value?.slug === 'string' ? m.value.slug : 'my-extension';
285
+ const scopes = Array.isArray(m.value?.scopes) ? m.value.scopes.filter((s) => EXTENSION_SCOPES.includes(s)) : [];
286
+ const name = typeof m.value?.name === 'string' ? m.value.name : slug;
287
+ const event = testEvent(type, { slug, scopes, name, pricing: m.value?.pricing }, { ref: p.ref, name: p.name });
288
+ const body = JSON.stringify(event);
289
+ const started = Date.now();
290
+ try {
291
+ const res = await doFetch(url, {
292
+ method: 'POST',
293
+ headers: { 'content-type': 'application/json', 'user-agent': 'usebecky-webhooks/1', 'usebecky-event-id': event.id, 'usebecky-event-type': type, 'usebecky-signature': await signWebhook(body, secret) },
294
+ body,
295
+ redirect: 'manual',
296
+ signal: AbortSignal.timeout(10_000),
297
+ });
298
+ const ms = Date.now() - started;
299
+ if (res.status >= 300 && res.status < 400)
300
+ return fail(`Your webhook answered with a redirect (HTTP ${res.status}).`, 'usebecky never follows redirects: use the final address as webhook_url.');
301
+ if (!res.ok) {
302
+ const text = (await res.text()).slice(0, 300);
303
+ const hint = res.status === 400 && /signature/i.test(text) ? `Signed with ${secret === DEV_CREDENTIALS.webhookSecret ? 'the dev secret' : 'your secret'}. Your extension must use the same USEBECKY_WEBHOOK_SECRET (pass --secret to change it).` : undefined;
304
+ return fail(`Your webhook answered HTTP ${res.status}: ${text}`, hint);
305
+ }
306
+ say(`${c.green('✔')} Sent the test event ${c.bold(type)} to ${url} ${c.dim(`(HTTP ${res.status}, ${ms} ms, signed with ${secret === DEV_CREDENTIALS.webhookSecret ? 'the dev secret' : 'your secret'})`)}`);
307
+ return 0;
308
+ }
309
+ catch (e) {
310
+ return fail(`Could not reach ${url}: ${e.message}`, `Is your extension running? Start it, or pass --url with the right address.`);
311
+ }
312
+ }
313
+ function ai() {
314
+ const source = ctx.skillDir ?? findExtensionSkill();
315
+ if (!source)
316
+ return fail('Could not find the skill files in this installation of @usebecky/extension.', 'Reinstall it: npm install @usebecky/extension@latest');
317
+ const results = installExtensionSkill(source, cwd, !!flags['--force']);
318
+ for (const r of results)
319
+ if (r.status === 'created' || r.status === 'updated')
320
+ say(`${c.green('✔')} ${r.status === 'created' ? 'Created' : 'Updated'} ${r.path}`);
321
+ const kept = results.filter((r) => r.status === 'kept');
322
+ if (kept.length)
323
+ say(`${c.yellow('!')} Kept ${kept.length} skill file${kept.length === 1 ? '' : 's'} you changed ${c.dim('(npx @usebecky/extension ai --force replaces them)')}`);
324
+ const agents = writeExtensionAgents(cwd);
325
+ if (agents.status !== 'unchanged')
326
+ say(`${c.green('✔')} ${agents.status === 'created' ? 'Created' : 'Updated'} ${agents.path} ${c.dim('(for Cursor, Codex, Copilot, Windsurf and other assistants)')}`);
327
+ say(`\nClaude Code now knows how to build usebecky extensions (${EXTENSION_SKILL_TARGET}). Try: ${c.cyan('"Show the visitor numbers of the connected project on the settings page"')}`);
328
+ return 0;
329
+ }
330
+ }
@@ -0,0 +1,16 @@
1
+ export declare const EXTENSION_SKILL_NAME = "usebecky-extension";
2
+ export declare const EXTENSION_SKILL_TARGET = ".claude/skills/usebecky-extension";
3
+ /** `<package>/skill/usebecky-extension`, looked up from this file (src/cli or dist/cli) upwards. */
4
+ export declare function findExtensionSkill(fromDir?: string): string | null;
5
+ export type SkillFileStatus = 'created' | 'updated' | 'unchanged' | 'kept';
6
+ /** Copy the skill. Files you changed are kept unless `force`. */
7
+ export declare function installExtensionSkill(source: string, cwd: string, force?: boolean): Array<{
8
+ path: string;
9
+ status: SkillFileStatus;
10
+ }>;
11
+ export declare function extensionAgentsBlock(): string;
12
+ /** Create or update the usebecky-extension section of AGENTS.md (other sections are left alone). */
13
+ export declare function writeExtensionAgents(cwd: string): {
14
+ path: string;
15
+ status: 'created' | 'appended' | 'updated' | 'unchanged';
16
+ };
@@ -0,0 +1,106 @@
1
+ // The usebecky-extension AI skill: copied into .claude/skills/usebecky-extension/ (Claude Code loads it
2
+ // by itself) plus a short delimited section in AGENTS.md (Cursor, Codex, Copilot, Windsurf...).
3
+ // Used by `npx @usebecky/extension ai` and, as a generated copy, by create-usebecky's extension starter
4
+ // (packages/create-usebecky/scripts/sync-shared.mjs). Keep it self-contained: node:* imports only.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ export const EXTENSION_SKILL_NAME = 'usebecky-extension';
9
+ export const EXTENSION_SKILL_TARGET = `.claude/skills/${EXTENSION_SKILL_NAME}`;
10
+ const AGENTS_FILE = 'AGENTS.md';
11
+ const START = '<!-- usebecky-extension:start -->';
12
+ const END = '<!-- usebecky-extension:end -->';
13
+ /** `<package>/skill/usebecky-extension`, looked up from this file (src/cli or dist/cli) upwards. */
14
+ export function findExtensionSkill(fromDir = path.dirname(fileURLToPath(import.meta.url))) {
15
+ let dir = path.resolve(fromDir);
16
+ for (let i = 0; i < 4; i++) {
17
+ const candidate = path.join(dir, 'skill', EXTENSION_SKILL_NAME);
18
+ if (fs.existsSync(path.join(candidate, 'SKILL.md')))
19
+ return candidate;
20
+ const parent = path.dirname(dir);
21
+ if (parent === dir)
22
+ break;
23
+ dir = parent;
24
+ }
25
+ return null;
26
+ }
27
+ function listFiles(dir) {
28
+ const out = [];
29
+ const walk = (rel) => {
30
+ for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
31
+ if (entry.name.startsWith('.'))
32
+ continue;
33
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
34
+ if (entry.isDirectory())
35
+ walk(child);
36
+ else if (entry.isFile())
37
+ out.push(child);
38
+ }
39
+ };
40
+ walk('');
41
+ return out.sort();
42
+ }
43
+ /** Copy the skill. Files you changed are kept unless `force`. */
44
+ export function installExtensionSkill(source, cwd, force = false) {
45
+ const target = path.join(cwd, ...EXTENSION_SKILL_TARGET.split('/'));
46
+ return listFiles(source).map((rel) => {
47
+ const shown = `${EXTENSION_SKILL_TARGET}/${rel}`;
48
+ const content = fs.readFileSync(path.join(source, ...rel.split('/')));
49
+ const dest = path.join(target, ...rel.split('/'));
50
+ if (!fs.existsSync(dest)) {
51
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
52
+ fs.writeFileSync(dest, content);
53
+ return { path: shown, status: 'created' };
54
+ }
55
+ if (fs.readFileSync(dest).equals(content))
56
+ return { path: shown, status: 'unchanged' };
57
+ if (!force)
58
+ return { path: shown, status: 'kept' };
59
+ fs.writeFileSync(dest, content);
60
+ return { path: shown, status: 'updated' };
61
+ });
62
+ }
63
+ export function extensionAgentsBlock() {
64
+ return `${START}
65
+ ## usebecky extension
66
+
67
+ This folder is an extension for the usebecky store, built with \`@usebecky/extension\`. Before you change anything about installing, OAuth, tokens, webhooks, the partner API, pages inside usebecky or \`usebecky-extension.json\`, read \`${EXTENSION_SKILL_TARGET}/SKILL.md\` and the references it points to.
68
+
69
+ Rules:
70
+
71
+ 1. Use the kit for OAuth, tokens and webhooks (\`createExtension\`, \`oauthHandlers\`, \`webhookHandler\`). Never write your own signature checks, PKCE or token refresh.
72
+ 2. Secrets (client secret, webhook secret, tokens) live in environment variables and the token store, never in code, logs, URLs or the browser.
73
+ 3. Verify every webhook with the kit before you trust it, and delete what you stored for a project on \`extension.uninstalled\`.
74
+ 4. Ask for the fewest scopes that work; describe every one of them in \`data_shared\` in plain words.
75
+ 5. Pages, menu rows, dashboards and settings inside usebecky are blocks answered from \`ext.uiHandler\` (listing \`ui\`): usebecky draws them in its own design. Never HTML, CSS, scripts or an iframe for usebecky. Your own web pages use usebecky's look with your own name and logo.
76
+ 6. Test with \`npm run dev\` (a pretend usebecky) and run \`npx @usebecky/extension validate\` before you submit.
77
+ ${END}`;
78
+ }
79
+ /** Create or update the usebecky-extension section of AGENTS.md (other sections are left alone). */
80
+ export function writeExtensionAgents(cwd) {
81
+ const file = path.join(cwd, AGENTS_FILE);
82
+ const block = extensionAgentsBlock();
83
+ if (!fs.existsSync(file)) {
84
+ fs.writeFileSync(file, `${block}\n`);
85
+ return { path: AGENTS_FILE, status: 'created' };
86
+ }
87
+ const existing = fs.readFileSync(file, 'utf8');
88
+ const start = existing.indexOf(START);
89
+ const end = existing.indexOf(END);
90
+ let content;
91
+ let status;
92
+ if (start >= 0) {
93
+ // A start marker without its end (edited by hand): our section runs to the end of the file.
94
+ const stop = end > start ? end + END.length : existing.length;
95
+ content = existing.slice(0, start) + block + (end > start ? existing.slice(stop) : '\n');
96
+ status = content === existing ? 'unchanged' : 'updated';
97
+ }
98
+ else {
99
+ const trimmed = existing.replace(/\s+$/, '');
100
+ content = `${trimmed ? `${trimmed}\n\n` : ''}${block}\n`;
101
+ status = 'appended';
102
+ }
103
+ if (status !== 'unchanged')
104
+ fs.writeFileSync(file, content);
105
+ return { path: AGENTS_FILE, status };
106
+ }
@@ -0,0 +1,12 @@
1
+ /** base64url without padding (RFC 4648 §5), as PKCE and tokens use it. */
2
+ export declare function base64url(bytes: Uint8Array): string;
3
+ /** `n` random bytes as base64url (n = 32 gives 43 characters: 256 bits). */
4
+ export declare function randomToken(n?: number): string;
5
+ export declare function sha256(input: string): Promise<Uint8Array>;
6
+ export declare function toHex(bytes: Uint8Array): string;
7
+ /** Lowercase or uppercase hex to bytes, or null when it isn't hex. */
8
+ export declare function fromHex(hex: string): Uint8Array | null;
9
+ /** Hex HMAC-SHA256 (what usebecky puts in `v1=`). */
10
+ export declare function hmacSha256Hex(secret: string, message: string): Promise<string>;
11
+ /** Does `signatureHex` equal HMAC-SHA256(secret, message)? Constant time (crypto.subtle.verify). */
12
+ export declare function hmacSha256Verify(secret: string, message: string, signatureHex: string): Promise<boolean>;
package/dist/crypto.js ADDED
@@ -0,0 +1,56 @@
1
+ // Small crypto helpers on Web Crypto (globalThis.crypto), so the kit runs on Node 20+, Bun, Deno and edge
2
+ // runtimes alike. Nothing hand-rolled: SHA-256 and HMAC come from the platform, comparisons are done by
3
+ // crypto.subtle.verify (constant time).
4
+ const encoder = new TextEncoder();
5
+ function subtle() {
6
+ const c = globalThis.crypto;
7
+ if (!c?.subtle)
8
+ throw new Error('Web Crypto is not available. Use Node.js 20 or newer.');
9
+ return c.subtle;
10
+ }
11
+ /** base64url without padding (RFC 4648 §5), as PKCE and tokens use it. */
12
+ export function base64url(bytes) {
13
+ let bin = '';
14
+ for (let i = 0; i < bytes.length; i++)
15
+ bin += String.fromCharCode(bytes[i]);
16
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
17
+ }
18
+ /** `n` random bytes as base64url (n = 32 gives 43 characters: 256 bits). */
19
+ export function randomToken(n = 32) {
20
+ const bytes = new Uint8Array(n);
21
+ globalThis.crypto.getRandomValues(bytes);
22
+ return base64url(bytes);
23
+ }
24
+ export async function sha256(input) {
25
+ return new Uint8Array(await subtle().digest('SHA-256', encoder.encode(input)));
26
+ }
27
+ function hmacKey(secret, usage) {
28
+ return subtle().importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
29
+ }
30
+ export function toHex(bytes) {
31
+ let out = '';
32
+ for (let i = 0; i < bytes.length; i++)
33
+ out += bytes[i].toString(16).padStart(2, '0');
34
+ return out;
35
+ }
36
+ /** Lowercase or uppercase hex to bytes, or null when it isn't hex. */
37
+ export function fromHex(hex) {
38
+ if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(hex))
39
+ return null;
40
+ const out = new Uint8Array(hex.length / 2);
41
+ for (let i = 0; i < out.length; i++)
42
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
43
+ return out;
44
+ }
45
+ /** Hex HMAC-SHA256 (what usebecky puts in `v1=`). */
46
+ export async function hmacSha256Hex(secret, message) {
47
+ const sig = await subtle().sign('HMAC', await hmacKey(secret, 'sign'), encoder.encode(message));
48
+ return toHex(new Uint8Array(sig));
49
+ }
50
+ /** Does `signatureHex` equal HMAC-SHA256(secret, message)? Constant time (crypto.subtle.verify). */
51
+ export async function hmacSha256Verify(secret, message, signatureHex) {
52
+ const sig = fromHex(signatureHex);
53
+ if (!sig || sig.length !== 32)
54
+ return false;
55
+ return subtle().verify('HMAC', await hmacKey(secret, 'verify'), sig, encoder.encode(message));
56
+ }