@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
package/dist/node.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { StoredTokens, TokenStore } from './stores.ts';
2
+ export { toNodeHandler, toFetchRequest, writeFetchResponse, type NodeHandler } from './handlers.ts';
3
+ /**
4
+ * Tokens in a JSON file (readable only by you, written atomically). Good for development and a single
5
+ * small server; with several instances or serverless functions, use a database (sqlTokenStore).
6
+ * Keep the file out of git: it holds every customer's tokens.
7
+ */
8
+ export declare function fileTokenStore(file: string): TokenStore & {
9
+ all(): Promise<StoredTokens[]>;
10
+ };
package/dist/node.js ADDED
@@ -0,0 +1,56 @@
1
+ // Node-only helpers: `import { fileTokenStore, toNodeHandler } from '@usebecky/extension/node'`.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ export { toNodeHandler, toFetchRequest, writeFetchResponse } from "./handlers.js";
5
+ /**
6
+ * Tokens in a JSON file (readable only by you, written atomically). Good for development and a single
7
+ * small server; with several instances or serverless functions, use a database (sqlTokenStore).
8
+ * Keep the file out of git: it holds every customer's tokens.
9
+ */
10
+ export function fileTokenStore(file) {
11
+ const target = path.resolve(file);
12
+ let queue = Promise.resolve();
13
+ async function read() {
14
+ try {
15
+ const data = JSON.parse(await fs.readFile(target, 'utf8'));
16
+ return data && typeof data === 'object' && data.tokens && typeof data.tokens === 'object' ? data.tokens : {};
17
+ }
18
+ catch (err) {
19
+ if (err.code === 'ENOENT')
20
+ return {};
21
+ throw new Error(`Could not read the token file ${target}: ${err.message}`);
22
+ }
23
+ }
24
+ async function write(tokens) {
25
+ await fs.mkdir(path.dirname(target), { recursive: true });
26
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
27
+ await fs.writeFile(tmp, JSON.stringify({ note: 'usebecky extension tokens. Secret: never commit or share this file.', tokens }, null, 2) + '\n', { mode: 0o600 });
28
+ await fs.rename(tmp, target);
29
+ }
30
+ /** One read-modify-write at a time, so two requests never overwrite each other's changes. */
31
+ function change(fn) {
32
+ const next = queue.then(async () => {
33
+ const tokens = await read();
34
+ fn(tokens);
35
+ await write(tokens);
36
+ });
37
+ queue = next.catch(() => { });
38
+ return next;
39
+ }
40
+ return {
41
+ async get(project) {
42
+ await queue;
43
+ return (await read())[project] ?? null;
44
+ },
45
+ set: (t) => change((all) => {
46
+ all[t.project] = { ...t };
47
+ }),
48
+ delete: (project) => change((all) => {
49
+ delete all[project];
50
+ }),
51
+ async all() {
52
+ await queue;
53
+ return Object.values(await read());
54
+ },
55
+ };
56
+ }
package/dist/pkce.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /** A fresh code verifier: 43 characters from [A-Za-z0-9-_] (32 random bytes). */
2
+ export declare function createCodeVerifier(): string;
3
+ /** BASE64URL(SHA256(verifier)): the `code_challenge` for `code_challenge_method=S256`. */
4
+ export declare function codeChallengeFor(verifier: string): Promise<string>;
5
+ export declare function createPkcePair(): Promise<{
6
+ verifier: string;
7
+ challenge: string;
8
+ method: 'S256';
9
+ }>;
package/dist/pkce.js ADDED
@@ -0,0 +1,16 @@
1
+ // PKCE (RFC 7636), S256 only: usebecky refuses `plain`.
2
+ import { base64url, randomToken, sha256 } from "./crypto.js";
3
+ /** A fresh code verifier: 43 characters from [A-Za-z0-9-_] (32 random bytes). */
4
+ export function createCodeVerifier() {
5
+ return randomToken(32);
6
+ }
7
+ /** BASE64URL(SHA256(verifier)): the `code_challenge` for `code_challenge_method=S256`. */
8
+ export async function codeChallengeFor(verifier) {
9
+ if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(verifier))
10
+ throw new Error('A PKCE code verifier is 43 to 128 characters from A-Z, a-z, 0-9 and -._~ (RFC 7636).');
11
+ return base64url(await sha256(verifier));
12
+ }
13
+ export async function createPkcePair() {
14
+ const verifier = createCodeVerifier();
15
+ return { verifier, challenge: await codeChallengeFor(verifier), method: 'S256' };
16
+ }
@@ -0,0 +1,100 @@
1
+ import type { ReplayGuard } from './identity.ts';
2
+ import type { ExtensionScope } from './types.ts';
3
+ export type Awaitable<T> = T | Promise<T>;
4
+ /** One install's tokens. Treat both tokens like passwords: never log them, never send them to a browser. */
5
+ export interface StoredTokens {
6
+ /** The customer's project ref (the key). */
7
+ project: string;
8
+ installationId: string;
9
+ accessToken: string;
10
+ refreshToken: string;
11
+ /** When the access token expires, ms since 1970. */
12
+ expiresAt: number;
13
+ scopes: ExtensionScope[];
14
+ }
15
+ export interface TokenStore {
16
+ get(project: string): Awaitable<StoredTokens | null | undefined>;
17
+ set(tokens: StoredTokens): Awaitable<void>;
18
+ delete(project: string): Awaitable<void>;
19
+ /**
20
+ * Optional. Run `fn` while holding a lock for this project shared by all your server instances, e.g. a
21
+ * Postgres advisory lock or a Redis lock. The kit already refreshes one install at a time inside one
22
+ * process; with several instances, add this so two of them never refresh the same install at once
23
+ * (usebecky rotates refresh tokens and treats a reused one as stolen: it disconnects the install).
24
+ */
25
+ lock?<T>(project: string, fn: () => Promise<T>): Promise<T>;
26
+ }
27
+ /** A sign-in under way: the PKCE verifier and the project the customer started from. */
28
+ export interface PendingAuthorization {
29
+ verifier: string;
30
+ project?: string;
31
+ /** ms since 1970. */
32
+ createdAt: number;
33
+ /** Started by the install handler: the callback must carry its state cookie. */
34
+ browserBound?: boolean;
35
+ /** install_url's `return_url` (the extension's page in the dashboard), when it was on the dashboard's address. */
36
+ returnUrl?: string;
37
+ /** The OpenID nonce sent with the authorize URL: the id_token must repeat it. */
38
+ nonce?: string;
39
+ }
40
+ export interface StateStore {
41
+ set(state: string, value: PendingAuthorization, ttlSeconds: number): Awaitable<void>;
42
+ /** Return the entry and delete it: every state works once. */
43
+ take(state: string): Awaitable<PendingAuthorization | null | undefined>;
44
+ }
45
+ /** Tokens in memory: lost on restart. For tests and trying things out. */
46
+ export declare function memoryTokenStore(): TokenStore & {
47
+ all(): StoredTokens[];
48
+ };
49
+ /**
50
+ * Pending sign-ins in memory (the default). Fine for one server process. With several instances behind a
51
+ * load balancer, the callback may reach another instance: implement StateStore on Redis or your database.
52
+ */
53
+ export declare function memoryStateStore(options?: {
54
+ max?: number;
55
+ now?: () => number;
56
+ }): StateStore;
57
+ /** Runs one statement with positional parameters and returns the rows (for writes: anything). */
58
+ export type SqlQuery = (sql: string, params: unknown[]) => Awaitable<Array<Record<string, unknown>> | unknown>;
59
+ export interface SqlTokenStoreOptions {
60
+ query: SqlQuery;
61
+ /** 'postgres' ($1, $2) or 'sqlite' (?, ?). Default 'postgres'. */
62
+ dialect?: 'postgres' | 'sqlite';
63
+ /** Default 'usebecky_extension_tokens'. */
64
+ table?: string;
65
+ }
66
+ /** The table sqlTokenStore uses. Run it once (a migration, or at start-up). */
67
+ export declare function tokenTableSql(table?: string): string;
68
+ /**
69
+ * Tokens in your SQL database (Postgres or SQLite). `query` is a thin wrapper around your driver:
70
+ *
71
+ * node-postgres: sqlTokenStore({ query: async (sql, params) => (await pool.query(sql, params)).rows })
72
+ * node:sqlite: sqlTokenStore({ dialect: 'sqlite', query: (sql, params) => db.prepare(sql).all(...params) })
73
+ *
74
+ * Create the table first with tokenTableSql(). Consider encrypting the token columns at rest.
75
+ */
76
+ export declare function sqlTokenStore(options: SqlTokenStoreOptions): TokenStore;
77
+ export interface SqlReplayGuardOptions {
78
+ /** The same thin wrapper as sqlTokenStore's. Here it must return the statement's rows (an array). */
79
+ query: SqlQuery;
80
+ /** 'postgres' ($1, $2) or 'sqlite' (?, ?). Default 'postgres'. */
81
+ dialect?: 'postgres' | 'sqlite';
82
+ /** Default 'usebecky_launch_jti'. */
83
+ table?: string;
84
+ /** ms since 1970 (tests). */
85
+ now?: () => number;
86
+ }
87
+ /** The table sqlReplayGuard uses: one row per used launch token id. Run it once, in your token store's database. */
88
+ export declare function replayTableSql(table?: string): string;
89
+ /**
90
+ * Used launch tokens in your SQL database (Postgres or SQLite), shared by all your server instances: an "Open in" link
91
+ * works once, even when two instances get it at the same moment. Required as soon as you run more than one instance
92
+ * (memoryReplayGuard only knows its own process). Pass the same `query` as to sqlTokenStore:
93
+ *
94
+ * node-postgres: sqlReplayGuard({ query: async (sql, params) => (await pool.query(sql, params)).rows })
95
+ * node:sqlite: sqlReplayGuard({ dialect: 'sqlite', query: (sql, params) => db.prepare(sql).all(...params) })
96
+ *
97
+ * Create the table first with replayTableSql(), then `createExtension({ ..., replayGuard })`. A row lives as long as
98
+ * its token (about two minutes); expired rows are deleted along the way.
99
+ */
100
+ export declare function sqlReplayGuard(options: SqlReplayGuardOptions): ReplayGuard;
package/dist/stores.js ADDED
@@ -0,0 +1,159 @@
1
+ // Where the kit keeps things between requests:
2
+ // TokenStore the access and refresh token of each install, keyed by project ref (one install per project)
3
+ // StateStore the PKCE verifier of each sign-in that is under way, keyed by the OAuth `state` (10 minutes)
4
+ // ReplayGuard the launch tokens of "Open in" already used (identity.ts), until they expire (about 2 minutes)
5
+ // Memory stores are for tests and the dev server. Production: fileTokenStore (@usebecky/extension/node) on
6
+ // one server, sqlTokenStore (or your own) with a real database everywhere else, and sqlReplayGuard in the same
7
+ // database as soon as you run more than one server instance.
8
+ import { ConfigError } from "./errors.js";
9
+ /** Tokens in memory: lost on restart. For tests and trying things out. */
10
+ export function memoryTokenStore() {
11
+ const map = new Map();
12
+ return {
13
+ get: (project) => (map.has(project) ? { ...map.get(project) } : null),
14
+ set: (tokens) => {
15
+ map.set(tokens.project, { ...tokens });
16
+ },
17
+ delete: (project) => {
18
+ map.delete(project);
19
+ },
20
+ all: () => [...map.values()].map((t) => ({ ...t })),
21
+ };
22
+ }
23
+ /**
24
+ * Pending sign-ins in memory (the default). Fine for one server process. With several instances behind a
25
+ * load balancer, the callback may reach another instance: implement StateStore on Redis or your database.
26
+ */
27
+ export function memoryStateStore(options = {}) {
28
+ const max = options.max ?? 10_000;
29
+ const now = options.now ?? Date.now;
30
+ const map = new Map();
31
+ return {
32
+ set(state, value, ttlSeconds) {
33
+ const t = now();
34
+ for (const [k, v] of map)
35
+ if (v.until <= t)
36
+ map.delete(k);
37
+ // Someone hammering the install route can't grow this forever: the oldest entries go first.
38
+ while (map.size >= max)
39
+ map.delete(map.keys().next().value);
40
+ map.set(state, { value: { ...value }, until: t + ttlSeconds * 1000 });
41
+ },
42
+ take(state) {
43
+ const hit = map.get(state);
44
+ map.delete(state);
45
+ return hit && hit.until > now() ? hit.value : null;
46
+ },
47
+ };
48
+ }
49
+ /** The table sqlTokenStore uses. Run it once (a migration, or at start-up). */
50
+ export function tokenTableSql(table = 'usebecky_extension_tokens') {
51
+ checkTable(table);
52
+ return `create table if not exists ${table} (
53
+ project text primary key,
54
+ installation_id text not null,
55
+ access_token text not null,
56
+ refresh_token text not null,
57
+ expires_at bigint not null,
58
+ scopes text not null,
59
+ updated_at text not null
60
+ )`;
61
+ }
62
+ /**
63
+ * Tokens in your SQL database (Postgres or SQLite). `query` is a thin wrapper around your driver:
64
+ *
65
+ * node-postgres: sqlTokenStore({ query: async (sql, params) => (await pool.query(sql, params)).rows })
66
+ * node:sqlite: sqlTokenStore({ dialect: 'sqlite', query: (sql, params) => db.prepare(sql).all(...params) })
67
+ *
68
+ * Create the table first with tokenTableSql(). Consider encrypting the token columns at rest.
69
+ */
70
+ export function sqlTokenStore(options) {
71
+ const table = options.table ?? 'usebecky_extension_tokens';
72
+ checkTable(table);
73
+ const p = placeholder(options.dialect);
74
+ const rows = async (sql, params) => {
75
+ const r = await options.query(sql, params);
76
+ return Array.isArray(r) ? r : [];
77
+ };
78
+ return {
79
+ async get(project) {
80
+ const [row] = await rows(`select project, installation_id, access_token, refresh_token, expires_at, scopes from ${table} where project = ${p(1)}`, [project]);
81
+ if (!row)
82
+ return null;
83
+ return {
84
+ project: String(row.project),
85
+ installationId: String(row.installation_id),
86
+ accessToken: String(row.access_token),
87
+ refreshToken: String(row.refresh_token),
88
+ expiresAt: Number(row.expires_at),
89
+ scopes: String(row.scopes).split(' ').filter(Boolean),
90
+ };
91
+ },
92
+ async set(t) {
93
+ await options.query(`insert into ${table} (project, installation_id, access_token, refresh_token, expires_at, scopes, updated_at)
94
+ values (${p(1)}, ${p(2)}, ${p(3)}, ${p(4)}, ${p(5)}, ${p(6)}, ${p(7)})
95
+ on conflict (project) do update set installation_id = excluded.installation_id, access_token = excluded.access_token,
96
+ refresh_token = excluded.refresh_token, expires_at = excluded.expires_at, scopes = excluded.scopes, updated_at = excluded.updated_at`, [t.project, t.installationId, t.accessToken, t.refreshToken, t.expiresAt, t.scopes.join(' '), new Date().toISOString()]);
97
+ },
98
+ async delete(project) {
99
+ await options.query(`delete from ${table} where project = ${p(1)}`, [project]);
100
+ },
101
+ };
102
+ }
103
+ /** The table sqlReplayGuard uses: one row per used launch token id. Run it once, in your token store's database. */
104
+ export function replayTableSql(table = 'usebecky_launch_jti') {
105
+ checkTable(table);
106
+ return `create table if not exists ${table} (
107
+ jti text primary key,
108
+ expires_at bigint not null
109
+ )`;
110
+ }
111
+ /** Expired rows are deleted at most this often (per server process). */
112
+ const REPLAY_CLEANUP_SECONDS = 60;
113
+ /**
114
+ * Used launch tokens in your SQL database (Postgres or SQLite), shared by all your server instances: an "Open in" link
115
+ * works once, even when two instances get it at the same moment. Required as soon as you run more than one instance
116
+ * (memoryReplayGuard only knows its own process). Pass the same `query` as to sqlTokenStore:
117
+ *
118
+ * node-postgres: sqlReplayGuard({ query: async (sql, params) => (await pool.query(sql, params)).rows })
119
+ * node:sqlite: sqlReplayGuard({ dialect: 'sqlite', query: (sql, params) => db.prepare(sql).all(...params) })
120
+ *
121
+ * Create the table first with replayTableSql(), then `createExtension({ ..., replayGuard })`. A row lives as long as
122
+ * its token (about two minutes); expired rows are deleted along the way.
123
+ */
124
+ export function sqlReplayGuard(options) {
125
+ const table = options.table ?? 'usebecky_launch_jti';
126
+ checkTable(table);
127
+ const p = placeholder(options.dialect);
128
+ const now = options.now ?? Date.now;
129
+ let nextCleanup = 0;
130
+ return {
131
+ async use(jti, expiresAt) {
132
+ const t = Math.floor(now() / 1000);
133
+ if (t >= nextCleanup) {
134
+ nextCleanup = t + REPLAY_CLEANUP_SECONDS;
135
+ // Their tokens have expired, so verifyLaunchToken refuses them before it asks the guard.
136
+ await options.query(`delete from ${table} where expires_at < ${p(1)}`, [t]);
137
+ }
138
+ // The primary key decides, on every instance at once: only the first insert of a jti adds a row. `returning`
139
+ // turns "how many rows were added" into rows, the one thing `query` hands back.
140
+ const added = await options.query(`insert into ${table} (jti, expires_at) values (${p(1)}, ${p(2)}) on conflict (jti) do nothing returning jti`, [jti, Math.ceil(expiresAt)]);
141
+ if (!Array.isArray(added)) {
142
+ throw new ConfigError({
143
+ code: 'invalid_option',
144
+ message: 'sqlReplayGuard: query() must return the rows of the statement (an array).',
145
+ hint: 'node-postgres: async (sql, params) => (await pool.query(sql, params)).rows. node:sqlite: (sql, params) => db.prepare(sql).all(...params).',
146
+ });
147
+ }
148
+ return added.length === 1;
149
+ },
150
+ };
151
+ }
152
+ /** Postgres numbers its parameters ($1, $2), SQLite doesn't (?, ?). */
153
+ function placeholder(dialect) {
154
+ return (n) => (dialect === 'sqlite' ? '?' : `$${n}`);
155
+ }
156
+ function checkTable(table) {
157
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(table))
158
+ throw new Error(`"${table}" is not a valid table name (letters, digits and _).`);
159
+ }