@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.
- package/README.md +223 -2
- package/dist/accounts.d.ts +85 -0
- package/dist/accounts.js +149 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/run.d.ts +25 -0
- package/dist/cli/run.js +330 -0
- package/dist/cli/skill.d.ts +16 -0
- package/dist/cli/skill.js +106 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +56 -0
- package/dist/dev/pages.d.ts +155 -0
- package/dist/dev/pages.js +243 -0
- package/dist/dev/plans.d.ts +45 -0
- package/dist/dev/plans.js +135 -0
- package/dist/dev/samples.d.ts +61 -0
- package/dist/dev/samples.js +191 -0
- package/dist/dev/server.d.ts +120 -0
- package/dist/dev/server.js +1657 -0
- package/dist/dev/tagging.d.ts +16 -0
- package/dist/dev/tagging.js +81 -0
- package/dist/dev/ui-render.d.ts +25 -0
- package/dist/dev/ui-render.js +256 -0
- package/dist/dev/wordmark.d.ts +1 -0
- package/dist/dev/wordmark.js +2 -0
- package/dist/errors.d.ts +98 -0
- package/dist/errors.js +110 -0
- package/dist/events.d.ts +92 -0
- package/dist/events.js +54 -0
- package/dist/extension.d.ts +214 -0
- package/dist/extension.js +497 -0
- package/dist/handlers.d.ts +39 -0
- package/dist/handlers.js +113 -0
- package/dist/identity.d.ts +99 -0
- package/dist/identity.js +134 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +17 -0
- package/dist/jwt.d.ts +62 -0
- package/dist/jwt.js +152 -0
- package/dist/manifest.d.ts +42 -0
- package/dist/manifest.js +785 -0
- package/dist/node.d.ts +10 -0
- package/dist/node.js +56 -0
- package/dist/pkce.d.ts +9 -0
- package/dist/pkce.js +16 -0
- package/dist/stores.d.ts +100 -0
- package/dist/stores.js +159 -0
- package/dist/types.d.ts +346 -0
- package/dist/types.js +70 -0
- package/dist/ui/handler.d.ts +66 -0
- package/dist/ui/handler.js +105 -0
- package/dist/ui/schema.d.ts +423 -0
- package/dist/ui/schema.js +666 -0
- package/dist/webhooks.d.ts +26 -0
- package/dist/webhooks.js +99 -0
- package/package.json +57 -4
- package/skill/usebecky-extension/SKILL.md +181 -0
- package/skill/usebecky-extension/references/accounts.md +125 -0
- package/skill/usebecky-extension/references/dev-server.md +102 -0
- package/skill/usebecky-extension/references/manifest.md +104 -0
- package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/skill/usebecky-extension/references/partner-api.md +87 -0
- package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/skill/usebecky-extension/references/ui.md +172 -0
- package/skill/usebecky-extension/references/webhooks.md +97 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type JwksClient } from './jwt.ts';
|
|
2
|
+
import type { Awaitable } from './stores.ts';
|
|
3
|
+
/** The JWT `typ` of a launch token. An id_token says "JWT": one can never be used as the other. */
|
|
4
|
+
export declare const LAUNCH_TOKEN_TYPE = "usebecky-launch+jwt";
|
|
5
|
+
/** The query parameter usebecky adds to your sso_url. */
|
|
6
|
+
export declare const LAUNCH_PARAM = "launch";
|
|
7
|
+
/** The OpenID scopes usebecky grants (all three) when your listing creates accounts from the sign-in. */
|
|
8
|
+
export declare const OIDC_SCOPES: readonly ["openid", "email", "profile"];
|
|
9
|
+
/** id_tokens last 10 minutes. */
|
|
10
|
+
export declare const ID_TOKEN_TTL_SECONDS = 600;
|
|
11
|
+
/** Launch tokens last 60 seconds. */
|
|
12
|
+
export declare const LAUNCH_TOKEN_TTL_SECONDS = 60;
|
|
13
|
+
/** Clocks may be this far apart (default for both checks). */
|
|
14
|
+
export declare const DEFAULT_CLOCK_SKEW_SECONDS = 60;
|
|
15
|
+
/** The person's role in the team that owns the project. */
|
|
16
|
+
export type UsebeckyRole = 'owner' | 'admin' | 'developer' | 'viewer';
|
|
17
|
+
/** What usebecky says about the customer in both tokens. */
|
|
18
|
+
export interface UsebeckyIdentity {
|
|
19
|
+
/** usebecky's API address (`https://api.usebecky.com`). */
|
|
20
|
+
iss: string;
|
|
21
|
+
/** Pairwise: stable for this person and your extension only. Your key for the account. */
|
|
22
|
+
sub: string;
|
|
23
|
+
/** Your client id. */
|
|
24
|
+
aud: string;
|
|
25
|
+
iat: number;
|
|
26
|
+
exp: number;
|
|
27
|
+
/** The account's email address (id_token: with the `email` scope, always granted). */
|
|
28
|
+
email?: string;
|
|
29
|
+
/** True only when usebecky has proved the address (a GitHub or Google sign-in). Don't link existing accounts by an unverified email. */
|
|
30
|
+
email_verified?: boolean;
|
|
31
|
+
/** The account's name, when it has one. */
|
|
32
|
+
name?: string;
|
|
33
|
+
/** The project's ref. One install per project. */
|
|
34
|
+
usebecky_project: string;
|
|
35
|
+
/** The install's id (the same as `installation_id` in the token response and webhooks). */
|
|
36
|
+
usebecky_install: string;
|
|
37
|
+
usebecky_role: UsebeckyRole;
|
|
38
|
+
}
|
|
39
|
+
/** The claims of a verified id_token. */
|
|
40
|
+
export interface IdTokenClaims extends UsebeckyIdentity {
|
|
41
|
+
/** The nonce your authorize URL sent (the kit checks it). */
|
|
42
|
+
nonce?: string;
|
|
43
|
+
}
|
|
44
|
+
/** The claims of a verified launch token. */
|
|
45
|
+
export interface LaunchClaims extends UsebeckyIdentity {
|
|
46
|
+
/** Single use: the replay guard has seen it now. */
|
|
47
|
+
jti: string;
|
|
48
|
+
/** Your own account id, as your provision endpoint returned it (provision "url" listings). */
|
|
49
|
+
partner_account_id?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Remembers launch token ids until they expire, so a launch link works once. With more than one server instance it
|
|
53
|
+
* must be shared by all of them (sqlReplayGuard() in your database, or your own on Redis): otherwise a stolen link
|
|
54
|
+
* works once on every instance.
|
|
55
|
+
*/
|
|
56
|
+
export interface ReplayGuard {
|
|
57
|
+
/** True the first time `jti` is seen; false when it was used before. `expiresAt` is unix seconds (keep it until then). */
|
|
58
|
+
use(jti: string, expiresAt: number): Awaitable<boolean>;
|
|
59
|
+
}
|
|
60
|
+
/** In memory: one server process only. With more than one instance use sqlReplayGuard() (or your own on Redis: SET NX EXAT). */
|
|
61
|
+
export declare function memoryReplayGuard(options?: {
|
|
62
|
+
max?: number;
|
|
63
|
+
now?: () => number;
|
|
64
|
+
}): ReplayGuard;
|
|
65
|
+
export interface TokenVerifyOptions {
|
|
66
|
+
/** Your client id (`ub_ci_...`): the token's audience. */
|
|
67
|
+
clientId: string;
|
|
68
|
+
/** usebecky's API address (default https://api.usebecky.com): the issuer, and where the JWKS is. */
|
|
69
|
+
apiUrl?: string;
|
|
70
|
+
/** Overrides the issuer (default: apiUrl). */
|
|
71
|
+
issuer?: string;
|
|
72
|
+
/** A JWKS client to share its cache (default: one per address, kept by the kit). */
|
|
73
|
+
jwks?: JwksClient;
|
|
74
|
+
/** Seconds the clocks may differ (default 60). */
|
|
75
|
+
clockSkewSeconds?: number;
|
|
76
|
+
/** Unix seconds "now", or a function returning it (tests). */
|
|
77
|
+
now?: number | (() => number);
|
|
78
|
+
fetch?: typeof fetch;
|
|
79
|
+
}
|
|
80
|
+
export interface IdTokenVerifyOptions extends TokenVerifyOptions {
|
|
81
|
+
/** The nonce you put in the authorize URL. When given, the token must carry exactly this one. */
|
|
82
|
+
nonce?: string;
|
|
83
|
+
}
|
|
84
|
+
export interface LaunchVerifyOptions extends TokenVerifyOptions {
|
|
85
|
+
/** Default: one in-memory guard per client id (one server process). More than one instance: sqlReplayGuard(). */
|
|
86
|
+
replayGuard?: ReplayGuard;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Verify an id_token from usebecky's token response (handleCallback() does it for you and returns `identity`): ES256
|
|
90
|
+
* signature against usebecky's JWKS, issuer, audience = your client id, expiry with clock skew, and the nonce when you
|
|
91
|
+
* pass one. Throws TokenVerificationError.
|
|
92
|
+
*/
|
|
93
|
+
export declare function verifyIdToken(token: unknown, options: IdTokenVerifyOptions): Promise<IdTokenClaims>;
|
|
94
|
+
/**
|
|
95
|
+
* Verify the launch token of "Open in <your service>" (the `launch` query parameter on your sso_url): ES256 signature,
|
|
96
|
+
* issuer, audience, at most 60 seconds old, and single use (the replay guard remembers its jti). Throws
|
|
97
|
+
* TokenVerificationError; send the person back to usebecky to open your service again.
|
|
98
|
+
*/
|
|
99
|
+
export declare function verifyLaunchToken(token: unknown, options: LaunchVerifyOptions): Promise<LaunchClaims>;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Who the customer is: usebecky's OpenID Connect id_tokens and the launch tokens of "Open in <your service>".
|
|
2
|
+
//
|
|
3
|
+
// Customers never sign up at your service by hand. usebecky tells you who they are, signed with its ES256 keys
|
|
4
|
+
// (https://api.usebecky.com/.well-known/jwks.json), and you create or link the account:
|
|
5
|
+
// - id_token in the OAuth token response, when your listing creates accounts from the sign-in
|
|
6
|
+
// (account.provision "oauth"). handleCallback() verifies it and hands you the claims as `identity`.
|
|
7
|
+
// - launch token usebecky sends the customer to your sso_url?launch=<token> ("Open in" in the dashboard). Valid for
|
|
8
|
+
// 60 seconds and once: verifyLaunchToken() checks it and remembers its jti (the replay guard).
|
|
9
|
+
// Both carry a pairwise `sub`: stable for one person and your extension, different for every other extension, never
|
|
10
|
+
// usebecky's internal id. Link accounts by `sub`, not by email (use the email only when email_verified is true).
|
|
11
|
+
import { TokenVerificationError } from "./errors.js";
|
|
12
|
+
import { createJwks, decodeJwt, JWT_ALGORITHMS, verifySignature } from "./jwt.js";
|
|
13
|
+
/** usebecky's API address: the issuer of every token (a local usebecky or the dev server: their own address). */
|
|
14
|
+
const DEFAULT_API_URL = 'https://api.usebecky.com';
|
|
15
|
+
/** The JWT `typ` of a launch token. An id_token says "JWT": one can never be used as the other. */
|
|
16
|
+
export const LAUNCH_TOKEN_TYPE = 'usebecky-launch+jwt';
|
|
17
|
+
/** The query parameter usebecky adds to your sso_url. */
|
|
18
|
+
export const LAUNCH_PARAM = 'launch';
|
|
19
|
+
/** The OpenID scopes usebecky grants (all three) when your listing creates accounts from the sign-in. */
|
|
20
|
+
export const OIDC_SCOPES = ['openid', 'email', 'profile'];
|
|
21
|
+
/** id_tokens last 10 minutes. */
|
|
22
|
+
export const ID_TOKEN_TTL_SECONDS = 600;
|
|
23
|
+
/** Launch tokens last 60 seconds. */
|
|
24
|
+
export const LAUNCH_TOKEN_TTL_SECONDS = 60;
|
|
25
|
+
/** Clocks may be this far apart (default for both checks). */
|
|
26
|
+
export const DEFAULT_CLOCK_SKEW_SECONDS = 60;
|
|
27
|
+
/** In memory: one server process only. With more than one instance use sqlReplayGuard() (or your own on Redis: SET NX EXAT). */
|
|
28
|
+
export function memoryReplayGuard(options = {}) {
|
|
29
|
+
const max = options.max ?? 100_000;
|
|
30
|
+
const now = options.now ?? Date.now;
|
|
31
|
+
const seen = new Map();
|
|
32
|
+
return {
|
|
33
|
+
use(jti, expiresAt) {
|
|
34
|
+
const t = now() / 1000;
|
|
35
|
+
for (const [k, until] of seen)
|
|
36
|
+
if (until < t)
|
|
37
|
+
seen.delete(k);
|
|
38
|
+
if (seen.has(jti))
|
|
39
|
+
return false;
|
|
40
|
+
while (seen.size >= max)
|
|
41
|
+
seen.delete(seen.keys().next().value);
|
|
42
|
+
seen.set(jti, expiresAt);
|
|
43
|
+
return true;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const fail = (code, message, hint) => new TokenVerificationError({ code, message, hint, status: 401 });
|
|
48
|
+
const trimSlash = (s) => s.replace(/\/+$/, '');
|
|
49
|
+
const jwksClients = new Map();
|
|
50
|
+
function jwksFor(opts, issuer) {
|
|
51
|
+
if (opts.jwks)
|
|
52
|
+
return opts.jwks;
|
|
53
|
+
const uri = `${issuer}/.well-known/jwks.json`;
|
|
54
|
+
if (opts.fetch)
|
|
55
|
+
return createJwks({ jwksUri: uri, fetch: opts.fetch });
|
|
56
|
+
let c = jwksClients.get(uri);
|
|
57
|
+
if (!c)
|
|
58
|
+
jwksClients.set(uri, (c = createJwks({ jwksUri: uri })));
|
|
59
|
+
return c;
|
|
60
|
+
}
|
|
61
|
+
const guards = new Map();
|
|
62
|
+
function defaultGuard(clientId) {
|
|
63
|
+
let g = guards.get(clientId);
|
|
64
|
+
if (!g)
|
|
65
|
+
guards.set(clientId, (g = memoryReplayGuard()));
|
|
66
|
+
return g;
|
|
67
|
+
}
|
|
68
|
+
/** Signature, issuer, audience and times: everything both token kinds share. */
|
|
69
|
+
async function verifyCommon(token, opts, kind) {
|
|
70
|
+
if (!opts?.clientId)
|
|
71
|
+
throw new TypeError(`verify${kind === 'launch' ? 'LaunchToken' : 'IdToken'}: clientId is required.`);
|
|
72
|
+
const decoded = decodeJwt(token);
|
|
73
|
+
const { header, payload } = decoded;
|
|
74
|
+
if (!JWT_ALGORITHMS.includes(header.alg))
|
|
75
|
+
throw fail('invalid_token', `This token is signed with "${String(header.alg).slice(0, 20)}"; usebecky signs with ES256 only.`);
|
|
76
|
+
const typ = typeof header.typ === 'string' ? header.typ : undefined;
|
|
77
|
+
if (kind === 'launch' && typ !== LAUNCH_TOKEN_TYPE)
|
|
78
|
+
throw fail('wrong_token_type', 'This is not a launch token (an id_token cannot open your service).');
|
|
79
|
+
if (kind === 'id_token' && typ === LAUNCH_TOKEN_TYPE)
|
|
80
|
+
throw fail('wrong_token_type', 'This is a launch token, not an id_token.');
|
|
81
|
+
if (typeof header.kid !== 'string' || !header.kid)
|
|
82
|
+
throw fail('unknown_key', 'This token names no signing key (kid).');
|
|
83
|
+
const issuer = trimSlash(opts.issuer ?? opts.apiUrl ?? DEFAULT_API_URL);
|
|
84
|
+
const jwk = await jwksFor(opts, issuer).getKey(header.kid);
|
|
85
|
+
if (!jwk)
|
|
86
|
+
throw fail('unknown_key', 'usebecky publishes no key with this token\'s id: it was not signed by usebecky, or the key was withdrawn.', `Check USEBECKY_API_URL (${issuer}).`);
|
|
87
|
+
if (!(await verifySignature(decoded, jwk)))
|
|
88
|
+
throw fail('invalid_signature', 'The token\'s signature does not match: it was changed or not made by usebecky.');
|
|
89
|
+
const now = typeof opts.now === 'function' ? opts.now() : (opts.now ?? Math.floor(Date.now() / 1000));
|
|
90
|
+
const skew = opts.clockSkewSeconds ?? DEFAULT_CLOCK_SKEW_SECONDS;
|
|
91
|
+
if (payload.iss !== issuer)
|
|
92
|
+
throw fail('invalid_issuer', `The token was issued by "${String(payload.iss).slice(0, 80)}", not by ${issuer}.`, 'Check USEBECKY_API_URL: the dev server, a local usebecky and the hosted one each sign their own tokens.');
|
|
93
|
+
const aud = payload.aud;
|
|
94
|
+
if (!(aud === opts.clientId || (Array.isArray(aud) && aud.length === 1 && aud[0] === opts.clientId)))
|
|
95
|
+
throw fail('invalid_audience', 'The token was issued to another extension.', 'Check USEBECKY_CLIENT_ID.');
|
|
96
|
+
if (typeof payload.exp !== 'number' || typeof payload.iat !== 'number')
|
|
97
|
+
throw fail('invalid_token', 'The token has no exp or iat.');
|
|
98
|
+
if (payload.exp + skew <= now)
|
|
99
|
+
throw fail('expired_token', kind === 'launch' ? 'This sign-in link has expired (they work for 60 seconds).' : 'The id_token has expired.', kind === 'launch' ? 'Open your service from usebecky again.' : undefined);
|
|
100
|
+
if (payload.iat - skew > now || (typeof payload.nbf === 'number' && payload.nbf - skew > now))
|
|
101
|
+
throw fail('token_not_yet_valid', 'The token is not valid yet. Check your server\'s clock.');
|
|
102
|
+
if (typeof payload.sub !== 'string' || !payload.sub)
|
|
103
|
+
throw fail('invalid_token', 'The token names nobody (no sub).');
|
|
104
|
+
if (typeof payload.usebecky_project !== 'string' || typeof payload.usebecky_install !== 'string')
|
|
105
|
+
throw fail('invalid_token', 'The token names no project or install.');
|
|
106
|
+
return { decoded, claims: payload, now, skew };
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Verify an id_token from usebecky's token response (handleCallback() does it for you and returns `identity`): ES256
|
|
110
|
+
* signature against usebecky's JWKS, issuer, audience = your client id, expiry with clock skew, and the nonce when you
|
|
111
|
+
* pass one. Throws TokenVerificationError.
|
|
112
|
+
*/
|
|
113
|
+
export async function verifyIdToken(token, options) {
|
|
114
|
+
const { claims } = await verifyCommon(token, options, 'id_token');
|
|
115
|
+
if (options.nonce !== undefined && claims.nonce !== options.nonce)
|
|
116
|
+
throw fail('invalid_nonce', 'The id_token\'s nonce does not match the one this sign-in started with.', 'Start the install again.');
|
|
117
|
+
return claims;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Verify the launch token of "Open in <your service>" (the `launch` query parameter on your sso_url): ES256 signature,
|
|
121
|
+
* issuer, audience, at most 60 seconds old, and single use (the replay guard remembers its jti). Throws
|
|
122
|
+
* TokenVerificationError; send the person back to usebecky to open your service again.
|
|
123
|
+
*/
|
|
124
|
+
export async function verifyLaunchToken(token, options) {
|
|
125
|
+
const { claims, now, skew } = await verifyCommon(token, options, 'launch');
|
|
126
|
+
if (typeof claims.jti !== 'string' || !claims.jti)
|
|
127
|
+
throw fail('invalid_token', 'This launch token has no id (jti).');
|
|
128
|
+
if (claims.exp - claims.iat > LAUNCH_TOKEN_TTL_SECONDS || now - claims.iat > LAUNCH_TOKEN_TTL_SECONDS + skew)
|
|
129
|
+
throw fail('expired_token', 'This sign-in link has expired (they work for 60 seconds).', 'Open your service from usebecky again.');
|
|
130
|
+
const guard = options.replayGuard ?? defaultGuard(options.clientId);
|
|
131
|
+
if (!(await guard.use(claims.jti, claims.exp + skew)))
|
|
132
|
+
throw fail('replayed_token', 'This sign-in link was already used.', 'Open your service from usebecky again: every link works once.');
|
|
133
|
+
return claims;
|
|
134
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export { createExtension, DEFAULT_API_URL, DEFAULT_DASHBOARD_URL, PARTNER_API_PATH, AUTHORIZE_PATH, STATE_TTL_SECONDS, STATE_COOKIE, MAX_WEBHOOK_BYTES, type Extension, type ExtensionOptions, type AuthorizeOptions, type CallbackInput, type CallbackResult, type PartnerApi, type WebhookHandlers, type WebhookHandlerOptions, type OAuthHandlerOptions, type ExtensionUiContext, type ExtensionUiActionContext, } from './extension.ts';
|
|
2
|
+
export { memoryTokenStore, memoryStateStore, sqlTokenStore, tokenTableSql, sqlReplayGuard, replayTableSql, type TokenStore, type StateStore, type StoredTokens, type PendingAuthorization, type SqlQuery, type SqlTokenStoreOptions, type SqlReplayGuardOptions, type Awaitable, } from './stores.ts';
|
|
3
|
+
export { verifyWebhook, signWebhook, parseSignatureHeader, signatureHeaderFrom, SIGNATURE_HEADER, DEFAULT_TOLERANCE_SECONDS, type HeaderSource, type VerifyOptions } from './webhooks.ts';
|
|
4
|
+
export { createCodeVerifier, codeChallengeFor, createPkcePair } from './pkce.ts';
|
|
5
|
+
export { toNodeHandler, toFetchRequest, writeFetchResponse, type FetchHandler, type NodeHandler, type NodeRequestLike, type NodeResponseLike } from './handlers.ts';
|
|
6
|
+
export { ExtensionError, OAuthCallbackError, TokenError, InstallationRevokedError, PartnerApiError, WebhookVerificationError, ConfigError, TokenVerificationError, ProvisionRequestError, type ExtensionErrorInit, type PartnerApiErrorCode } from './errors.ts';
|
|
7
|
+
export { verifyIdToken, verifyLaunchToken, memoryReplayGuard, LAUNCH_TOKEN_TYPE, LAUNCH_PARAM, OIDC_SCOPES, ID_TOKEN_TTL_SECONDS, LAUNCH_TOKEN_TTL_SECONDS, DEFAULT_CLOCK_SKEW_SECONDS, type UsebeckyIdentity, type UsebeckyRole, type IdTokenClaims, type LaunchClaims, type ReplayGuard, type TokenVerifyOptions, type IdTokenVerifyOptions, type LaunchVerifyOptions, } from './identity.ts';
|
|
8
|
+
export { provisionHandler, ssoHandler, verifyProvisionRequest, memoryIdempotencyStore, PROVISION_EVENT_TYPE, MAX_PROVISION_BYTES, type ProvisionRequest, type ProvisionResult, type IdempotencyStore, type ProvisionHandlerOptions, type SsoHandlerOptions, } from './accounts.ts';
|
|
9
|
+
export { createJwks, decodeJwt, signEs256, generateEs256Key, type JwksClient, type JwksOptions, type PublicJwk, type DecodedJwt } from './jwt.ts';
|
|
10
|
+
export { USEBECKY_EVENT_TYPES, SUBSCRIBABLE_EVENT_TYPES, EXTENSION_EVENT_TYPES, ALL_EVENT_TYPES, isKnownEventType, type UsebeckyEventType, type ExtensionLifecycleEventType, type ExtensionEventType, type ExtensionEvent, type ExtensionEventData, type ExtensionEventDataMap, type ExtensionInstalledData, type ExtensionUninstalledData, type ExtensionPlanChangedData, type UninstallReason, type AnyExtensionEvent, } from './events.ts';
|
|
11
|
+
export { validateManifest, parseManifestJson, MANIFEST_FILE, MAX_LOGO_BYTES, type ManifestIssue, type ManifestResult, type ValidateOptions } from './manifest.ts';
|
|
12
|
+
export { EXTENSION_SCOPES, EXTENSION_SCOPE_INFO, EXTENSION_CATEGORIES, EXTENSION_FIELD_TYPES, LISTING_LIMITS, RESERVED_SLUGS, TOKEN_PREFIXES, ACCESS_TOKEN_TTL_SECONDS, REFRESH_TOKEN_TTL_DAYS, AUTHORIZATION_CODE_TTL_SECONDS, PARTNER_RATE_LIMIT_PER_MINUTE, type ExtensionScope, type ExtensionCategory, type ExtensionCapability, EXTENSION_CAPABILITIES, type ExtensionFieldType, type ExtensionField, type ExtensionSettingValue, type ExtensionSettings, type ExtensionPricing, type ExtensionPricingPlan, type ExtensionConnect, type ExtensionAccount, type ExtensionUi, type ExtensionUiPage, type ExtensionListing, type ExtensionManifest, type Installation, type InstallationSettings, type TaggingSettings, type Project, type AnalyticsSummary, type TokenResponse, } from './types.ts';
|
|
13
|
+
export { UI_LIMITS, UI_SECTIONS, UI_EVENT_TYPE, SETTINGS_PAGE, PLAN_ID, checkView, checkRenderAnswer, checkActionAnswer, inlineTokens, type View, type Block, type BlockType, type Button, type ActionButton, type PageButton, type LinkButton, type PlanButton, type Plan, type PlanStatus, type NextPlan, type PlanDiscount, type Stat, type Series, type ValueFormat, type Column, type Cell, type Row, type Filter, type Field, type FieldValue, type Tone, type UiParams, type UiSection, type ActionResult, type UiRequest, type UiRenderRequest, type UiActionRequest, type UiProblem, type UiCheck, type Inline, } from './ui/schema.ts';
|
|
14
|
+
export { uiHandler, verifyUiRequest, MAX_UI_REQUEST_BYTES, type UiContext, type UiActionContext, type PageHandler, type ActionHandler, type UiHandlerOptions } from './ui/handler.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// @usebecky/extension: build extensions for the usebecky store.
|
|
2
|
+
// Works on Node 20+, Bun, Deno and edge runtimes (Web Crypto + fetch). Node-only helpers live in
|
|
3
|
+
// '@usebecky/extension/node', the local dev server in '@usebecky/extension/dev'.
|
|
4
|
+
export { createExtension, DEFAULT_API_URL, DEFAULT_DASHBOARD_URL, PARTNER_API_PATH, AUTHORIZE_PATH, STATE_TTL_SECONDS, STATE_COOKIE, MAX_WEBHOOK_BYTES, } from "./extension.js";
|
|
5
|
+
export { memoryTokenStore, memoryStateStore, sqlTokenStore, tokenTableSql, sqlReplayGuard, replayTableSql, } from "./stores.js";
|
|
6
|
+
export { verifyWebhook, signWebhook, parseSignatureHeader, signatureHeaderFrom, SIGNATURE_HEADER, DEFAULT_TOLERANCE_SECONDS } from "./webhooks.js";
|
|
7
|
+
export { createCodeVerifier, codeChallengeFor, createPkcePair } from "./pkce.js";
|
|
8
|
+
export { toNodeHandler, toFetchRequest, writeFetchResponse } from "./handlers.js";
|
|
9
|
+
export { ExtensionError, OAuthCallbackError, TokenError, InstallationRevokedError, PartnerApiError, WebhookVerificationError, ConfigError, TokenVerificationError, ProvisionRequestError } from "./errors.js";
|
|
10
|
+
export { verifyIdToken, verifyLaunchToken, memoryReplayGuard, LAUNCH_TOKEN_TYPE, LAUNCH_PARAM, OIDC_SCOPES, ID_TOKEN_TTL_SECONDS, LAUNCH_TOKEN_TTL_SECONDS, DEFAULT_CLOCK_SKEW_SECONDS, } from "./identity.js";
|
|
11
|
+
export { provisionHandler, ssoHandler, verifyProvisionRequest, memoryIdempotencyStore, PROVISION_EVENT_TYPE, MAX_PROVISION_BYTES, } from "./accounts.js";
|
|
12
|
+
export { createJwks, decodeJwt, signEs256, generateEs256Key } from "./jwt.js";
|
|
13
|
+
export { USEBECKY_EVENT_TYPES, SUBSCRIBABLE_EVENT_TYPES, EXTENSION_EVENT_TYPES, ALL_EVENT_TYPES, isKnownEventType, } from "./events.js";
|
|
14
|
+
export { validateManifest, parseManifestJson, MANIFEST_FILE, MAX_LOGO_BYTES } from "./manifest.js";
|
|
15
|
+
export { EXTENSION_SCOPES, EXTENSION_SCOPE_INFO, EXTENSION_CATEGORIES, EXTENSION_FIELD_TYPES, LISTING_LIMITS, RESERVED_SLUGS, TOKEN_PREFIXES, ACCESS_TOKEN_TTL_SECONDS, REFRESH_TOKEN_TTL_DAYS, AUTHORIZATION_CODE_TTL_SECONDS, PARTNER_RATE_LIMIT_PER_MINUTE, EXTENSION_CAPABILITIES, } from "./types.js";
|
|
16
|
+
export { UI_LIMITS, UI_SECTIONS, UI_EVENT_TYPE, SETTINGS_PAGE, PLAN_ID, checkView, checkRenderAnswer, checkActionAnswer, inlineTokens, } from "./ui/schema.js";
|
|
17
|
+
export { uiHandler, verifyUiRequest, MAX_UI_REQUEST_BYTES } from "./ui/handler.js";
|
package/dist/jwt.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** The one algorithm usebecky signs with. "none", HS256 and everything else are refused. */
|
|
2
|
+
export declare const JWT_ALGORITHMS: readonly ["ES256"];
|
|
3
|
+
/** base64url (with or without padding) to bytes; null when it isn't base64url. */
|
|
4
|
+
export declare function fromBase64url(s: string): Uint8Array | null;
|
|
5
|
+
export interface DecodedJwt {
|
|
6
|
+
header: {
|
|
7
|
+
alg?: unknown;
|
|
8
|
+
kid?: unknown;
|
|
9
|
+
typ?: unknown;
|
|
10
|
+
[k: string]: unknown;
|
|
11
|
+
};
|
|
12
|
+
payload: Record<string, unknown>;
|
|
13
|
+
/** `<header>.<payload>`: what the signature covers. */
|
|
14
|
+
signingInput: string;
|
|
15
|
+
signature: Uint8Array;
|
|
16
|
+
}
|
|
17
|
+
/** Split and decode a compact JWT without checking anything. Throws invalid_token when it isn't one. */
|
|
18
|
+
export declare function decodeJwt(token: unknown): DecodedJwt;
|
|
19
|
+
/** A public key from usebecky's JWKS. */
|
|
20
|
+
export interface PublicJwk {
|
|
21
|
+
kty: string;
|
|
22
|
+
kid?: string;
|
|
23
|
+
alg?: string;
|
|
24
|
+
use?: string;
|
|
25
|
+
crv?: string;
|
|
26
|
+
x?: string;
|
|
27
|
+
y?: string;
|
|
28
|
+
[k: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
/** Check the ES256 signature of a decoded token with a JWK. */
|
|
31
|
+
export declare function verifySignature(decoded: DecodedJwt, jwk: PublicJwk): Promise<boolean>;
|
|
32
|
+
/** Sign claims with an ES256 private key (the dev server and your tests; usebecky signs its own tokens). */
|
|
33
|
+
export declare function signEs256(privateKey: CryptoKey, header: Record<string, unknown>, claims: Record<string, unknown>): Promise<string>;
|
|
34
|
+
/** A new ES256 key pair with its public JWK (kid included), for the dev server and tests. */
|
|
35
|
+
export declare function generateEs256Key(kid?: string): Promise<{
|
|
36
|
+
privateKey: CryptoKey;
|
|
37
|
+
publicJwk: PublicJwk;
|
|
38
|
+
}>;
|
|
39
|
+
/** Fetches usebecky's public keys and keeps them, refetching for a key id it hasn't seen (key rotation). */
|
|
40
|
+
export interface JwksClient {
|
|
41
|
+
readonly uri: string;
|
|
42
|
+
/** The key with this id, or null when usebecky doesn't publish one (after a refetch). */
|
|
43
|
+
getKey(kid: string): Promise<PublicJwk | null>;
|
|
44
|
+
/** Fetch now (the next getKey uses the new set). */
|
|
45
|
+
refresh(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
export interface JwksOptions {
|
|
48
|
+
/** `https://api.usebecky.com/.well-known/jwks.json`. Or `apiUrl`. */
|
|
49
|
+
jwksUri?: string;
|
|
50
|
+
/** usebecky's API address: the JWKS is `<apiUrl>/.well-known/jwks.json`. */
|
|
51
|
+
apiUrl?: string;
|
|
52
|
+
fetch?: typeof fetch;
|
|
53
|
+
/** Keep the keys this long (default 600 seconds). */
|
|
54
|
+
cacheSeconds?: number;
|
|
55
|
+
/** An unknown key id refetches at most this often (default 30 seconds), so junk tokens can't flood usebecky. */
|
|
56
|
+
minRefetchSeconds?: number;
|
|
57
|
+
/** ms since 1970 (tests). */
|
|
58
|
+
now?: () => number;
|
|
59
|
+
}
|
|
60
|
+
export declare function createJwks(options: JwksOptions): JwksClient;
|
|
61
|
+
/** One cached JWKS client per address and fetch function (so every verify call shares the cache). */
|
|
62
|
+
export declare function sharedJwks(uri: string, doFetch?: typeof fetch): JwksClient;
|
package/dist/jwt.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// JSON Web Tokens the way usebecky signs them: ES256 (ECDSA P-256 with SHA-256), compact form, keys from a JWKS.
|
|
2
|
+
// On Web Crypto only, so it runs on Node 20+, Bun, Deno and edge runtimes. Nothing hand-rolled: the signature is checked
|
|
3
|
+
// by crypto.subtle.verify; this file only splits, decodes and compares.
|
|
4
|
+
import { base64url } from "./crypto.js";
|
|
5
|
+
import { TokenVerificationError } from "./errors.js";
|
|
6
|
+
/** The one algorithm usebecky signs with. "none", HS256 and everything else are refused. */
|
|
7
|
+
export const JWT_ALGORITHMS = ['ES256'];
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
function subtle() {
|
|
10
|
+
const c = globalThis.crypto;
|
|
11
|
+
if (!c?.subtle)
|
|
12
|
+
throw new Error('Web Crypto is not available. Use Node.js 20 or newer.');
|
|
13
|
+
return c.subtle;
|
|
14
|
+
}
|
|
15
|
+
/** base64url (with or without padding) to bytes; null when it isn't base64url. */
|
|
16
|
+
export function fromBase64url(s) {
|
|
17
|
+
if (!/^[A-Za-z0-9_-]*={0,2}$/.test(s))
|
|
18
|
+
return null;
|
|
19
|
+
try {
|
|
20
|
+
const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '') + '='.repeat((4 - (s.replace(/=+$/, '').length % 4)) % 4));
|
|
21
|
+
const out = new Uint8Array(bin.length);
|
|
22
|
+
for (let i = 0; i < bin.length; i++)
|
|
23
|
+
out[i] = bin.charCodeAt(i);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const fail = (code, message, hint) => new TokenVerificationError({ code, message, hint, status: 401 });
|
|
31
|
+
/** Split and decode a compact JWT without checking anything. Throws invalid_token when it isn't one. */
|
|
32
|
+
export function decodeJwt(token) {
|
|
33
|
+
if (typeof token !== 'string' || token.length > 16_384)
|
|
34
|
+
throw fail('invalid_token', 'This is not a usebecky token.');
|
|
35
|
+
const parts = token.split('.');
|
|
36
|
+
if (parts.length !== 3 || parts.some((p) => !p))
|
|
37
|
+
throw fail('invalid_token', 'This is not a usebecky token (a JWT has three parts).');
|
|
38
|
+
const json = (part) => {
|
|
39
|
+
const bytes = fromBase64url(part);
|
|
40
|
+
if (!bytes)
|
|
41
|
+
return null;
|
|
42
|
+
try {
|
|
43
|
+
const v = JSON.parse(new TextDecoder().decode(bytes));
|
|
44
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const header = json(parts[0]);
|
|
51
|
+
const payload = json(parts[1]);
|
|
52
|
+
const signature = fromBase64url(parts[2]);
|
|
53
|
+
if (!header || !payload || !signature)
|
|
54
|
+
throw fail('invalid_token', 'This token is damaged: its parts are not valid base64url JSON.');
|
|
55
|
+
return { header, payload, signingInput: `${parts[0]}.${parts[1]}`, signature };
|
|
56
|
+
}
|
|
57
|
+
async function importEs256(jwk) {
|
|
58
|
+
if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string')
|
|
59
|
+
throw fail('unknown_key', 'usebecky published a key this kit cannot use.', 'Update @usebecky/extension.');
|
|
60
|
+
return subtle().importKey('jwk', { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ext: true }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
|
|
61
|
+
}
|
|
62
|
+
/** Check the ES256 signature of a decoded token with a JWK. */
|
|
63
|
+
export async function verifySignature(decoded, jwk) {
|
|
64
|
+
if (decoded.signature.length !== 64)
|
|
65
|
+
return false;
|
|
66
|
+
const key = await importEs256(jwk);
|
|
67
|
+
return subtle().verify({ name: 'ECDSA', hash: 'SHA-256' }, key, decoded.signature, encoder.encode(decoded.signingInput));
|
|
68
|
+
}
|
|
69
|
+
/** Sign claims with an ES256 private key (the dev server and your tests; usebecky signs its own tokens). */
|
|
70
|
+
export async function signEs256(privateKey, header, claims) {
|
|
71
|
+
const enc = (v) => base64url(encoder.encode(JSON.stringify(v)));
|
|
72
|
+
const input = `${enc({ ...header, alg: 'ES256' })}.${enc(claims)}`;
|
|
73
|
+
const sig = await subtle().sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, encoder.encode(input));
|
|
74
|
+
return `${input}.${base64url(new Uint8Array(sig))}`;
|
|
75
|
+
}
|
|
76
|
+
/** A new ES256 key pair with its public JWK (kid included), for the dev server and tests. */
|
|
77
|
+
export async function generateEs256Key(kid) {
|
|
78
|
+
const pair = (await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']));
|
|
79
|
+
const jwk = (await subtle().exportKey('jwk', pair.publicKey));
|
|
80
|
+
const id = kid ?? base64url(new Uint8Array(await subtle().digest('SHA-256', encoder.encode(`{"crv":"P-256","kty":"EC","x":"${jwk.x}","y":"${jwk.y}"}`))));
|
|
81
|
+
return { privateKey: pair.privateKey, publicJwk: { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, kid: id, alg: 'ES256', use: 'sig' } };
|
|
82
|
+
}
|
|
83
|
+
export function createJwks(options) {
|
|
84
|
+
const uri = options.jwksUri ?? `${(options.apiUrl ?? '').replace(/\/+$/, '')}/.well-known/jwks.json`;
|
|
85
|
+
if (!/^https?:\/\//.test(uri))
|
|
86
|
+
throw new TypeError('createJwks: pass jwksUri or apiUrl.');
|
|
87
|
+
const doFetch = options.fetch ?? ((...a) => fetch(...a));
|
|
88
|
+
const now = options.now ?? Date.now;
|
|
89
|
+
const cacheMs = (options.cacheSeconds ?? 600) * 1000;
|
|
90
|
+
const minRefetchMs = (options.minRefetchSeconds ?? 30) * 1000;
|
|
91
|
+
let keys = new Map();
|
|
92
|
+
let fetchedAt = -Infinity;
|
|
93
|
+
let attemptedAt = -Infinity;
|
|
94
|
+
let running = null;
|
|
95
|
+
async function load() {
|
|
96
|
+
attemptedAt = now();
|
|
97
|
+
let res;
|
|
98
|
+
try {
|
|
99
|
+
res = await doFetch(uri, { headers: { accept: 'application/json' } });
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
throw fail('jwks_unavailable', `Could not load usebecky's signing keys from ${uri}: ${err.message}`, 'Check your internet connection and USEBECKY_API_URL. Try again in a moment.');
|
|
103
|
+
}
|
|
104
|
+
const body = (await res.json().catch(() => null));
|
|
105
|
+
if (!res.ok || !body || !Array.isArray(body.keys))
|
|
106
|
+
throw fail('jwks_unavailable', `usebecky's signing keys could not be read (HTTP ${res.status} from ${uri}).`, 'Try again in a moment.');
|
|
107
|
+
const next = new Map();
|
|
108
|
+
for (const k of body.keys)
|
|
109
|
+
if (k && typeof k === 'object' && typeof k.kid === 'string')
|
|
110
|
+
next.set(k.kid, k);
|
|
111
|
+
keys = next;
|
|
112
|
+
fetchedAt = now();
|
|
113
|
+
}
|
|
114
|
+
function refresh() {
|
|
115
|
+
running ??= load().finally(() => (running = null));
|
|
116
|
+
return running;
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
uri,
|
|
120
|
+
refresh,
|
|
121
|
+
async getKey(kid) {
|
|
122
|
+
const fresh = now() - fetchedAt < cacheMs;
|
|
123
|
+
if (fresh && keys.has(kid))
|
|
124
|
+
return keys.get(kid);
|
|
125
|
+
// Expired, or a key id we don't know (usebecky published a new key): fetch again, but not too often.
|
|
126
|
+
if (!fresh || now() - attemptedAt >= minRefetchMs) {
|
|
127
|
+
try {
|
|
128
|
+
await refresh();
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
// usebecky unreachable: a key we already had still verifies.
|
|
132
|
+
if (keys.has(kid))
|
|
133
|
+
return keys.get(kid);
|
|
134
|
+
throw err;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return keys.get(kid) ?? null;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
const shared = new Map();
|
|
142
|
+
/** One cached JWKS client per address and fetch function (so every verify call shares the cache). */
|
|
143
|
+
export function sharedJwks(uri, doFetch) {
|
|
144
|
+
if (doFetch)
|
|
145
|
+
return createJwks({ jwksUri: uri, fetch: doFetch });
|
|
146
|
+
let c = shared.get(uri);
|
|
147
|
+
if (!c) {
|
|
148
|
+
c = createJwks({ jwksUri: uri });
|
|
149
|
+
shared.set(uri, c);
|
|
150
|
+
}
|
|
151
|
+
return c;
|
|
152
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ExtensionManifest } from './types.ts';
|
|
2
|
+
export declare const MANIFEST_FILE = "usebecky-extension.json";
|
|
3
|
+
/** The logo upload's limit. */
|
|
4
|
+
export declare const MAX_LOGO_BYTES: number;
|
|
5
|
+
export interface ManifestIssue {
|
|
6
|
+
/** Where, like `connect.redirect_uris.0` ("" for the whole file): usebecky's `details.field`. */
|
|
7
|
+
path: string;
|
|
8
|
+
message: string;
|
|
9
|
+
/** What to do, when usebecky (or the kit) has a tip. */
|
|
10
|
+
hint?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ManifestResult {
|
|
13
|
+
ok: boolean;
|
|
14
|
+
/** Must be fixed: usebecky would refuse the listing (on import, or when you submit it for review). */
|
|
15
|
+
errors: ManifestIssue[];
|
|
16
|
+
/** Worth a look before you submit (placeholders, localhost addresses, the logo...). */
|
|
17
|
+
warnings: ManifestIssue[];
|
|
18
|
+
/** The manifest, typed, when there are no errors. */
|
|
19
|
+
manifest: ExtensionManifest | null;
|
|
20
|
+
}
|
|
21
|
+
export interface ValidateOptions {
|
|
22
|
+
/** Size in bytes of a file next to the manifest, or null when it doesn't exist. */
|
|
23
|
+
fileInfo?: (relativePath: string) => {
|
|
24
|
+
size: number;
|
|
25
|
+
} | null;
|
|
26
|
+
/**
|
|
27
|
+
* Check `webhook_url` like a usebecky that allows plain http and private addresses for webhooks: a local usebecky
|
|
28
|
+
* (outside production, AUTOMATION_ALLOW_PRIVATE_URLS) or the dev server. Default false: the hosted usebecky, which
|
|
29
|
+
* needs https and a public host name.
|
|
30
|
+
*/
|
|
31
|
+
allowPrivateWebhookUrl?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** Check a parsed usebecky-extension.json. */
|
|
34
|
+
export declare function validateManifest(input: unknown, options?: ValidateOptions): ManifestResult;
|
|
35
|
+
/** JSON.parse with the line and column of a syntax error, in plain words. */
|
|
36
|
+
export declare function parseManifestJson(text: string): {
|
|
37
|
+
value: unknown;
|
|
38
|
+
error: null;
|
|
39
|
+
} | {
|
|
40
|
+
value: null;
|
|
41
|
+
error: string;
|
|
42
|
+
};
|