@weft-framework/server 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
package/dist/oauth.js ADDED
@@ -0,0 +1,408 @@
1
+ import { isSecret } from "./secret.js";
2
+ import { base64url, fromBase64url } from "./security.js";
3
+ export class SignInError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "SignInError";
8
+ this.code = code;
9
+ }
10
+ }
11
+ const ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
12
+ const RESERVED = new Set([
13
+ "response_type",
14
+ "client_id",
15
+ "redirect_uri",
16
+ "scope",
17
+ "state",
18
+ "nonce",
19
+ "code_challenge",
20
+ "code_challenge_method",
21
+ ]);
22
+ const MAX_BODY = 1 << 20;
23
+ const SKEW_S = 60;
24
+ const JWKS_REFRESH_MS = 60_000;
25
+ const enc = new TextEncoder();
26
+ const dec = new TextDecoder("utf-8", { fatal: true });
27
+ function fail(message) {
28
+ throw new SignInError("failed", message);
29
+ }
30
+ function secretOf(s) {
31
+ return isSecret(s) ? s.reveal() : s;
32
+ }
33
+ export function checkEndpoint(raw, what) {
34
+ if (typeof raw !== "string") {
35
+ throw new Error(`sign-in: ${what} is missing`);
36
+ }
37
+ let u;
38
+ try {
39
+ u = new URL(raw);
40
+ }
41
+ catch {
42
+ throw new Error(`sign-in: ${what} is not a URL: ${raw}`);
43
+ }
44
+ const local = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
45
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
46
+ throw new Error(`sign-in: ${what} must use https: ${raw}`);
47
+ }
48
+ if (u.username || u.password) {
49
+ throw new Error(`sign-in: ${what} must not carry credentials`);
50
+ }
51
+ return u.href;
52
+ }
53
+ function checkCommon(o, fallbackId) {
54
+ const id = o.id ?? fallbackId;
55
+ if (typeof id !== "string" || !ID.test(id)) {
56
+ throw new Error(`sign-in: provider id ${JSON.stringify(id)} must be 1-32 lowercase letters, digits or -`);
57
+ }
58
+ if (typeof o.clientId !== "string" || o.clientId === "") {
59
+ throw new Error(`sign-in: ${id} needs a clientId`);
60
+ }
61
+ if (!isSecret(o.clientSecret) && (typeof o.clientSecret !== "string" || o.clientSecret === "")) {
62
+ throw new Error(`sign-in: ${id} needs a clientSecret`);
63
+ }
64
+ for (const key of Object.keys(o.params ?? {})) {
65
+ if (RESERVED.has(key)) {
66
+ throw new Error(`sign-in: ${id}: the parameter ${key} is set by the flow`);
67
+ }
68
+ }
69
+ for (const s of o.scopes ?? []) {
70
+ if (typeof s !== "string" || !/^[\x21\x23-\x5b\x5d-\x7e]+$/.test(s)) {
71
+ throw new Error(`sign-in: ${id}: bad scope ${JSON.stringify(s)}`);
72
+ }
73
+ }
74
+ const timeoutMs = o.timeoutMs ?? 10_000;
75
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
76
+ throw new Error(`sign-in: ${id}: timeoutMs is a positive number`);
77
+ }
78
+ return { id, label: o.label ?? fallbackId, fetch: o.fetch ?? ((i, init) => fetch(i, init)), timeoutMs };
79
+ }
80
+ async function json(f, url, init, timeoutMs, what) {
81
+ let res;
82
+ try {
83
+ res = await f(url, { ...init, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
84
+ }
85
+ catch (err) {
86
+ fail(`${what}: ${err.message}`);
87
+ }
88
+ const declared = Number(res.headers.get("content-length") ?? "0");
89
+ if (declared > MAX_BODY) {
90
+ await res.body?.cancel().catch(() => undefined);
91
+ fail(`${what}: response too large`);
92
+ }
93
+ const buf = new Uint8Array(await res.arrayBuffer());
94
+ if (buf.byteLength > MAX_BODY) {
95
+ fail(`${what}: response too large`);
96
+ }
97
+ let body;
98
+ try {
99
+ body = JSON.parse(dec.decode(buf));
100
+ }
101
+ catch {
102
+ fail(`${what}: HTTP ${res.status}, not JSON`);
103
+ }
104
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
105
+ fail(`${what}: HTTP ${res.status}, not a JSON object`);
106
+ }
107
+ const o = body;
108
+ if (!res.ok) {
109
+ const code = typeof o.error === "string" ? o.error.slice(0, 64) : "";
110
+ fail(`${what}: HTTP ${res.status}${code ? ` (${code})` : ""}`);
111
+ }
112
+ return o;
113
+ }
114
+ function str(v) {
115
+ return typeof v === "string" && v !== "" ? v : null;
116
+ }
117
+ export async function pkceChallenge(verifier) {
118
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(verifier))));
119
+ }
120
+ function authorizeUrl(endpoint, fields, extra) {
121
+ const u = new URL(endpoint);
122
+ for (const [k, v] of Object.entries(extra ?? {}))
123
+ u.searchParams.set(k, v);
124
+ for (const [k, v] of Object.entries(fields))
125
+ u.searchParams.set(k, v);
126
+ return u.href;
127
+ }
128
+ const ALGS = {
129
+ RS256: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verify: "RSASSA-PKCS1-v1_5" },
130
+ RS384: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-384" }, verify: "RSASSA-PKCS1-v1_5" },
131
+ RS512: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-512" }, verify: "RSASSA-PKCS1-v1_5" },
132
+ PS256: { import: { name: "RSA-PSS", hash: "SHA-256" }, verify: { name: "RSA-PSS", saltLength: 32 } },
133
+ ES256: { import: { name: "ECDSA", namedCurve: "P-256" }, verify: { name: "ECDSA", hash: "SHA-256" } },
134
+ ES384: { import: { name: "ECDSA", namedCurve: "P-384" }, verify: { name: "ECDSA", hash: "SHA-384" } },
135
+ };
136
+ function part(s, what) {
137
+ const raw = fromBase64url(s);
138
+ if (!raw)
139
+ fail(`ID token: bad ${what}`);
140
+ let v;
141
+ try {
142
+ v = JSON.parse(dec.decode(raw));
143
+ }
144
+ catch {
145
+ fail(`ID token: bad ${what}`);
146
+ }
147
+ if (typeof v !== "object" || v === null || Array.isArray(v))
148
+ fail(`ID token: bad ${what}`);
149
+ return v;
150
+ }
151
+ export async function verifyIdToken(token, o) {
152
+ if (typeof token !== "string" || token.length > 16_384)
153
+ fail("ID token: missing or too long");
154
+ const parts = token.split(".");
155
+ if (parts.length !== 3)
156
+ fail("ID token: not a signed JWT");
157
+ const header = part(parts[0], "header");
158
+ const alg = header.alg;
159
+ if (typeof alg !== "string" || !o.algs.includes(alg) || !(alg in ALGS)) {
160
+ fail(`ID token: algorithm ${JSON.stringify(alg)} is not allowed`);
161
+ }
162
+ if (header.crit !== undefined)
163
+ fail("ID token: critical header extensions are not supported");
164
+ const kid = typeof header.kid === "string" ? header.kid : null;
165
+ const jwk = await o.key(kid, alg);
166
+ if (!jwk)
167
+ fail("ID token: signed with an unknown key");
168
+ const spec = ALGS[alg];
169
+ let key;
170
+ try {
171
+ const { kid: _k, use: _u, alg: _a, key_ops: _o, ...material } = jwk;
172
+ key = await crypto.subtle.importKey("jwk", material, spec.import, false, ["verify"]);
173
+ }
174
+ catch {
175
+ fail("ID token: the provider's key does not fit its algorithm");
176
+ }
177
+ const sig = fromBase64url(parts[2]);
178
+ if (!sig)
179
+ fail("ID token: bad signature encoding");
180
+ const ok = await crypto.subtle.verify(spec.verify, key, new Uint8Array(sig), enc.encode(`${parts[0]}.${parts[1]}`));
181
+ if (!ok)
182
+ fail("ID token: bad signature");
183
+ const claims = part(parts[1], "claims");
184
+ const now = Math.floor((o.now ?? Date.now()) / 1000);
185
+ if (!o.issuer(claims.iss, claims))
186
+ fail("ID token: wrong issuer");
187
+ const aud = claims.aud;
188
+ const auds = Array.isArray(aud) ? aud : [aud];
189
+ if (!auds.includes(o.audience))
190
+ fail("ID token: not issued for this app");
191
+ if (auds.length > 1 && claims.azp !== o.audience)
192
+ fail("ID token: issued to another party");
193
+ if (claims.azp !== undefined && claims.azp !== o.audience)
194
+ fail("ID token: issued to another party");
195
+ if (typeof claims.exp !== "number" || claims.exp + SKEW_S < now)
196
+ fail("ID token: expired");
197
+ if (typeof claims.iat !== "number" || claims.iat - SKEW_S > now)
198
+ fail("ID token: issued in the future");
199
+ if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf - SKEW_S > now))
200
+ fail("ID token: not valid yet");
201
+ if (typeof claims.nonce !== "string" || claims.nonce !== o.nonce)
202
+ fail("ID token: nonce does not match");
203
+ if (typeof claims.sub !== "string" || claims.sub === "" || claims.sub.length > 255)
204
+ fail("ID token: no subject");
205
+ return claims;
206
+ }
207
+ function makeOidc(o, fallbackId, fallbackLabel, b = {}) {
208
+ const c = checkCommon(o, fallbackId);
209
+ const issuer = checkEndpoint(o.issuer, `${c.id} issuer`).replace(/\/$/, "");
210
+ const scopes = o.scopes ?? b.defaultScopes ?? ["openid", "email", "profile"];
211
+ if (!scopes.includes("openid")) {
212
+ throw new Error(`sign-in: ${c.id}: OpenID Connect needs the openid scope`);
213
+ }
214
+ let meta = null;
215
+ const metadata = () => {
216
+ meta ??= (async () => {
217
+ const m = await json(c.fetch, `${issuer}/.well-known/openid-configuration`, {}, c.timeoutMs, `${c.id} discovery`);
218
+ const ok = b.metadataIssuer ? b.metadataIssuer(m.issuer, issuer) : m.issuer === issuer;
219
+ if (!ok)
220
+ fail(`${c.id} discovery: the metadata is for another issuer`);
221
+ for (const k of ["authorization_endpoint", "token_endpoint", "jwks_uri"]) {
222
+ try {
223
+ checkEndpoint(m[k], `${c.id} ${k}`);
224
+ }
225
+ catch (err) {
226
+ fail(err.message);
227
+ }
228
+ }
229
+ return m;
230
+ })();
231
+ meta.catch(() => (meta = null));
232
+ return meta;
233
+ };
234
+ let keys = [];
235
+ let fetched = 0;
236
+ const refresh = async () => {
237
+ const m = await metadata();
238
+ const set = await json(c.fetch, m.jwks_uri, {}, c.timeoutMs, `${c.id} keys`);
239
+ keys = Array.isArray(set.keys) ? set.keys.filter((k) => typeof k === "object" && k !== null) : [];
240
+ fetched = Date.now();
241
+ };
242
+ const find = (kid, alg) => {
243
+ const kty = alg.startsWith("ES") ? "EC" : "RSA";
244
+ const usable = keys.filter((k) => k.kty === kty && (k.use === undefined || k.use === "sig") && (k.alg === undefined || k.alg === alg));
245
+ if (kid !== null)
246
+ return usable.find((k) => k.kid === kid) ?? null;
247
+ return usable.length === 1 ? usable[0] : null;
248
+ };
249
+ return {
250
+ id: c.id,
251
+ label: o.label ?? fallbackLabel,
252
+ async authorize(input) {
253
+ const m = await metadata();
254
+ return authorizeUrl(m.authorization_endpoint, {
255
+ response_type: "code",
256
+ client_id: o.clientId,
257
+ redirect_uri: input.redirectUri,
258
+ scope: scopes.join(" "),
259
+ state: input.state,
260
+ nonce: input.nonce,
261
+ code_challenge: input.challenge,
262
+ code_challenge_method: "S256",
263
+ }, o.params);
264
+ },
265
+ async identify(input) {
266
+ const m = await metadata();
267
+ const form = new URLSearchParams({
268
+ grant_type: "authorization_code",
269
+ code: input.code,
270
+ redirect_uri: input.redirectUri,
271
+ code_verifier: input.verifier,
272
+ });
273
+ const headers = {
274
+ "content-type": "application/x-www-form-urlencoded",
275
+ accept: "application/json",
276
+ };
277
+ const methods = m.token_endpoint_auth_methods_supported;
278
+ const secret = secretOf(o.clientSecret);
279
+ if (Array.isArray(methods) && methods.includes("client_secret_post") && !methods.includes("client_secret_basic")) {
280
+ form.set("client_id", o.clientId);
281
+ form.set("client_secret", secret);
282
+ }
283
+ else {
284
+ const user = encodeURIComponent(o.clientId);
285
+ headers.authorization = `Basic ${btoa(`${user}:${encodeURIComponent(secret)}`)}`;
286
+ }
287
+ const tokens = await json(c.fetch, m.token_endpoint, { method: "POST", headers, body: form.toString() }, c.timeoutMs, `${c.id} token`);
288
+ const supported = m.id_token_signing_alg_values_supported;
289
+ const algs = Array.isArray(supported) ? Object.keys(ALGS).filter((a) => supported.includes(a)) : ["RS256"];
290
+ const claims = await verifyIdToken(tokens.id_token, {
291
+ audience: o.clientId,
292
+ nonce: input.nonce,
293
+ algs,
294
+ issuer: (iss, all) => (b.issuer ? b.issuer(iss, all, issuer) : iss === issuer),
295
+ key: async (kid, alg) => {
296
+ if (fetched === 0)
297
+ await refresh();
298
+ let k = find(kid, alg);
299
+ if (!k && Date.now() - fetched > JWKS_REFRESH_MS) {
300
+ await refresh();
301
+ k = find(kid, alg);
302
+ }
303
+ return k;
304
+ },
305
+ });
306
+ const email = str(claims.email);
307
+ return Object.freeze({
308
+ provider: c.id,
309
+ subject: claims.sub,
310
+ email,
311
+ emailVerified: email !== null && (b.verified ? b.verified(claims) : claims.email_verified === true || claims.email_verified === "true"),
312
+ name: str(claims.name),
313
+ picture: str(claims.picture),
314
+ claims: Object.freeze(claims),
315
+ });
316
+ },
317
+ };
318
+ }
319
+ export function oidc(o) {
320
+ return makeOidc(o, o.id, o.id);
321
+ }
322
+ export function google(o) {
323
+ return makeOidc({ ...o, issuer: "https://accounts.google.com" }, "google", "Google");
324
+ }
325
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
326
+ export function microsoft(o) {
327
+ const tenant = o.tenant ?? "common";
328
+ if (!/^[A-Za-z0-9.-]{1,64}$/.test(tenant)) {
329
+ throw new Error(`sign-in: microsoft tenant ${JSON.stringify(tenant)} is not a tenant id or domain`);
330
+ }
331
+ const authority = (o.authority ?? "https://login.microsoftonline.com").replace(/\/$/, "");
332
+ const multi = tenant === "common" || tenant === "organizations" || tenant === "consumers";
333
+ const template = (expected) => expected.replace(`/${tenant}/`, "/{tenantid}/");
334
+ return makeOidc({ ...o, issuer: `${authority}/${tenant}/v2.0` }, "microsoft", "Microsoft", {
335
+ metadataIssuer: (found, expected) => found === expected || (multi && found === template(expected)),
336
+ issuer: (iss, claims, expected) => {
337
+ if (!multi)
338
+ return iss === expected;
339
+ const tid = claims.tid;
340
+ return typeof tid === "string" && GUID.test(tid) && iss === template(expected).replace("{tenantid}", tid);
341
+ },
342
+ verified: (claims) => claims.email_verified === true || claims.xms_edov === true,
343
+ });
344
+ }
345
+ export function github(o) {
346
+ const c = checkCommon(o, "github");
347
+ const base = checkEndpoint(o.baseUrl ?? "https://github.com", "github baseUrl").replace(/\/$/, "");
348
+ const api = checkEndpoint(o.apiUrl ?? (o.baseUrl ? `${base}/api/v3` : "https://api.github.com"), "github apiUrl").replace(/\/$/, "");
349
+ const scopes = o.scopes ?? ["read:user", "user:email"];
350
+ return {
351
+ id: c.id,
352
+ label: o.label ?? "GitHub",
353
+ async authorize(input) {
354
+ return authorizeUrl(`${base}/login/oauth/authorize`, {
355
+ client_id: o.clientId,
356
+ redirect_uri: input.redirectUri,
357
+ scope: scopes.join(" "),
358
+ state: input.state,
359
+ code_challenge: input.challenge,
360
+ code_challenge_method: "S256",
361
+ }, o.params);
362
+ },
363
+ async identify(input) {
364
+ const form = new URLSearchParams({
365
+ client_id: o.clientId,
366
+ client_secret: secretOf(o.clientSecret),
367
+ code: input.code,
368
+ redirect_uri: input.redirectUri,
369
+ code_verifier: input.verifier,
370
+ });
371
+ const tokens = await json(c.fetch, `${base}/login/oauth/access_token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, body: form.toString() }, c.timeoutMs, "github token");
372
+ if (typeof tokens.error === "string")
373
+ fail(`github token: ${tokens.error.slice(0, 64)}`);
374
+ const access = str(tokens.access_token);
375
+ if (!access)
376
+ fail("github token: no access token");
377
+ const headers = { authorization: `Bearer ${access}`, accept: "application/vnd.github+json", "user-agent": "weft-sign-in" };
378
+ const user = await json(c.fetch, `${api}/user`, { headers }, c.timeoutMs, "github user");
379
+ if (typeof user.id !== "number" || !Number.isSafeInteger(user.id))
380
+ fail("github user: no id");
381
+ let email = str(user.email);
382
+ let verified = false;
383
+ try {
384
+ const res = await c.fetch(`${api}/user/emails`, { headers, redirect: "error", signal: AbortSignal.timeout(c.timeoutMs) });
385
+ const text = res.ok ? await res.text() : "";
386
+ const list = text.length <= MAX_BODY && text ? JSON.parse(text) : [];
387
+ const primary = Array.isArray(list)
388
+ ? list.find((e) => e?.primary === true && e.verified === true)
389
+ : undefined;
390
+ if (primary && typeof primary.email === "string") {
391
+ email = primary.email;
392
+ verified = true;
393
+ }
394
+ }
395
+ catch {
396
+ }
397
+ return Object.freeze({
398
+ provider: c.id,
399
+ subject: String(user.id),
400
+ email,
401
+ emailVerified: verified,
402
+ name: str(user.name) ?? str(user.login),
403
+ picture: str(user.avatar_url),
404
+ claims: Object.freeze(user),
405
+ });
406
+ },
407
+ };
408
+ }
package/dist/otel.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { ErrorReport } from "./app.js";
2
+ import type { Secret } from "./secret.js";
3
+ export interface Telemetry {
4
+ startRequest(req: Request): TraceContext;
5
+ endRequest(t: TraceContext, info: {
6
+ method: string;
7
+ route?: string;
8
+ path: string;
9
+ status: number;
10
+ }): void;
11
+ error(err: unknown, report: ErrorReport, t: TraceContext | null): void;
12
+ span?(name: string, o?: SpanOptions): Span;
13
+ }
14
+ type Attr = string | number | boolean | undefined;
15
+ export interface SpanOptions {
16
+ kind?: "internal" | "consumer";
17
+ parent?: TraceContext | null;
18
+ attributes?: Record<string, Attr>;
19
+ elapsedMs?: number;
20
+ metric?: {
21
+ name: string;
22
+ attributes: Record<string, Attr>;
23
+ };
24
+ }
25
+ export interface Span {
26
+ readonly context: TraceContext;
27
+ end(o?: {
28
+ error?: unknown;
29
+ attributes?: Record<string, Attr>;
30
+ }): void;
31
+ }
32
+ export interface TraceContext {
33
+ traceId: string;
34
+ spanId: string;
35
+ parentSpanId?: string;
36
+ start: number;
37
+ }
38
+ export interface OtlpOptions {
39
+ endpoint: string;
40
+ headers?: Record<string, string | Secret>;
41
+ service: string;
42
+ resource?: Record<string, string | number | boolean>;
43
+ batchMs?: number;
44
+ maxBatch?: number;
45
+ maxQueue?: number;
46
+ metricsMs?: number;
47
+ maxSeries?: number;
48
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
49
+ onError?(err: unknown): void;
50
+ now?(): number;
51
+ }
52
+ export interface OtlpExporter extends Telemetry {
53
+ flush(): Promise<void>;
54
+ readonly dropped: number;
55
+ }
56
+ export declare function otlpExporter(o: OtlpOptions): OtlpExporter;
57
+ export {};