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 +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Helpers for working with Node/Express/Fetch request and response objects.
|
|
2
|
+
export const ACCESS_TOKEN_COOKIE = 'ub-access-token';
|
|
3
|
+
const LEGACY_ACCESS_TOKEN_COOKIE = 'yb-access-token';
|
|
4
|
+
/** Express (`res.status().json()`) or plain node:http (`res.end()`). */
|
|
5
|
+
export function sendJson(res, status, body) {
|
|
6
|
+
if (!res)
|
|
7
|
+
return;
|
|
8
|
+
if (typeof res.status === 'function' && typeof res.json === 'function') {
|
|
9
|
+
res.status(status).json(body);
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
if (res.headersSent)
|
|
13
|
+
return;
|
|
14
|
+
res.statusCode = status;
|
|
15
|
+
if (typeof res.setHeader === 'function')
|
|
16
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
17
|
+
res.end(JSON.stringify(body));
|
|
18
|
+
}
|
|
19
|
+
export function parseCookies(header) {
|
|
20
|
+
const out = {};
|
|
21
|
+
if (!header)
|
|
22
|
+
return out;
|
|
23
|
+
for (const part of header.split(';')) {
|
|
24
|
+
const i = part.indexOf('=');
|
|
25
|
+
if (i < 0)
|
|
26
|
+
continue;
|
|
27
|
+
const k = part.slice(0, i).trim();
|
|
28
|
+
if (!k || k in out)
|
|
29
|
+
continue;
|
|
30
|
+
let v = part.slice(i + 1).trim();
|
|
31
|
+
if (v.startsWith('"') && v.endsWith('"'))
|
|
32
|
+
v = v.slice(1, -1);
|
|
33
|
+
try {
|
|
34
|
+
out[k] = decodeURIComponent(v);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
out[k] = v;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
function header(headers, name) {
|
|
43
|
+
if (!headers)
|
|
44
|
+
return undefined;
|
|
45
|
+
if (typeof headers.get === 'function')
|
|
46
|
+
return headers.get(name) ?? undefined;
|
|
47
|
+
const v = headers[name] ?? headers[name.toLowerCase()] ?? headers[name.charAt(0).toUpperCase() + name.slice(1)];
|
|
48
|
+
return Array.isArray(v) ? v[0] : v;
|
|
49
|
+
}
|
|
50
|
+
function bearer(value) {
|
|
51
|
+
if (!value)
|
|
52
|
+
return null;
|
|
53
|
+
const m = /^Bearer\s+(.+)$/i.exec(value.trim());
|
|
54
|
+
const token = m ? m[1].trim() : null;
|
|
55
|
+
// An API key in the Authorization header (ub_..., or yb_... from before the rename) is not a user token.
|
|
56
|
+
return token && !/^[uy]b_/.test(token) ? token : null;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Find the user's access token in: a raw token string, an Express/Node request, a Fetch
|
|
60
|
+
* Request / NextRequest, or Next.js `cookies()` / `headers()`.
|
|
61
|
+
* Order: `Authorization: Bearer <token>` header, then the `ub-access-token` cookie.
|
|
62
|
+
*/
|
|
63
|
+
export function extractToken(input) {
|
|
64
|
+
if (!input)
|
|
65
|
+
return null;
|
|
66
|
+
if (typeof input === 'string') {
|
|
67
|
+
const t = input.trim();
|
|
68
|
+
if (!t)
|
|
69
|
+
return null;
|
|
70
|
+
return /^Bearer\s+/i.test(t) ? bearer(t) : t;
|
|
71
|
+
}
|
|
72
|
+
if (typeof input !== 'object')
|
|
73
|
+
return null;
|
|
74
|
+
const obj = input;
|
|
75
|
+
const fromHeader = (cookieHeader) => (typeof cookieHeader === 'string' ? firstCookie((name) => parseCookies(cookieHeader)[name]) : null);
|
|
76
|
+
if (obj.headers) {
|
|
77
|
+
const fromAuth = bearer(header(obj.headers, 'authorization'));
|
|
78
|
+
if (fromAuth)
|
|
79
|
+
return fromAuth;
|
|
80
|
+
if (obj.cookies && typeof obj.cookies === 'object') {
|
|
81
|
+
const v = typeof obj.cookies.get === 'function'
|
|
82
|
+
? firstCookie((name) => {
|
|
83
|
+
const c = obj.cookies.get(name);
|
|
84
|
+
return typeof c === 'string' ? c : c?.value;
|
|
85
|
+
})
|
|
86
|
+
: firstCookie((name) => (typeof obj.cookies[name] === 'string' ? obj.cookies[name] : null));
|
|
87
|
+
if (v)
|
|
88
|
+
return v;
|
|
89
|
+
}
|
|
90
|
+
return fromHeader(header(obj.headers, 'cookie'));
|
|
91
|
+
}
|
|
92
|
+
// Next.js cookies() (has get(name) → { value }) or headers() (get(name) → string)
|
|
93
|
+
if (typeof obj.get === 'function') {
|
|
94
|
+
try {
|
|
95
|
+
const auth = obj.get('authorization');
|
|
96
|
+
if (typeof auth === 'string')
|
|
97
|
+
return bearer(auth) ?? fromHeader(obj.get('cookie'));
|
|
98
|
+
const v = firstCookie((name) => {
|
|
99
|
+
const c = obj.get(name);
|
|
100
|
+
return typeof c === 'string' ? c : c?.value;
|
|
101
|
+
});
|
|
102
|
+
if (v)
|
|
103
|
+
return v;
|
|
104
|
+
return fromHeader(obj.get('cookie'));
|
|
105
|
+
}
|
|
106
|
+
catch { }
|
|
107
|
+
}
|
|
108
|
+
if (typeof obj.access_token === 'string')
|
|
109
|
+
return obj.access_token;
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
/** The access token cookie's value: ub-access-token, else yb-access-token (set before the rename to usebecky). */
|
|
113
|
+
function firstCookie(read) {
|
|
114
|
+
return read(ACCESS_TOKEN_COOKIE) || read(LEGACY_ACCESS_TOKEN_COOKIE) || null;
|
|
115
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { Database } from '../db/query.ts';
|
|
2
|
+
import { HttpClient, type FetchLike } from '../lib/http.ts';
|
|
3
|
+
import type { Result, Session, User } from '../lib/types.ts';
|
|
4
|
+
import { PaymentsClient } from '../payments/client.ts';
|
|
5
|
+
import { type ServerNewsletter } from '../newsletter/client.ts';
|
|
6
|
+
import { StorageClient } from '../storage/client.ts';
|
|
7
|
+
import { FunctionsClient } from '../functions/client.ts';
|
|
8
|
+
import { type ServerCache } from './cache.ts';
|
|
9
|
+
import { type ServerEmails } from './emails.ts';
|
|
10
|
+
import { type ServerPush } from './push.ts';
|
|
11
|
+
import { type ServerPayments } from './payments.ts';
|
|
12
|
+
import { type ServerAnalytics } from './analytics.ts';
|
|
13
|
+
import { type ServerUsage } from './usage.ts';
|
|
14
|
+
import { Events } from './events.ts';
|
|
15
|
+
export type { ServerEmails, SendEmailOptions, SentEmail, EmailAttachment, EmailTag, EmailStatus, EmailEvent, EmailDetails, BatchEmailResult } from './emails.ts';
|
|
16
|
+
export type { ServerPush, PushSendOptions, PushMessage, PushPlatformStats } from './push.ts';
|
|
17
|
+
export type { ServerCache, CacheSetOptions, RateLimitResult, LimitOptions, Duration } from './cache.ts';
|
|
18
|
+
export type { FunctionContext, FunctionHandler, FunctionTrigger, FunctionUser } from './functions.ts';
|
|
19
|
+
export { FunctionsClient, type InvokeOptions } from '../functions/client.ts';
|
|
20
|
+
export type { ServerUsage, ProjectUsage, UsageQuota } from './usage.ts';
|
|
21
|
+
export type { ServerAnalytics, AnalyticsPeriod, AnalyticsFilters, AnalyticsMetric, AnalyticsPeriodView, AnalyticsOverview, AnalyticsDimension, AnalyticsRow, AnalyticsReport, AnalyticsReportOptions, AnalyticsTimeseries, AnalyticsTimeseriesOptions } from './analytics.ts';
|
|
22
|
+
export type { ServerPayments, ServerSubscription, Gift, GiftDetails, GiftOptions, ServerOrder, OrderUpdate } from './payments.ts';
|
|
23
|
+
export type { ServerNewsletter, NewsletterAddOptions, NewsletterListOptions, NewsletterSubscriber, NewsletterSubscriberStatus } from '../newsletter/client.ts';
|
|
24
|
+
export { Events, verifyEvent, signEvent, SIGNATURE_HEADER, type UseBeckyEvent, type EventType, type EventHandler, type EventDataMap, type SubscriptionGiftEventData, type EmailFailedData, type EmailEventData, type OrderEventData, type DisputeInfo, type PaymentDisputedData, type PaymentDisputeClosedData, type PaymentFraudWarningData } from './events.ts';
|
|
25
|
+
export { extractToken, parseCookies, ACCESS_TOKEN_COOKIE } from './http-utils.ts';
|
|
26
|
+
export { UseBeckyError, isUseBeckyError } from '../lib/errors.ts';
|
|
27
|
+
export { HOSTED_API_URL } from '../lib/hosted.ts';
|
|
28
|
+
export type { Result, User, Session, Product, Price, Subscription, SubscriptionSource, AccessSource, AccessInfo, Purchase, BillingInfo, Bucket, FileObject } from '../lib/types.ts';
|
|
29
|
+
export type { QueryResult } from '../db/query.ts';
|
|
30
|
+
declare global {
|
|
31
|
+
namespace Express {
|
|
32
|
+
interface User extends UseBeckyUser {
|
|
33
|
+
}
|
|
34
|
+
interface Request {
|
|
35
|
+
user?: User | undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
type UseBeckyUser = User;
|
|
40
|
+
export interface ServerClientOptions {
|
|
41
|
+
/** API address. Default: env USEBECKY_URL, else the hosted API (HOSTED_API_URL). Only set it to use a different API. */
|
|
42
|
+
url?: string;
|
|
43
|
+
/** Secret key (ub_sk_...). Default: env USEBECKY_SECRET_KEY. Never send it to a browser. */
|
|
44
|
+
secretKey?: string;
|
|
45
|
+
/** Publishable key, used by `as(req)` for requests without a signed-in user. Default: env USEBECKY_PUBLISHABLE_KEY. */
|
|
46
|
+
publishableKey?: string;
|
|
47
|
+
/** Signing secret for events (whsec_...). Default: env USEBECKY_WEBHOOK_SECRET. */
|
|
48
|
+
webhookSecret?: string;
|
|
49
|
+
/** How long verified users are cached, in ms. Default 30000. */
|
|
50
|
+
userCacheTtlMs?: number;
|
|
51
|
+
/** Custom fetch implementation. */
|
|
52
|
+
fetch?: FetchLike;
|
|
53
|
+
}
|
|
54
|
+
/** Anything we can find a user's access token in. */
|
|
55
|
+
export type RequestLike = string | {
|
|
56
|
+
headers: any;
|
|
57
|
+
[key: string]: any;
|
|
58
|
+
} | {
|
|
59
|
+
get(name: string): any;
|
|
60
|
+
} | null | undefined;
|
|
61
|
+
type Middleware = (req: any, res: any, next: (err?: unknown) => void) => void;
|
|
62
|
+
/** Database + storage bound to one role. */
|
|
63
|
+
export declare class ScopedClient<DB = any> extends Database<DB> {
|
|
64
|
+
/** Files, with the same permissions as `from()`. */
|
|
65
|
+
readonly storage: StorageClient;
|
|
66
|
+
/** Your Functions, called with the same identity: `functions.invoke('name', { body })`. */
|
|
67
|
+
readonly functions: FunctionsClient;
|
|
68
|
+
constructor(http: HttpClient, publicKey: string | null);
|
|
69
|
+
}
|
|
70
|
+
/** Acting as a specific user (RLS applies). */
|
|
71
|
+
export declare class UserScopedClient<DB = any> extends ScopedClient<DB> {
|
|
72
|
+
/** Payments as this user (checkout/portal return URLs instead of redirecting). */
|
|
73
|
+
readonly payments: PaymentsClient;
|
|
74
|
+
constructor(http: HttpClient, publicKey: string | null, hasUser: boolean);
|
|
75
|
+
}
|
|
76
|
+
export interface AdminUsersApi {
|
|
77
|
+
/** List users, newest first. `q` searches by email. */
|
|
78
|
+
listUsers(options?: {
|
|
79
|
+
page?: number;
|
|
80
|
+
perPage?: number;
|
|
81
|
+
q?: string;
|
|
82
|
+
}): Promise<Result<{
|
|
83
|
+
users: User[];
|
|
84
|
+
total: number;
|
|
85
|
+
page: number;
|
|
86
|
+
perPage: number;
|
|
87
|
+
}>>;
|
|
88
|
+
/** Create a user. Pass `emailConfirm: true` to skip the confirmation email. */
|
|
89
|
+
createUser(attrs: {
|
|
90
|
+
email: string;
|
|
91
|
+
password?: string;
|
|
92
|
+
emailConfirm?: boolean;
|
|
93
|
+
userMetadata?: Record<string, unknown>;
|
|
94
|
+
appMetadata?: Record<string, unknown>;
|
|
95
|
+
}): Promise<Result<User>>;
|
|
96
|
+
getUserById(id: string): Promise<Result<User>>;
|
|
97
|
+
/** Update a user. `ban: '24h' | 'forever' | 'none'` (or any `<n>h`). */
|
|
98
|
+
updateUser(id: string, attrs: {
|
|
99
|
+
email?: string;
|
|
100
|
+
password?: string;
|
|
101
|
+
emailConfirm?: boolean;
|
|
102
|
+
ban?: 'none' | '24h' | 'forever' | `${number}h`;
|
|
103
|
+
appMetadata?: Record<string, unknown>;
|
|
104
|
+
userMetadata?: Record<string, unknown>;
|
|
105
|
+
}): Promise<Result<User>>;
|
|
106
|
+
deleteUser(id: string): Promise<Result<{
|
|
107
|
+
id: string;
|
|
108
|
+
}>>;
|
|
109
|
+
/**
|
|
110
|
+
* Email an invitation to sign up. `locale`: the invitation's language, like `'de'` (default: `data.locale`
|
|
111
|
+
* if you pass one, else your project's default language).
|
|
112
|
+
*/
|
|
113
|
+
inviteUser(email: string, options?: {
|
|
114
|
+
redirectTo?: string;
|
|
115
|
+
data?: Record<string, unknown>;
|
|
116
|
+
locale?: string;
|
|
117
|
+
}): Promise<Result<User>>;
|
|
118
|
+
/** Sign a user out of every device. */
|
|
119
|
+
signOutUser(id: string): Promise<Result<{
|
|
120
|
+
ok: boolean;
|
|
121
|
+
}>>;
|
|
122
|
+
/**
|
|
123
|
+
* Sign a user in from your server, without a password, code or captcha: a new session (access and refresh token)
|
|
124
|
+
* for automated tests and support tools. On the user's activity log as "Signed in by your server". No second factor
|
|
125
|
+
* (the session is aal1); banned users are refused.
|
|
126
|
+
*
|
|
127
|
+
* ```ts
|
|
128
|
+
* const { data: session } = await baas.auth.admin.createSession(userId)
|
|
129
|
+
* // in the test's browser client: await client.auth.setSessionTokens(session!)
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
createSession(id: string): Promise<Result<Session>>;
|
|
133
|
+
}
|
|
134
|
+
export interface ServerAuth {
|
|
135
|
+
/**
|
|
136
|
+
* Who is calling? Accepts an Express/Node request, a Fetch Request / NextRequest,
|
|
137
|
+
* Next.js `cookies()`/`headers()`, or a raw access token. Returns `null` when signed out.
|
|
138
|
+
* Verified with usebecky and cached for ~30 seconds.
|
|
139
|
+
*/
|
|
140
|
+
getUser(input: RequestLike | Promise<RequestLike>): Promise<User | null>;
|
|
141
|
+
/** Express/Connect middleware: sets `req.user` (or null). Never blocks the request. */
|
|
142
|
+
middleware(): Middleware;
|
|
143
|
+
/** Express/Connect middleware: responds 401 JSON when nobody is signed in, else sets `req.user`. */
|
|
144
|
+
requireUser(): Middleware;
|
|
145
|
+
/** User management (secret key). */
|
|
146
|
+
admin: AdminUsersApi;
|
|
147
|
+
}
|
|
148
|
+
export interface ServerClient<DB = any> {
|
|
149
|
+
readonly url: string;
|
|
150
|
+
readonly auth: ServerAuth;
|
|
151
|
+
/** As admin (service role): bypasses Row Level Security. Only use for trusted server work. */
|
|
152
|
+
readonly admin: ScopedClient<DB>;
|
|
153
|
+
/** As the user who made this request (RLS applies). Accepts a request, `req.user`, or a token. */
|
|
154
|
+
as(input: RequestLike | User): UserScopedClient<DB>;
|
|
155
|
+
/** Aliases: `baas.db.as(req)`, `baas.db.admin`. */
|
|
156
|
+
readonly db: {
|
|
157
|
+
as(input: RequestLike | User): UserScopedClient<DB>;
|
|
158
|
+
readonly admin: ScopedClient<DB>;
|
|
159
|
+
};
|
|
160
|
+
/** Access checks, subscriptions (list, cancel, resume), gifts and shop orders. */
|
|
161
|
+
readonly payments: ServerPayments;
|
|
162
|
+
/** Visitor analytics reports (secret key): `overview`, `report('pages' | 'countries' | ...)`, `timeseries`, per site with
|
|
163
|
+
* `filters: { hostname }`. */
|
|
164
|
+
readonly analytics: ServerAnalytics;
|
|
165
|
+
/** The project's usage against its plan (secret key): `baas.usage.get()`. Events quota.warning / quota.exceeded say it too. */
|
|
166
|
+
readonly usage: ServerUsage;
|
|
167
|
+
/** Signed events from usebecky (subscriptions, users, ...). */
|
|
168
|
+
readonly events: Events;
|
|
169
|
+
/** Send emails from your server (secret key): `send({ to, subject, text })` or `send({ to, template, data })`, `batch`, `get`, `cancel`. */
|
|
170
|
+
readonly emails: ServerEmails;
|
|
171
|
+
/** Newsletter subscribers from your server (secret key): `add`, `unsubscribe`, `list`. */
|
|
172
|
+
readonly newsletter: ServerNewsletter;
|
|
173
|
+
/** Push notifications from your server (secret key): `baas.push.send({ userIds, title, body })`. */
|
|
174
|
+
readonly push: ServerPush;
|
|
175
|
+
/** Run your Functions from your server (secret key, so "servers only" functions work): `baas.functions.invoke('name', { body })`. */
|
|
176
|
+
readonly functions: FunctionsClient;
|
|
177
|
+
/**
|
|
178
|
+
* The built-in cache (Business plan), for your server and Functions only: `set(key, value, { ttl: '10m' })`,
|
|
179
|
+
* `get(key)`, `delete(key)`, `getOrSet(key, compute)`, and `limit(key, 5, '1h')` for rate limits.
|
|
180
|
+
*/
|
|
181
|
+
readonly cache: ServerCache;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Create a server client explicitly: `createServerClient('ub_sk_...')` or `createServerClient({ secretKey, ... })`.
|
|
185
|
+
* The API address defaults to the hosted API. Most apps can just `import { baas } from 'usebecky/server'`.
|
|
186
|
+
*/
|
|
187
|
+
export declare function createServerClient<DB = any>(secretKeyOrOptions?: string | ServerClientOptions, _events?: Events): ServerClient<DB>;
|
|
188
|
+
/**
|
|
189
|
+
* Ready-to-use server client from the env var USEBECKY_SECRET_KEY (on the hosted API; USEBECKY_URL only to use a different one).
|
|
190
|
+
* Created on first use, so importing it never crashes your app. `baas.events` only needs
|
|
191
|
+
* USEBECKY_WEBHOOK_SECRET.
|
|
192
|
+
*/
|
|
193
|
+
export declare const baas: ServerClient;
|
|
194
|
+
/** For tests: forget the singleton so it re-reads env vars. */
|
|
195
|
+
export declare function resetServerClient(): void;
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// `usebecky/server`: use usebecky from your own backend (Express, Next.js, Remix, Hono, ...).
|
|
2
|
+
//
|
|
3
|
+
// import { baas } from 'usebecky/server' // reads USEBECKY_URL + USEBECKY_SECRET_KEY
|
|
4
|
+
// app.use(baas.auth.middleware()) // req.user is the signed-in user (or null)
|
|
5
|
+
// await baas.as(req).from('todos').select() // as that user: RLS applies
|
|
6
|
+
// await baas.admin.from('todos').select() // as admin: bypasses RLS, careful!
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { validateUrl } from "../client.js";
|
|
9
|
+
import { Database } from "../db/query.js";
|
|
10
|
+
import { DASHBOARD_API_KEYS } from "../lib/dashboard-paths.js";
|
|
11
|
+
import { keyType, readEnv } from "../lib/env.js";
|
|
12
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
13
|
+
import { HOSTED_API_URL } from "../lib/hosted.js";
|
|
14
|
+
import { HttpClient } from "../lib/http.js";
|
|
15
|
+
import { decodeJwt } from "../lib/jwt.js";
|
|
16
|
+
import { localeField } from "../lib/locale.js";
|
|
17
|
+
import { PaymentsClient } from "../payments/client.js";
|
|
18
|
+
import { serverNewsletter } from "../newsletter/client.js";
|
|
19
|
+
import { StorageClient } from "../storage/client.js";
|
|
20
|
+
import { FunctionsClient } from "../functions/client.js";
|
|
21
|
+
import { createCache } from "./cache.js";
|
|
22
|
+
import { createEmails } from "./emails.js";
|
|
23
|
+
import { createPush } from "./push.js";
|
|
24
|
+
import { createServerPayments } from "./payments.js";
|
|
25
|
+
import { createServerAnalytics } from "./analytics.js";
|
|
26
|
+
import { createServerUsage } from "./usage.js";
|
|
27
|
+
import { Events } from "./events.js";
|
|
28
|
+
import { extractToken, sendJson } from "./http-utils.js";
|
|
29
|
+
export { FunctionsClient } from "../functions/client.js";
|
|
30
|
+
export { Events, verifyEvent, signEvent, SIGNATURE_HEADER } from "./events.js";
|
|
31
|
+
export { extractToken, parseCookies, ACCESS_TOKEN_COOKIE } from "./http-utils.js";
|
|
32
|
+
export { UseBeckyError, isUseBeckyError } from "../lib/errors.js";
|
|
33
|
+
export { HOSTED_API_URL } from "../lib/hosted.js";
|
|
34
|
+
/** Database + storage bound to one role. */
|
|
35
|
+
export class ScopedClient extends Database {
|
|
36
|
+
/** Files, with the same permissions as `from()`. */
|
|
37
|
+
storage;
|
|
38
|
+
/** Your Functions, called with the same identity: `functions.invoke('name', { body })`. */
|
|
39
|
+
functions;
|
|
40
|
+
constructor(http, publicKey) {
|
|
41
|
+
super(http);
|
|
42
|
+
this.storage = new StorageClient(http, publicKey);
|
|
43
|
+
this.functions = new FunctionsClient(http);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Acting as a specific user (RLS applies). */
|
|
47
|
+
export class UserScopedClient extends ScopedClient {
|
|
48
|
+
/** Payments as this user (checkout/portal return URLs instead of redirecting). */
|
|
49
|
+
payments;
|
|
50
|
+
constructor(http, publicKey, hasUser) {
|
|
51
|
+
super(http, publicKey);
|
|
52
|
+
this.payments = new PaymentsClient(http, async () => hasUser);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
let warnedPublishable = false;
|
|
56
|
+
function configError() {
|
|
57
|
+
const lines = [
|
|
58
|
+
'usebecky/server: missing USEBECKY_SECRET_KEY.',
|
|
59
|
+
'',
|
|
60
|
+
`Add it to your server's environment (for example a .env file), copying it from ${DASHBOARD_API_KEYS}:`,
|
|
61
|
+
' USEBECKY_SECRET_KEY=ub_sk_...',
|
|
62
|
+
'',
|
|
63
|
+
'Or pass it in: createServerClient("ub_sk_...").',
|
|
64
|
+
'Tips: `npx usebecky init` writes it for you. Node does not read .env files on its own: run `node --env-file=.env server.js`.',
|
|
65
|
+
'Never put the secret key in browser code.',
|
|
66
|
+
];
|
|
67
|
+
return new Error(lines.join('\n'));
|
|
68
|
+
}
|
|
69
|
+
function hashToken(token) {
|
|
70
|
+
return createHash('sha256').update(token).digest('hex');
|
|
71
|
+
}
|
|
72
|
+
const notSignedInFetch = async () => new Response(JSON.stringify({
|
|
73
|
+
error: {
|
|
74
|
+
code: 'not_signed_in',
|
|
75
|
+
message: 'This request has no signed-in user, so it cannot run as one.',
|
|
76
|
+
hint: 'Send the access token ("Authorization: Bearer <token>" or the ub-access-token cookie), use baas.auth.requireUser() first, or set USEBECKY_PUBLISHABLE_KEY to allow anonymous access.',
|
|
77
|
+
},
|
|
78
|
+
}), { status: 401, headers: { 'content-type': 'application/json' } });
|
|
79
|
+
/**
|
|
80
|
+
* Create a server client explicitly: `createServerClient('ub_sk_...')` or `createServerClient({ secretKey, ... })`.
|
|
81
|
+
* The API address defaults to the hosted API. Most apps can just `import { baas } from 'usebecky/server'`.
|
|
82
|
+
*/
|
|
83
|
+
export function createServerClient(secretKeyOrOptions = {}, _events) {
|
|
84
|
+
const options = typeof secretKeyOrOptions === 'string' ? { secretKey: secretKeyOrOptions } : secretKeyOrOptions;
|
|
85
|
+
const rawUrl = options.url || readEnv('USEBECKY_URL') || readEnv('NEXT_PUBLIC_USEBECKY_URL') || HOSTED_API_URL;
|
|
86
|
+
const givenSecret = options.secretKey || readEnv('USEBECKY_SECRET_KEY');
|
|
87
|
+
if (!givenSecret)
|
|
88
|
+
throw configError();
|
|
89
|
+
const secretKey = givenSecret;
|
|
90
|
+
const url = validateUrl(rawUrl, 'URL (USEBECKY_URL)');
|
|
91
|
+
if (keyType(secretKey) === 'publishable' && !warnedPublishable) {
|
|
92
|
+
warnedPublishable = true;
|
|
93
|
+
console.warn('\n[usebecky] ⚠️ USEBECKY_SECRET_KEY contains a PUBLISHABLE key (ub_pk_...).\n' +
|
|
94
|
+
' Server features like baas.admin, baas.auth.admin and payments.hasAccess need the SECRET key (ub_sk_...).\n' +
|
|
95
|
+
` Copy it from ${DASHBOARD_API_KEYS}.\n`);
|
|
96
|
+
}
|
|
97
|
+
const publishableKey = options.publishableKey ?? readEnv('USEBECKY_PUBLISHABLE_KEY') ?? readEnv('NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY') ?? (keyType(secretKey) === 'publishable' ? secretKey : undefined);
|
|
98
|
+
const http = new HttpClient({ url, key: secretKey, fetch: options.fetch, getToken: async () => null });
|
|
99
|
+
const ttl = options.userCacheTtlMs ?? 30_000;
|
|
100
|
+
const events = _events ?? new Events(() => options.webhookSecret ?? readEnv('USEBECKY_WEBHOOK_SECRET'));
|
|
101
|
+
// ---- getUser with a short cache ----
|
|
102
|
+
const cache = new Map();
|
|
103
|
+
const inflight = new Map();
|
|
104
|
+
const tokenOfUser = new WeakMap();
|
|
105
|
+
let lastWarn = 0;
|
|
106
|
+
async function verify(token) {
|
|
107
|
+
const claims = decodeJwt(token);
|
|
108
|
+
const nowMs = Date.now();
|
|
109
|
+
if (!claims || (typeof claims.exp === 'number' && claims.exp * 1000 <= nowMs))
|
|
110
|
+
return null;
|
|
111
|
+
const key = hashToken(token);
|
|
112
|
+
const hit = cache.get(key);
|
|
113
|
+
if (hit && hit.expires > nowMs)
|
|
114
|
+
return hit.user;
|
|
115
|
+
const pending = inflight.get(key);
|
|
116
|
+
if (pending)
|
|
117
|
+
return pending;
|
|
118
|
+
const p = (async () => {
|
|
119
|
+
const res = await http.request('/auth/v1/user', { token });
|
|
120
|
+
if (res.error && (res.error.status === 0 || res.error.status >= 500 || res.error.status === 429)) {
|
|
121
|
+
if (Date.now() - lastWarn > 60_000) {
|
|
122
|
+
lastWarn = Date.now();
|
|
123
|
+
console.warn(`[usebecky] Could not verify a user token: ${res.error.message}`);
|
|
124
|
+
}
|
|
125
|
+
return null; // not cached: try again next time
|
|
126
|
+
}
|
|
127
|
+
const user = res.error ? null : (res.data ?? null);
|
|
128
|
+
if (user)
|
|
129
|
+
tokenOfUser.set(user, token);
|
|
130
|
+
const expires = Math.min(Date.now() + ttl, typeof claims.exp === 'number' ? claims.exp * 1000 : Infinity);
|
|
131
|
+
cache.set(key, { user, expires });
|
|
132
|
+
if (cache.size > 5000) {
|
|
133
|
+
for (const [k, v] of cache) {
|
|
134
|
+
if (v.expires <= Date.now() || cache.size > 4000)
|
|
135
|
+
cache.delete(k);
|
|
136
|
+
if (cache.size <= 4000)
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return user;
|
|
141
|
+
})().finally(() => inflight.delete(key));
|
|
142
|
+
inflight.set(key, p);
|
|
143
|
+
return p;
|
|
144
|
+
}
|
|
145
|
+
async function getUser(input) {
|
|
146
|
+
const resolved = input && typeof input.then === 'function' ? await input : input;
|
|
147
|
+
const token = extractToken(resolved);
|
|
148
|
+
return token ? verify(token) : null;
|
|
149
|
+
}
|
|
150
|
+
function tokenFrom(input) {
|
|
151
|
+
// `req.user` objects returned by getUser()/middleware remember the token they came from.
|
|
152
|
+
const known = input && typeof input === 'object' ? tokenOfUser.get(input) : undefined;
|
|
153
|
+
return known ?? extractToken(input);
|
|
154
|
+
}
|
|
155
|
+
function as(input) {
|
|
156
|
+
const token = tokenFrom(input);
|
|
157
|
+
if (token)
|
|
158
|
+
return new UserScopedClient(http.withToken(token), publishableKey ?? null, true);
|
|
159
|
+
if (publishableKey)
|
|
160
|
+
return new UserScopedClient(new HttpClient({ url, key: publishableKey, fetch: options.fetch }), publishableKey, false);
|
|
161
|
+
return new UserScopedClient(new HttpClient({ url, key: secretKey, fetch: notSignedInFetch }), null, false);
|
|
162
|
+
}
|
|
163
|
+
const admin = new ScopedClient(http, publishableKey ?? null);
|
|
164
|
+
const authAdmin = {
|
|
165
|
+
async listUsers(o = {}) {
|
|
166
|
+
const res = await http.request('/auth/v1/admin/users', { query: { page: o.page ?? 1, per_page: o.perPage ?? 50, q: o.q } });
|
|
167
|
+
if (res.error)
|
|
168
|
+
return { data: null, error: res.error };
|
|
169
|
+
return { data: { users: res.data?.users ?? [], total: res.data?.total ?? 0, page: res.data?.page ?? o.page ?? 1, perPage: res.data?.per_page ?? o.perPage ?? 50 }, error: null };
|
|
170
|
+
},
|
|
171
|
+
async createUser(a) {
|
|
172
|
+
return one(http.request('/auth/v1/admin/users', { method: 'POST', body: { email: a.email, password: a.password, email_confirm: a.emailConfirm, user_metadata: a.userMetadata, app_metadata: a.appMetadata } }));
|
|
173
|
+
},
|
|
174
|
+
async getUserById(id) {
|
|
175
|
+
return one(http.request(`/auth/v1/admin/users/${encodeURIComponent(id)}`));
|
|
176
|
+
},
|
|
177
|
+
async updateUser(id, a) {
|
|
178
|
+
return one(http.request(`/auth/v1/admin/users/${encodeURIComponent(id)}`, {
|
|
179
|
+
method: 'PUT',
|
|
180
|
+
body: { email: a.email, password: a.password, email_confirm: a.emailConfirm, ban_duration: a.ban, user_metadata: a.userMetadata, app_metadata: a.appMetadata },
|
|
181
|
+
}));
|
|
182
|
+
},
|
|
183
|
+
async deleteUser(id) {
|
|
184
|
+
const r = await one(http.request(`/auth/v1/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }));
|
|
185
|
+
return r.error ? r : { data: { id: r.data?.id ?? id }, error: null };
|
|
186
|
+
},
|
|
187
|
+
async inviteUser(email, o = {}) {
|
|
188
|
+
return one(http.request('/auth/v1/admin/invite', { method: 'POST', body: { email, redirect_to: o.redirectTo, data: o.data, ...localeField(o.locale, 'admin.inviteUser({ locale })') } }));
|
|
189
|
+
},
|
|
190
|
+
async signOutUser(id) {
|
|
191
|
+
const r = await one(http.request(`/auth/v1/admin/users/${encodeURIComponent(id)}/logout`, { method: 'POST' }));
|
|
192
|
+
return r.error ? r : { data: { ok: true }, error: null };
|
|
193
|
+
},
|
|
194
|
+
async createSession(id) {
|
|
195
|
+
if (!id)
|
|
196
|
+
return { data: null, error: new UseBeckyError({ code: 'invalid_input', message: 'Pass the id of the user to sign in.', status: 0 }) };
|
|
197
|
+
return one(http.request(`/auth/v1/admin/users/${encodeURIComponent(id)}/sessions`, { method: 'POST' }));
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
const auth = {
|
|
201
|
+
getUser,
|
|
202
|
+
middleware() {
|
|
203
|
+
return (req, _res, next) => {
|
|
204
|
+
getUser(req).then((user) => {
|
|
205
|
+
req.user = user;
|
|
206
|
+
next();
|
|
207
|
+
}, (err) => next(err));
|
|
208
|
+
};
|
|
209
|
+
},
|
|
210
|
+
requireUser() {
|
|
211
|
+
return (req, res, next) => {
|
|
212
|
+
const done = (user) => {
|
|
213
|
+
if (!user) {
|
|
214
|
+
sendJson(res, 401, {
|
|
215
|
+
error: {
|
|
216
|
+
code: 'not_signed_in',
|
|
217
|
+
message: 'You need to be signed in.',
|
|
218
|
+
hint: 'Sign in first. The browser client sends the token automatically in the ub-access-token cookie; from other clients send "Authorization: Bearer <access token>".',
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
req.user = user;
|
|
224
|
+
if (typeof next === 'function')
|
|
225
|
+
next();
|
|
226
|
+
};
|
|
227
|
+
if (req?.user && typeof req.user === 'object' && req.user.id)
|
|
228
|
+
return done(req.user);
|
|
229
|
+
getUser(req).then(done, (err) => (typeof next === 'function' ? next(err) : sendJson(res, 500, { error: { code: 'server_error', message: String(err?.message ?? err) } })));
|
|
230
|
+
};
|
|
231
|
+
},
|
|
232
|
+
admin: authAdmin,
|
|
233
|
+
};
|
|
234
|
+
const payments = createServerPayments(http);
|
|
235
|
+
const analytics = createServerAnalytics(http);
|
|
236
|
+
const usage = createServerUsage(http);
|
|
237
|
+
return {
|
|
238
|
+
url,
|
|
239
|
+
auth,
|
|
240
|
+
admin,
|
|
241
|
+
as,
|
|
242
|
+
db: { as, admin },
|
|
243
|
+
payments,
|
|
244
|
+
analytics,
|
|
245
|
+
usage,
|
|
246
|
+
events,
|
|
247
|
+
emails: createEmails(http),
|
|
248
|
+
newsletter: serverNewsletter(http),
|
|
249
|
+
push: createPush(http),
|
|
250
|
+
functions: admin.functions,
|
|
251
|
+
cache: createCache(http),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async function one(p) {
|
|
255
|
+
const r = await p;
|
|
256
|
+
return r.error ? { data: null, error: r.error } : { data: r.data, error: null };
|
|
257
|
+
}
|
|
258
|
+
// ---- the lazy `baas` singleton -----------------------------------------------------------
|
|
259
|
+
let instance = null;
|
|
260
|
+
const sharedEvents = new Events();
|
|
261
|
+
function get() {
|
|
262
|
+
return (instance ??= createServerClient({}, sharedEvents));
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Ready-to-use server client from the env var USEBECKY_SECRET_KEY (on the hosted API; USEBECKY_URL only to use a different one).
|
|
266
|
+
* Created on first use, so importing it never crashes your app. `baas.events` only needs
|
|
267
|
+
* USEBECKY_WEBHOOK_SECRET.
|
|
268
|
+
*/
|
|
269
|
+
export const baas = {
|
|
270
|
+
get url() {
|
|
271
|
+
return get().url;
|
|
272
|
+
},
|
|
273
|
+
get auth() {
|
|
274
|
+
return get().auth;
|
|
275
|
+
},
|
|
276
|
+
get admin() {
|
|
277
|
+
return get().admin;
|
|
278
|
+
},
|
|
279
|
+
as(input) {
|
|
280
|
+
return get().as(input);
|
|
281
|
+
},
|
|
282
|
+
get db() {
|
|
283
|
+
return get().db;
|
|
284
|
+
},
|
|
285
|
+
get payments() {
|
|
286
|
+
return get().payments;
|
|
287
|
+
},
|
|
288
|
+
get analytics() {
|
|
289
|
+
return get().analytics;
|
|
290
|
+
},
|
|
291
|
+
get usage() {
|
|
292
|
+
return get().usage;
|
|
293
|
+
},
|
|
294
|
+
events: sharedEvents,
|
|
295
|
+
get emails() {
|
|
296
|
+
return get().emails;
|
|
297
|
+
},
|
|
298
|
+
get functions() {
|
|
299
|
+
return get().functions;
|
|
300
|
+
},
|
|
301
|
+
get push() {
|
|
302
|
+
return get().push;
|
|
303
|
+
},
|
|
304
|
+
get newsletter() {
|
|
305
|
+
return get().newsletter;
|
|
306
|
+
},
|
|
307
|
+
get cache() {
|
|
308
|
+
return get().cache;
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
/** For tests: forget the singleton so it re-reads env vars. */
|
|
312
|
+
export function resetServerClient() {
|
|
313
|
+
instance = null;
|
|
314
|
+
}
|