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
package/dist/lib/http.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Minimal fetch wrapper: adds the API key + user token, parses JSON, never throws.
|
|
2
|
+
import { errorFromResponse, networkError } from "./errors.js";
|
|
3
|
+
export const VERSION = '0.2.0';
|
|
4
|
+
/** 401 codes that mean "this access token is no longer good" (refresh, then retry once). */
|
|
5
|
+
const TOKEN_REJECTED = new Set(['token_expired', 'invalid_token']);
|
|
6
|
+
export function isRawBody(body) {
|
|
7
|
+
if (body == null)
|
|
8
|
+
return false;
|
|
9
|
+
if (typeof body === 'string')
|
|
10
|
+
return true;
|
|
11
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
12
|
+
return true;
|
|
13
|
+
const g = globalThis;
|
|
14
|
+
if (typeof g.Blob === 'function' && body instanceof g.Blob)
|
|
15
|
+
return true;
|
|
16
|
+
if (typeof g.FormData === 'function' && body instanceof g.FormData)
|
|
17
|
+
return true;
|
|
18
|
+
if (typeof g.ReadableStream === 'function' && body instanceof g.ReadableStream)
|
|
19
|
+
return true;
|
|
20
|
+
if (typeof g.URLSearchParams === 'function' && body instanceof g.URLSearchParams)
|
|
21
|
+
return true;
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
export function buildUrl(base, path, query) {
|
|
25
|
+
let url = base + path;
|
|
26
|
+
if (query) {
|
|
27
|
+
const sp = new URLSearchParams();
|
|
28
|
+
const entries = Array.isArray(query) ? query : Object.entries(query);
|
|
29
|
+
for (const [k, v] of entries)
|
|
30
|
+
if (v !== undefined && v !== null)
|
|
31
|
+
sp.append(k, String(v));
|
|
32
|
+
const qs = sp.toString();
|
|
33
|
+
if (qs)
|
|
34
|
+
url += (url.includes('?') ? '&' : '?') + qs;
|
|
35
|
+
}
|
|
36
|
+
return url;
|
|
37
|
+
}
|
|
38
|
+
export class HttpClient {
|
|
39
|
+
url;
|
|
40
|
+
key;
|
|
41
|
+
fetchImpl;
|
|
42
|
+
getToken;
|
|
43
|
+
onTokenRejected;
|
|
44
|
+
extraHeaders;
|
|
45
|
+
localeRef;
|
|
46
|
+
constructor(init) {
|
|
47
|
+
this.url = init.url.replace(/\/+$/, '');
|
|
48
|
+
this.key = init.key;
|
|
49
|
+
const custom = init.fetch;
|
|
50
|
+
// Resolve globalThis.fetch lazily so it is never called with the wrong `this`.
|
|
51
|
+
this.fetchImpl = custom ?? ((input, reqInit) => globalThis.fetch(input, reqInit));
|
|
52
|
+
this.getToken = init.getToken ?? (async () => null);
|
|
53
|
+
this.onTokenRejected = init.onTokenRejected;
|
|
54
|
+
this.extraHeaders = init.headers ?? {};
|
|
55
|
+
this.localeRef = init.locale ?? { value: null };
|
|
56
|
+
}
|
|
57
|
+
/** The language sent as `Accept-Language`, or null for none. */
|
|
58
|
+
get locale() {
|
|
59
|
+
return this.localeRef.value;
|
|
60
|
+
}
|
|
61
|
+
/** Change the `Accept-Language` language for every later request (null = send none). */
|
|
62
|
+
setLocale(locale) {
|
|
63
|
+
this.localeRef.value = locale;
|
|
64
|
+
}
|
|
65
|
+
/** Same client, but every request carries `token` as the user token. */
|
|
66
|
+
withToken(token) {
|
|
67
|
+
return new HttpClient({ url: this.url, key: this.key, fetch: this.fetchImpl, getToken: async () => token, headers: this.extraHeaders, locale: this.localeRef });
|
|
68
|
+
}
|
|
69
|
+
async authHeaders(token) {
|
|
70
|
+
const headers = { apikey: this.key, 'x-client-info': `usebecky-js/${VERSION}`, ...this.extraHeaders };
|
|
71
|
+
const locale = this.localeRef.value;
|
|
72
|
+
if (locale) {
|
|
73
|
+
for (const k of Object.keys(headers))
|
|
74
|
+
if (k.toLowerCase() === 'accept-language')
|
|
75
|
+
delete headers[k];
|
|
76
|
+
headers['accept-language'] = locale;
|
|
77
|
+
}
|
|
78
|
+
const userToken = token === undefined ? await this.getToken() : token;
|
|
79
|
+
if (userToken)
|
|
80
|
+
headers.authorization = `Bearer ${userToken}`;
|
|
81
|
+
return headers;
|
|
82
|
+
}
|
|
83
|
+
async request(path, opts = {}) {
|
|
84
|
+
let token = opts.token;
|
|
85
|
+
if (token === undefined) {
|
|
86
|
+
try {
|
|
87
|
+
token = await this.getToken();
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
token = null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const first = await this.send(path, opts, token);
|
|
94
|
+
// The session's token was rejected (e.g. expired early, clock skew): refresh once and retry.
|
|
95
|
+
if (opts.token === undefined &&
|
|
96
|
+
token &&
|
|
97
|
+
this.onTokenRejected &&
|
|
98
|
+
first.error?.status === 401 &&
|
|
99
|
+
TOKEN_REJECTED.has(first.error.code) &&
|
|
100
|
+
!(typeof globalThis.ReadableStream === 'function' && opts.body instanceof globalThis.ReadableStream)) {
|
|
101
|
+
const fresh = await this.onTokenRejected(token).catch(() => null);
|
|
102
|
+
if (fresh && fresh !== token)
|
|
103
|
+
return this.send(path, opts, fresh);
|
|
104
|
+
}
|
|
105
|
+
return first;
|
|
106
|
+
}
|
|
107
|
+
async send(path, opts, token) {
|
|
108
|
+
const method = (opts.method ?? 'GET').toUpperCase();
|
|
109
|
+
const url = buildUrl(this.url, path, opts.query);
|
|
110
|
+
let headers;
|
|
111
|
+
try {
|
|
112
|
+
headers = { ...(await this.authHeaders(token)), ...(opts.headers ?? {}) };
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
return { data: null, error: networkError(url, err), status: 0, headers: null };
|
|
116
|
+
}
|
|
117
|
+
let body = undefined;
|
|
118
|
+
if (opts.body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
119
|
+
if (isRawBody(opts.body))
|
|
120
|
+
body = opts.body;
|
|
121
|
+
else {
|
|
122
|
+
body = JSON.stringify(opts.body);
|
|
123
|
+
if (!hasHeader(headers, 'content-type'))
|
|
124
|
+
headers['content-type'] = 'application/json';
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
let res;
|
|
128
|
+
try {
|
|
129
|
+
res = await this.fetchImpl(url, { method, headers, body, signal: opts.signal, ...(body && typeof globalThis.ReadableStream === 'function' && body instanceof globalThis.ReadableStream ? { duplex: 'half' } : {}) });
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
return { data: null, error: networkError(url, err), status: 0, headers: null };
|
|
133
|
+
}
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
let text = '';
|
|
136
|
+
try {
|
|
137
|
+
text = await res.text();
|
|
138
|
+
}
|
|
139
|
+
catch { }
|
|
140
|
+
let parsed = text;
|
|
141
|
+
try {
|
|
142
|
+
parsed = text ? JSON.parse(text) : null;
|
|
143
|
+
}
|
|
144
|
+
catch { }
|
|
145
|
+
return { data: null, error: errorFromResponse(res.status, parsed, res.statusText), status: res.status, headers: res.headers };
|
|
146
|
+
}
|
|
147
|
+
const parse = opts.parse ?? 'json';
|
|
148
|
+
try {
|
|
149
|
+
if (parse === 'none' || method === 'HEAD' || res.status === 204)
|
|
150
|
+
return { data: null, error: null, status: res.status, headers: res.headers };
|
|
151
|
+
if (parse === 'blob')
|
|
152
|
+
return { data: (await res.blob()), error: null, status: res.status, headers: res.headers };
|
|
153
|
+
const text = await res.text();
|
|
154
|
+
if (parse === 'text')
|
|
155
|
+
return { data: text, error: null, status: res.status, headers: res.headers };
|
|
156
|
+
if (!text)
|
|
157
|
+
return { data: null, error: null, status: res.status, headers: res.headers };
|
|
158
|
+
try {
|
|
159
|
+
return { data: JSON.parse(text), error: null, status: res.status, headers: res.headers };
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return { data: text, error: null, status: res.status, headers: res.headers };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
return { data: null, error: networkError(url, err), status: res.status, headers: res.headers };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function hasHeader(headers, name) {
|
|
171
|
+
return Object.keys(headers).some((k) => k.toLowerCase() === name);
|
|
172
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function decodeJwt(token: string): Record<string, any> | null;
|
package/dist/lib/jwt.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Decode (NOT verify) a JWT payload. Used to read `exp`, `sub`, `aal` locally.
|
|
2
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
3
|
+
function base64ToBytes(b64) {
|
|
4
|
+
const clean = b64.replace(/[^A-Za-z0-9+/]/g, '');
|
|
5
|
+
const out = [];
|
|
6
|
+
let buffer = 0;
|
|
7
|
+
let bits = 0;
|
|
8
|
+
for (const ch of clean) {
|
|
9
|
+
buffer = (buffer << 6) | B64.indexOf(ch);
|
|
10
|
+
bits += 6;
|
|
11
|
+
if (bits >= 8) {
|
|
12
|
+
bits -= 8;
|
|
13
|
+
out.push((buffer >> bits) & 0xff);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return new Uint8Array(out);
|
|
17
|
+
}
|
|
18
|
+
export function decodeJwt(token) {
|
|
19
|
+
try {
|
|
20
|
+
const part = token.split('.')[1];
|
|
21
|
+
if (!part)
|
|
22
|
+
return null;
|
|
23
|
+
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
|
|
24
|
+
const json = new TextDecoder().decode(base64ToBytes(b64));
|
|
25
|
+
const payload = JSON.parse(json);
|
|
26
|
+
return payload && typeof payload === 'object' ? payload : null;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tidy a language code into BCP-47 form ("pt_br" → "pt-BR", "DE" → "de"), or null when it isn't one.
|
|
3
|
+
* Only letters, digits and hyphens survive, so the value is always safe as an Accept-Language header
|
|
4
|
+
* (no CORS preflight needed for it).
|
|
5
|
+
*/
|
|
6
|
+
export declare function normalizeLocale(input: unknown): string | null;
|
|
7
|
+
/** Like normalizeLocale, but warns once (in the console) when a non-empty value isn't a language code. */
|
|
8
|
+
export declare function readLocale(input: unknown, where: string): string | null;
|
|
9
|
+
/** The `locale` body field for an email call: `{ locale }` with a valid code, else nothing. */
|
|
10
|
+
export declare function localeField(input: unknown, where: string): {
|
|
11
|
+
locale?: string;
|
|
12
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Language codes for the emails usebecky sends to your users ("de", "pt-BR", ...).
|
|
2
|
+
//
|
|
3
|
+
// The client sends its language as the Accept-Language header on every request, and the email calls
|
|
4
|
+
// (signUp, sendMagicLink, resetPassword, resend, updateUser, admin.inviteUser, emails.send) can pass a
|
|
5
|
+
// `locale` body field. The server picks the email language: explicit `locale` → the user's
|
|
6
|
+
// user_metadata.locale → Accept-Language → the project's default language. Unknown codes are ignored there.
|
|
7
|
+
let warned = false;
|
|
8
|
+
/**
|
|
9
|
+
* Tidy a language code into BCP-47 form ("pt_br" → "pt-BR", "DE" → "de"), or null when it isn't one.
|
|
10
|
+
* Only letters, digits and hyphens survive, so the value is always safe as an Accept-Language header
|
|
11
|
+
* (no CORS preflight needed for it).
|
|
12
|
+
*/
|
|
13
|
+
export function normalizeLocale(input) {
|
|
14
|
+
if (typeof input !== 'string')
|
|
15
|
+
return null;
|
|
16
|
+
const raw = input.trim().replace(/_/g, '-');
|
|
17
|
+
if (!/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/.test(raw) || raw.length > 35)
|
|
18
|
+
return null;
|
|
19
|
+
return raw
|
|
20
|
+
.split('-')
|
|
21
|
+
.map((part, i) => {
|
|
22
|
+
if (i === 0)
|
|
23
|
+
return part.toLowerCase();
|
|
24
|
+
if (part.length === 2 && /^[A-Za-z]+$/.test(part))
|
|
25
|
+
return part.toUpperCase(); // region: BR
|
|
26
|
+
if (part.length === 4 && /^[A-Za-z]+$/.test(part))
|
|
27
|
+
return part[0].toUpperCase() + part.slice(1).toLowerCase(); // script: Hans
|
|
28
|
+
return part.toLowerCase();
|
|
29
|
+
})
|
|
30
|
+
.join('-');
|
|
31
|
+
}
|
|
32
|
+
/** Like normalizeLocale, but warns once (in the console) when a non-empty value isn't a language code. */
|
|
33
|
+
export function readLocale(input, where) {
|
|
34
|
+
if (input === undefined || input === null || input === '')
|
|
35
|
+
return null;
|
|
36
|
+
const locale = normalizeLocale(input);
|
|
37
|
+
if (!locale && !warned) {
|
|
38
|
+
warned = true;
|
|
39
|
+
try {
|
|
40
|
+
;
|
|
41
|
+
globalThis.console?.warn?.(`[usebecky] ${where}: ${JSON.stringify(input)} is not a language code like "de" or "pt-BR", so it was ignored.`);
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
return locale;
|
|
46
|
+
}
|
|
47
|
+
/** The `locale` body field for an email call: `{ locale }` with a valid code, else nothing. */
|
|
48
|
+
export function localeField(input, where) {
|
|
49
|
+
const locale = readLocale(input, where);
|
|
50
|
+
return locale ? { locale } : {};
|
|
51
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface PkcePair {
|
|
2
|
+
verifier: string;
|
|
3
|
+
challenge: string;
|
|
4
|
+
}
|
|
5
|
+
/** base64url without padding. */
|
|
6
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
7
|
+
/**
|
|
8
|
+
* SHA-256 in plain JavaScript, for runtimes without `crypto.subtle` (React Native, or a page served over
|
|
9
|
+
* http:// from a LAN address, where browsers hide crypto.subtle).
|
|
10
|
+
*/
|
|
11
|
+
export declare function sha256Bytes(msg: Uint8Array): Uint8Array;
|
|
12
|
+
/** The S256 challenge for a verifier: base64url(SHA-256(verifier)). Uses crypto.subtle when available. */
|
|
13
|
+
export declare function challengeFor(verifier: string): Promise<string>;
|
|
14
|
+
/** True when this runtime has a secure random generator (needed for PKCE). */
|
|
15
|
+
export declare function canUsePkce(): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* A new verifier (32 random bytes → 43 characters) and its challenge. `null` when the runtime has no
|
|
18
|
+
* secure random generator (React Native without a crypto polyfill): then sign-in uses the older flow.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createPkcePair(): Promise<PkcePair | null>;
|
package/dist/lib/pkce.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// PKCE (RFC 7636) for social sign-in: a random code verifier and its S256 challenge.
|
|
2
|
+
//
|
|
3
|
+
// signInWith() sends the challenge to /auth/v1/authorize and keeps the verifier. The server redirects
|
|
4
|
+
// back with a one-time ?code= instead of tokens, and only the holder of the verifier can swap that code
|
|
5
|
+
// for a session (POST /auth/v1/token?grant_type=pkce). So another app or page that catches the redirect
|
|
6
|
+
// gets nothing useful.
|
|
7
|
+
const g = globalThis;
|
|
8
|
+
const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
9
|
+
/** base64url without padding. */
|
|
10
|
+
export function base64url(bytes) {
|
|
11
|
+
let out = '';
|
|
12
|
+
let i = 0;
|
|
13
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
14
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
15
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63] + B64URL[n & 63];
|
|
16
|
+
}
|
|
17
|
+
const rest = bytes.length - i;
|
|
18
|
+
if (rest === 1) {
|
|
19
|
+
const n = bytes[i] << 16;
|
|
20
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63];
|
|
21
|
+
}
|
|
22
|
+
else if (rest === 2) {
|
|
23
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
|
|
24
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63];
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
28
|
+
// prettier-ignore
|
|
29
|
+
const K = new Uint32Array([
|
|
30
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
31
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
32
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
33
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
34
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
35
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
36
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
37
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
38
|
+
]);
|
|
39
|
+
const ror = (x, n) => (x >>> n) | (x << (32 - n));
|
|
40
|
+
/**
|
|
41
|
+
* SHA-256 in plain JavaScript, for runtimes without `crypto.subtle` (React Native, or a page served over
|
|
42
|
+
* http:// from a LAN address, where browsers hide crypto.subtle).
|
|
43
|
+
*/
|
|
44
|
+
export function sha256Bytes(msg) {
|
|
45
|
+
const len = msg.length;
|
|
46
|
+
const padded = new Uint8Array(((len + 9 + 63) >> 6) << 6);
|
|
47
|
+
padded.set(msg);
|
|
48
|
+
padded[len] = 0x80;
|
|
49
|
+
const dv = new DataView(padded.buffer);
|
|
50
|
+
dv.setUint32(padded.length - 8, Math.floor(len / 0x20000000));
|
|
51
|
+
dv.setUint32(padded.length - 4, (len << 3) >>> 0);
|
|
52
|
+
const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
|
53
|
+
const W = new Uint32Array(64);
|
|
54
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
55
|
+
for (let i = 0; i < 16; i++)
|
|
56
|
+
W[i] = dv.getUint32(off + i * 4);
|
|
57
|
+
for (let i = 16; i < 64; i++) {
|
|
58
|
+
const a = W[i - 15];
|
|
59
|
+
const b = W[i - 2];
|
|
60
|
+
W[i] = (W[i - 16] + (ror(a, 7) ^ ror(a, 18) ^ (a >>> 3)) + W[i - 7] + (ror(b, 17) ^ ror(b, 19) ^ (b >>> 10))) >>> 0;
|
|
61
|
+
}
|
|
62
|
+
let a = H[0];
|
|
63
|
+
let b = H[1];
|
|
64
|
+
let c = H[2];
|
|
65
|
+
let d = H[3];
|
|
66
|
+
let e = H[4];
|
|
67
|
+
let f = H[5];
|
|
68
|
+
let gg = H[6];
|
|
69
|
+
let h = H[7];
|
|
70
|
+
for (let i = 0; i < 64; i++) {
|
|
71
|
+
const t1 = (h + (ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)) + ((e & f) ^ (~e & gg)) + K[i] + W[i]) >>> 0;
|
|
72
|
+
const t2 = ((ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
|
73
|
+
h = gg;
|
|
74
|
+
gg = f;
|
|
75
|
+
f = e;
|
|
76
|
+
e = (d + t1) >>> 0;
|
|
77
|
+
d = c;
|
|
78
|
+
c = b;
|
|
79
|
+
b = a;
|
|
80
|
+
a = (t1 + t2) >>> 0;
|
|
81
|
+
}
|
|
82
|
+
H[0] = (H[0] + a) >>> 0;
|
|
83
|
+
H[1] = (H[1] + b) >>> 0;
|
|
84
|
+
H[2] = (H[2] + c) >>> 0;
|
|
85
|
+
H[3] = (H[3] + d) >>> 0;
|
|
86
|
+
H[4] = (H[4] + e) >>> 0;
|
|
87
|
+
H[5] = (H[5] + f) >>> 0;
|
|
88
|
+
H[6] = (H[6] + gg) >>> 0;
|
|
89
|
+
H[7] = (H[7] + h) >>> 0;
|
|
90
|
+
}
|
|
91
|
+
const out = new Uint8Array(32);
|
|
92
|
+
const odv = new DataView(out.buffer);
|
|
93
|
+
for (let i = 0; i < 8; i++)
|
|
94
|
+
odv.setUint32(i * 4, H[i]);
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
/** The S256 challenge for a verifier: base64url(SHA-256(verifier)). Uses crypto.subtle when available. */
|
|
98
|
+
export async function challengeFor(verifier) {
|
|
99
|
+
const bytes = Uint8Array.from(verifier, (ch) => ch.charCodeAt(0) & 0xff); // verifiers are ASCII
|
|
100
|
+
const subtle = g.crypto?.subtle;
|
|
101
|
+
if (subtle && typeof subtle.digest === 'function') {
|
|
102
|
+
try {
|
|
103
|
+
return base64url(new Uint8Array(await subtle.digest('SHA-256', bytes)));
|
|
104
|
+
}
|
|
105
|
+
catch { }
|
|
106
|
+
}
|
|
107
|
+
return base64url(sha256Bytes(bytes));
|
|
108
|
+
}
|
|
109
|
+
/** True when this runtime has a secure random generator (needed for PKCE). */
|
|
110
|
+
export function canUsePkce() {
|
|
111
|
+
return typeof g.crypto?.getRandomValues === 'function';
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* A new verifier (32 random bytes → 43 characters) and its challenge. `null` when the runtime has no
|
|
115
|
+
* secure random generator (React Native without a crypto polyfill): then sign-in uses the older flow.
|
|
116
|
+
*/
|
|
117
|
+
export async function createPkcePair() {
|
|
118
|
+
if (!canUsePkce())
|
|
119
|
+
return null;
|
|
120
|
+
const bytes = new Uint8Array(32);
|
|
121
|
+
g.crypto.getRandomValues(bytes);
|
|
122
|
+
const verifier = base64url(bytes);
|
|
123
|
+
return { verifier, challenge: await challengeFor(verifier) };
|
|
124
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface StorageAdapter {
|
|
2
|
+
getItem(key: string): string | null | Promise<string | null>;
|
|
3
|
+
setItem(key: string, value: string): void | Promise<void>;
|
|
4
|
+
removeItem(key: string): void | Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
/** Keeps the session in memory only (lost when the page/process reloads). */
|
|
7
|
+
export declare function memoryStorage(): StorageAdapter;
|
|
8
|
+
/** localStorage in browsers (when it works), otherwise memory. */
|
|
9
|
+
export declare function defaultStorage(): StorageAdapter;
|
|
10
|
+
/**
|
|
11
|
+
* Keys written before the rename to usebecky start with "yb-" instead of "ub-". Reading a "ub-" key
|
|
12
|
+
* that is missing falls back to its "yb-" twin once, moves the value over and deletes the old key,
|
|
13
|
+
* so nobody is signed out by the rename.
|
|
14
|
+
*/
|
|
15
|
+
export declare function withLegacyKeys(storage: StorageAdapter): StorageAdapter;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Where the auth session is kept. Works with localStorage, React Native AsyncStorage
|
|
2
|
+
// (async methods are fine) or anything with getItem/setItem/removeItem.
|
|
3
|
+
/** Keeps the session in memory only (lost when the page/process reloads). */
|
|
4
|
+
export function memoryStorage() {
|
|
5
|
+
const map = new Map();
|
|
6
|
+
return {
|
|
7
|
+
getItem: (k) => map.get(k) ?? null,
|
|
8
|
+
setItem: (k, v) => {
|
|
9
|
+
map.set(k, v);
|
|
10
|
+
},
|
|
11
|
+
removeItem: (k) => {
|
|
12
|
+
map.delete(k);
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** localStorage in browsers (when it works), otherwise memory. */
|
|
17
|
+
export function defaultStorage() {
|
|
18
|
+
const g = globalThis;
|
|
19
|
+
if (typeof g.window === 'object' && g.window && typeof g.document === 'object') {
|
|
20
|
+
try {
|
|
21
|
+
const ls = g.localStorage;
|
|
22
|
+
if (ls) {
|
|
23
|
+
const probe = '__ub_probe__';
|
|
24
|
+
ls.setItem(probe, '1');
|
|
25
|
+
ls.removeItem(probe);
|
|
26
|
+
return {
|
|
27
|
+
getItem: (k) => {
|
|
28
|
+
try {
|
|
29
|
+
return ls.getItem(k);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
setItem: (k, v) => {
|
|
36
|
+
try {
|
|
37
|
+
ls.setItem(k, v);
|
|
38
|
+
}
|
|
39
|
+
catch { }
|
|
40
|
+
},
|
|
41
|
+
removeItem: (k) => {
|
|
42
|
+
try {
|
|
43
|
+
ls.removeItem(k);
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch { }
|
|
51
|
+
}
|
|
52
|
+
return memoryStorage();
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Keys written before the rename to usebecky start with "yb-" instead of "ub-". Reading a "ub-" key
|
|
56
|
+
* that is missing falls back to its "yb-" twin once, moves the value over and deletes the old key,
|
|
57
|
+
* so nobody is signed out by the rename.
|
|
58
|
+
*/
|
|
59
|
+
export function withLegacyKeys(storage) {
|
|
60
|
+
const legacyOf = (key) => (key.startsWith('ub-') ? `yb-${key.slice(3)}` : null);
|
|
61
|
+
const move = (key, old, value) => {
|
|
62
|
+
if (value === null || value === undefined)
|
|
63
|
+
return null;
|
|
64
|
+
try {
|
|
65
|
+
const saved = storage.setItem(key, value);
|
|
66
|
+
if (saved instanceof Promise)
|
|
67
|
+
saved.then(() => storage.removeItem(old)).catch(() => { });
|
|
68
|
+
else
|
|
69
|
+
Promise.resolve(storage.removeItem(old)).catch(() => { });
|
|
70
|
+
}
|
|
71
|
+
catch { }
|
|
72
|
+
return value;
|
|
73
|
+
};
|
|
74
|
+
const fromLegacy = (key, old) => {
|
|
75
|
+
const value = storage.getItem(old);
|
|
76
|
+
return value instanceof Promise ? value.then((v) => move(key, old, v)) : move(key, old, value);
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
getItem(key) {
|
|
80
|
+
const old = legacyOf(key);
|
|
81
|
+
const value = storage.getItem(key);
|
|
82
|
+
if (!old)
|
|
83
|
+
return value;
|
|
84
|
+
if (value instanceof Promise)
|
|
85
|
+
return value.then((v) => (v === null || v === undefined ? fromLegacy(key, old) : v));
|
|
86
|
+
return value === null || value === undefined ? fromLegacy(key, old) : value;
|
|
87
|
+
},
|
|
88
|
+
setItem: (key, value) => storage.setItem(key, value),
|
|
89
|
+
removeItem: (key) => storage.removeItem(key),
|
|
90
|
+
};
|
|
91
|
+
}
|