toiljs 0.0.131 → 0.0.134
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/CHANGELOG.md +18 -0
- package/build/backend/security.js +4 -2
- package/build/cli/index.js +9 -9
- package/build/client/auth.d.ts +14 -0
- package/build/client/auth.js +31 -4
- package/build/client/components/GoogleSignIn.d.ts +8 -0
- package/build/client/components/GoogleSignIn.js +57 -0
- package/build/client/index.d.ts +3 -1
- package/build/client/index.js +2 -1
- package/build/compiler/config.d.ts +3 -1
- package/build/compiler/config.js +3 -0
- package/build/compiler/security.d.ts +4 -3
- package/build/compiler/security.js +8 -7
- package/build/compiler/sri.js +2 -2
- package/build/compiler/toil-docs.generated.js +3 -1
- package/build/compiler/vite.js +1 -1
- package/build/devserver/http/runtime.d.ts +1 -1
- package/build/devserver/http/runtime.js +5 -5
- package/build/devserver/production.js +3 -3
- package/build/devserver/runtime/base64.d.ts +2 -0
- package/build/devserver/runtime/base64.js +39 -0
- package/build/devserver/runtime/crypto.d.ts +1 -1
- package/build/devserver/runtime/crypto.js +24 -0
- package/build/devserver/runtime/google.d.ts +9 -0
- package/build/devserver/runtime/google.js +157 -0
- package/build/devserver/runtime/host.js +6 -0
- package/build/devserver/runtime/module.d.ts +2 -0
- package/build/devserver/runtime/module.js +19 -0
- package/build/shared/index.d.ts +2 -1
- package/build/shared/index.js +1 -1
- package/build/shared/security.d.ts +4 -2
- package/build/shared/security.js +6 -2
- package/examples/basic/client/routes/google-login.tsx +132 -0
- package/package.json +19 -19
- package/server/auth/AuthController.ts +201 -61
- package/server/auth/AuthMaintenance.ts +1 -1
- package/server/auth/AuthRealm.ts +22 -0
- package/server/auth/AuthStateDb.ts +14 -0
- package/server/auth/AuthStore.ts +4 -0
- package/server/auth/Authenticator.ts +93 -0
- package/server/auth/FactorSettings.ts +9 -8
- package/server/auth/GoogleIdentity.ts +63 -0
- package/server/auth/SessionEpochs.ts +54 -12
- package/server/globals/auth.ts +51 -20
- package/server/globals.d.ts +6 -0
- package/server/runtime/envelope.ts +9 -7
- package/server/runtime/http/base64.ts +18 -98
- package/server/runtime/http/percent.ts +4 -0
- package/server/runtime/http/securecookies.ts +1 -1
- package/server/runtime/request.ts +3 -0
- package/std/server/http/base64.d.ts +2 -18
- package/std/server/http/securecookies.d.ts +1 -1
- package/std/server/request.d.ts +3 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createPublicKey, verify } from 'node:crypto';
|
|
2
|
+
const CERTS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
|
|
3
|
+
let keys = new Map();
|
|
4
|
+
let expires = 0;
|
|
5
|
+
let refreshAfter = 0;
|
|
6
|
+
let needsRefresh = false;
|
|
7
|
+
let pending;
|
|
8
|
+
export async function prepareGoogleKeys() {
|
|
9
|
+
if (pending)
|
|
10
|
+
return pending;
|
|
11
|
+
if ((!needsRefresh && Date.now() < expires) || Date.now() < refreshAfter)
|
|
12
|
+
return;
|
|
13
|
+
refreshAfter = Date.now() + 30_000;
|
|
14
|
+
pending = (async () => {
|
|
15
|
+
const response = await fetch(CERTS_URL, {
|
|
16
|
+
signal: AbortSignal.timeout(5000),
|
|
17
|
+
redirect: 'error',
|
|
18
|
+
});
|
|
19
|
+
if (!response.ok)
|
|
20
|
+
throw new Error('Google keys unavailable');
|
|
21
|
+
const reader = response.body?.getReader();
|
|
22
|
+
if (!reader)
|
|
23
|
+
throw new Error('Google keys unavailable');
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let size = 0;
|
|
26
|
+
try {
|
|
27
|
+
for (;;) {
|
|
28
|
+
const { done, value } = await reader.read();
|
|
29
|
+
if (done)
|
|
30
|
+
break;
|
|
31
|
+
size += value.length;
|
|
32
|
+
if (size > 65536)
|
|
33
|
+
throw new Error('Google keys too large');
|
|
34
|
+
chunks.push(value);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
await reader.cancel();
|
|
39
|
+
}
|
|
40
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
41
|
+
if (!Array.isArray(body.keys) || body.keys.length > 16)
|
|
42
|
+
throw new Error('Invalid Google keys');
|
|
43
|
+
const next = new Map();
|
|
44
|
+
for (const jwk of body.keys) {
|
|
45
|
+
if (jwk.kty !== 'RSA' ||
|
|
46
|
+
jwk.alg !== 'RS256' ||
|
|
47
|
+
jwk.use !== 'sig' ||
|
|
48
|
+
typeof jwk.kid !== 'string' ||
|
|
49
|
+
jwk.e !== 'AQAB')
|
|
50
|
+
continue;
|
|
51
|
+
const key = createPublicKey({ key: jwk, format: 'jwk' });
|
|
52
|
+
const bits = key.asymmetricKeyDetails?.modulusLength ?? 0;
|
|
53
|
+
if (bits < 2048 || bits > 4096)
|
|
54
|
+
continue;
|
|
55
|
+
next.set(jwk.kid, key);
|
|
56
|
+
}
|
|
57
|
+
if (!next.size)
|
|
58
|
+
throw new Error('Invalid Google keys');
|
|
59
|
+
keys = next;
|
|
60
|
+
needsRefresh = false;
|
|
61
|
+
const ttl = /(?:^|,)\s*max-age=(\d+)/i.exec(response.headers.get('cache-control') ?? '');
|
|
62
|
+
expires = Date.now() + Math.min(Number(ttl?.[1] ?? 300), 21600) * 1000;
|
|
63
|
+
})().finally(() => {
|
|
64
|
+
pending = undefined;
|
|
65
|
+
});
|
|
66
|
+
return pending;
|
|
67
|
+
}
|
|
68
|
+
export function verifyGoogleToken(token, audience, nonce) {
|
|
69
|
+
if (token.length > 16384 ||
|
|
70
|
+
!audience ||
|
|
71
|
+
audience.length > 256 ||
|
|
72
|
+
!nonce ||
|
|
73
|
+
nonce.length > 128 ||
|
|
74
|
+
Date.now() >= expires)
|
|
75
|
+
return null;
|
|
76
|
+
try {
|
|
77
|
+
const parts = token.split('.');
|
|
78
|
+
if (parts.length !== 3 || parts.some((p) => !/^[A-Za-z0-9_-]+$/.test(p)))
|
|
79
|
+
return null;
|
|
80
|
+
const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString());
|
|
81
|
+
if (header.alg !== 'RS256' || typeof header.kid !== 'string' || header.crit !== undefined)
|
|
82
|
+
return null;
|
|
83
|
+
const key = keys.get(header.kid);
|
|
84
|
+
if (!key) {
|
|
85
|
+
needsRefresh = true;
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (!verify('RSA-SHA256', Buffer.from(parts[0] + '.' + parts[1]), key, Buffer.from(parts[2], 'base64url')))
|
|
89
|
+
return null;
|
|
90
|
+
const c = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
|
|
91
|
+
const now = Math.floor(Date.now() / 1000);
|
|
92
|
+
if ((c.iss !== 'https://accounts.google.com' && c.iss !== 'accounts.google.com') ||
|
|
93
|
+
c.aud !== audience ||
|
|
94
|
+
(c.azp !== undefined && c.azp !== audience) ||
|
|
95
|
+
c.nonce !== nonce ||
|
|
96
|
+
c.email_verified !== true ||
|
|
97
|
+
typeof c.exp !== 'number' ||
|
|
98
|
+
!Number.isSafeInteger(c.exp) ||
|
|
99
|
+
c.exp <= now ||
|
|
100
|
+
(c.nbf !== undefined &&
|
|
101
|
+
(typeof c.nbf !== 'number' || !Number.isSafeInteger(c.nbf) || c.nbf > now + 30)) ||
|
|
102
|
+
typeof c.iat !== 'number' ||
|
|
103
|
+
!Number.isSafeInteger(c.iat) ||
|
|
104
|
+
c.iat > now + 30 ||
|
|
105
|
+
c.iat < now - 600 ||
|
|
106
|
+
typeof c.sub !== 'string' ||
|
|
107
|
+
!/^[A-Za-z0-9_-]{1,255}$/.test(c.sub) ||
|
|
108
|
+
typeof c.email !== 'string' ||
|
|
109
|
+
c.email.length > 254 ||
|
|
110
|
+
!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(c.email))
|
|
111
|
+
return null;
|
|
112
|
+
const email = c.email.toLowerCase();
|
|
113
|
+
return {
|
|
114
|
+
sub: c.sub, email, issuedAt: c.iat,
|
|
115
|
+
emailAuthoritative: email.endsWith('@gmail.com') || (typeof c.hd === 'string' && c.hd.length > 0),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
export function googleVerifyImport(ref, tp, tl, ap, al, np, nl, out, cap) {
|
|
123
|
+
const memory = ref.memory;
|
|
124
|
+
if (!memory ||
|
|
125
|
+
tl < 1 ||
|
|
126
|
+
tl > 16384 ||
|
|
127
|
+
al < 1 ||
|
|
128
|
+
al > 256 ||
|
|
129
|
+
nl < 1 ||
|
|
130
|
+
nl > 128 ||
|
|
131
|
+
cap < 0 ||
|
|
132
|
+
cap > 1024)
|
|
133
|
+
return -1;
|
|
134
|
+
const bytes = Buffer.from(memory.buffer);
|
|
135
|
+
for (const [ptr, len] of [
|
|
136
|
+
[tp, tl],
|
|
137
|
+
[ap, al],
|
|
138
|
+
[np, nl],
|
|
139
|
+
[out, cap],
|
|
140
|
+
])
|
|
141
|
+
if (ptr < 0 || ptr > bytes.length || len > bytes.length - ptr)
|
|
142
|
+
return -1;
|
|
143
|
+
const c = verifyGoogleToken(bytes.toString('utf8', tp, tp + tl), bytes.toString('utf8', ap, ap + al), bytes.toString('utf8', np, np + nl));
|
|
144
|
+
if (!c)
|
|
145
|
+
return -1;
|
|
146
|
+
const sub = Buffer.from(c.sub), email = Buffer.from(c.email);
|
|
147
|
+
const len = 17 + sub.length + email.length;
|
|
148
|
+
if (len > cap)
|
|
149
|
+
return -1;
|
|
150
|
+
bytes.writeUInt32LE(sub.length, out);
|
|
151
|
+
bytes.set(sub, out + 4);
|
|
152
|
+
bytes.writeUInt32LE(email.length, out + 4 + sub.length);
|
|
153
|
+
bytes.set(email, out + 8 + sub.length);
|
|
154
|
+
bytes.writeBigUInt64LE(BigInt(c.issuedAt), out + 8 + sub.length + email.length);
|
|
155
|
+
bytes[out + 16 + sub.length + email.length] = c.emailAuthoritative ? 1 : 0;
|
|
156
|
+
return len;
|
|
157
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { buildBase64Imports } from './base64.js';
|
|
2
|
+
import { googleVerifyImport } from './google.js';
|
|
1
3
|
import { buildImageImports, freshImageState } from '../images/index.js';
|
|
2
4
|
import { devEnvGet, devEnvGetSecure } from '../config/env.js';
|
|
3
5
|
import { ratelimitCheck } from '../config/ratelimit.js';
|
|
@@ -149,6 +151,7 @@ function buildLogImports(ref, db) {
|
|
|
149
151
|
}
|
|
150
152
|
export function buildEnvImports(ref, _state) {
|
|
151
153
|
return {
|
|
154
|
+
...buildBase64Imports(ref),
|
|
152
155
|
...buildLogImports(ref, _state.db),
|
|
153
156
|
...buildImageImports(ref, _state.images, () => _state.db.functionKind),
|
|
154
157
|
abort: (msgPtr, filePtr, line, col) => {
|
|
@@ -158,6 +161,7 @@ export function buildEnvImports(ref, _state) {
|
|
|
158
161
|
env_get_secure: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, true),
|
|
159
162
|
thread_spawn: (_startArg) => -1,
|
|
160
163
|
'Date.now': () => BigInt(ref.now?.() ?? Date.now()),
|
|
164
|
+
google_verify: (tp, tl, ap, al, np, nl, out, cap) => googleVerifyImport(ref, tp, tl, ap, al, np, nl, out, cap),
|
|
161
165
|
email_send: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
162
166
|
email_send_detached: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
163
167
|
};
|
|
@@ -165,6 +169,7 @@ export function buildEnvImports(ref, _state) {
|
|
|
165
169
|
export function buildHostImports(ref, state) {
|
|
166
170
|
return {
|
|
167
171
|
env: {
|
|
172
|
+
...buildBase64Imports(ref),
|
|
168
173
|
...buildLogImports(ref, state.db),
|
|
169
174
|
...buildImageImports(ref, state.images, () => state.db.functionKind),
|
|
170
175
|
abort: (msgPtr, filePtr, line, col) => {
|
|
@@ -214,6 +219,7 @@ export function buildHostImports(ref, state) {
|
|
|
214
219
|
const d = ratelimitCheck(routeId, strategy, limit, window, identity, Date.now());
|
|
215
220
|
return d.allowed ? 1 : -Math.max(1, d.retryAfterSecs);
|
|
216
221
|
},
|
|
222
|
+
google_verify: (tp, tl, ap, al, np, nl, out, cap) => googleVerifyImport(ref, tp, tl, ap, al, np, nl, out, cap),
|
|
217
223
|
email_send: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
218
224
|
email_send_detached: (reqPtr, reqLen) => devEmailSend(ref, reqPtr, reqLen),
|
|
219
225
|
env_get: (keyPtr, keyLen, outPtr, outCap) => envLookup(ref, keyPtr, keyLen, outPtr, outCap, false),
|
|
@@ -26,6 +26,7 @@ export interface DispatchInterleaving {
|
|
|
26
26
|
export declare class WasmServerModule {
|
|
27
27
|
private readonly wasmPath;
|
|
28
28
|
private module;
|
|
29
|
+
private usesGoogleVerification;
|
|
29
30
|
private loadedMtimeMs;
|
|
30
31
|
private routeKinds;
|
|
31
32
|
private rpcKinds;
|
|
@@ -37,6 +38,7 @@ export declare class WasmServerModule {
|
|
|
37
38
|
get available(): boolean;
|
|
38
39
|
refresh(): boolean;
|
|
39
40
|
dispatch(req: EnvelopeRequest): WasmDispatchResult;
|
|
41
|
+
dispatchWithNetwork(req: EnvelopeRequest): Promise<WasmDispatchResult>;
|
|
40
42
|
dispatchAsync(req: EnvelopeRequest, hooks?: DispatchInterleaving): Promise<WasmDispatchResult>;
|
|
41
43
|
private prepareDispatch;
|
|
42
44
|
private finishDispatch;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { devEnvGet } from '../config/env.js';
|
|
2
|
+
import { prepareGoogleKeys } from './google.js';
|
|
1
3
|
import { deriveChangesFrame, fullRescanFrame } from '../db/changes.js';
|
|
2
4
|
import { deriveContinuationKey, deriveCheckpointKey } from '../db/derives.js';
|
|
3
5
|
import fs from 'node:fs';
|
|
@@ -29,6 +31,8 @@ export function dbFunctionKindForRequest(routes, method, path) {
|
|
|
29
31
|
return routeKind === DbFunctionKind.Query ? DbFunctionKind.Query : dbKindForHttpMethod(method);
|
|
30
32
|
}
|
|
31
33
|
const PROVIDED_IMPORTS = new Set([
|
|
34
|
+
'codec.base64url_encode',
|
|
35
|
+
'codec.base64url_decode',
|
|
32
36
|
'abort',
|
|
33
37
|
'set_status',
|
|
34
38
|
'set_header',
|
|
@@ -38,6 +42,7 @@ const PROVIDED_IMPORTS = new Set([
|
|
|
38
42
|
'server_log',
|
|
39
43
|
'client_ip',
|
|
40
44
|
'ratelimit_check',
|
|
45
|
+
'google_verify',
|
|
41
46
|
'email_send',
|
|
42
47
|
'email_send_detached',
|
|
43
48
|
'env_get',
|
|
@@ -57,6 +62,7 @@ const PROVIDED_IMPORTS = new Set([
|
|
|
57
62
|
'crypto.verify',
|
|
58
63
|
'crypto.derive_bits',
|
|
59
64
|
'crypto.mldsa_verify',
|
|
65
|
+
'crypto.totp_verify',
|
|
60
66
|
'crypto.mlkem_decapsulate',
|
|
61
67
|
'crypto.voprf_evaluate',
|
|
62
68
|
'data.resolve_collection',
|
|
@@ -117,6 +123,7 @@ const PROVIDED_IMPORTS = new Set([
|
|
|
117
123
|
export class WasmServerModule {
|
|
118
124
|
wasmPath;
|
|
119
125
|
module = null;
|
|
126
|
+
usesGoogleVerification = false;
|
|
120
127
|
loadedMtimeMs = -1;
|
|
121
128
|
routeKinds = [];
|
|
122
129
|
rpcKinds = [];
|
|
@@ -138,6 +145,7 @@ export class WasmServerModule {
|
|
|
138
145
|
catch {
|
|
139
146
|
unregisterMaterializer(this.wasmPath);
|
|
140
147
|
this.module = null;
|
|
148
|
+
this.usesGoogleVerification = false;
|
|
141
149
|
this.routeKinds = [];
|
|
142
150
|
this.rpcKinds = [];
|
|
143
151
|
this.derives = [];
|
|
@@ -157,6 +165,7 @@ export class WasmServerModule {
|
|
|
157
165
|
this.rpcKinds = parseRpcKinds(bytes);
|
|
158
166
|
this.derives = parseDerives(bytes);
|
|
159
167
|
this.module = module;
|
|
168
|
+
this.usesGoogleVerification = WebAssembly.Module.imports(module).some(entry => entry.module === 'env' && entry.name === 'google_verify');
|
|
160
169
|
this.loadedMtimeMs = mtimeMs;
|
|
161
170
|
this.derivesDirty = this.derives.length > 0;
|
|
162
171
|
registerMaterializer(this.wasmPath, (written) => {
|
|
@@ -180,6 +189,16 @@ export class WasmServerModule {
|
|
|
180
189
|
throw error;
|
|
181
190
|
}
|
|
182
191
|
}
|
|
192
|
+
async dispatchWithNetwork(req) {
|
|
193
|
+
if (this.usesGoogleVerification && req.method === 'POST' &&
|
|
194
|
+
/^\/auth\/google\/login(?:\?|$)/.test(req.path) && devEnvGet('AUTH_GOOGLE_CLIENT_ID')) {
|
|
195
|
+
try {
|
|
196
|
+
await prepareGoogleKeys();
|
|
197
|
+
}
|
|
198
|
+
catch { }
|
|
199
|
+
}
|
|
200
|
+
return this.dispatch(req);
|
|
201
|
+
}
|
|
183
202
|
async dispatchAsync(req, hooks = {}) {
|
|
184
203
|
const jspi = WebAssembly;
|
|
185
204
|
if (typeof jspi.Suspending !== 'function' || typeof jspi.promising !== 'function')
|
package/build/shared/index.d.ts
CHANGED
|
@@ -15,4 +15,5 @@ export interface EmailBackendConfig {
|
|
|
15
15
|
readonly maxPerRecipientPerHour?: number;
|
|
16
16
|
readonly smtp?: SmtpBackendConfig;
|
|
17
17
|
}
|
|
18
|
-
export { DEFAULT_COOP, DEFAULT_CSP, contentSecurityPolicy, builtContentSecurityPolicy, withSecurityHeaders, } from './security.js';
|
|
18
|
+
export { DEFAULT_COOP, DEFAULT_CSP, contentSecurityPolicy, builtContentSecurityPolicy, builtCrossOriginOpenerPolicy, withSecurityHeaders, } from './security.js';
|
|
19
|
+
export type { CoopPolicy } from './security.js';
|
package/build/shared/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export const FRAMEWORK_NAME = 'toiljs';
|
|
2
|
-
export { DEFAULT_COOP, DEFAULT_CSP, contentSecurityPolicy, builtContentSecurityPolicy, withSecurityHeaders, } from './security.js';
|
|
2
|
+
export { DEFAULT_COOP, DEFAULT_CSP, contentSecurityPolicy, builtContentSecurityPolicy, builtCrossOriginOpenerPolicy, withSecurityHeaders, } from './security.js';
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
export
|
|
1
|
+
export type CoopPolicy = 'same-origin' | 'same-origin-allow-popups';
|
|
2
|
+
export declare const DEFAULT_COOP: CoopPolicy;
|
|
2
3
|
export declare function contentSecurityPolicy(scriptSources?: readonly string[], dev?: boolean, extraSources?: Readonly<Record<string, readonly string[]>>): string;
|
|
3
4
|
export declare const DEFAULT_CSP: string;
|
|
4
5
|
export declare function builtContentSecurityPolicy(html: string): string | null;
|
|
5
|
-
export declare function
|
|
6
|
+
export declare function builtCrossOriginOpenerPolicy(html: string): CoopPolicy;
|
|
7
|
+
export declare function withSecurityHeaders(headers: readonly (readonly [string, string])[], policy?: string, coop?: CoopPolicy): (readonly [string, string])[];
|
package/build/shared/security.js
CHANGED
|
@@ -68,13 +68,17 @@ export function builtContentSecurityPolicy(html) {
|
|
|
68
68
|
.replace(/'/g, "'")
|
|
69
69
|
.replace(/&/g, '&') ?? null);
|
|
70
70
|
}
|
|
71
|
-
export function
|
|
71
|
+
export function builtCrossOriginOpenerPolicy(html) {
|
|
72
|
+
return /<meta name="toil-coop" content="same-origin-allow-popups">/.test(html)
|
|
73
|
+
? 'same-origin-allow-popups' : DEFAULT_COOP;
|
|
74
|
+
}
|
|
75
|
+
export function withSecurityHeaders(headers, policy = DEFAULT_CSP, coop = DEFAULT_COOP) {
|
|
72
76
|
const out = [...headers];
|
|
73
77
|
if (!headers.some(([name]) => name.toLowerCase() === 'content-security-policy')) {
|
|
74
78
|
out.push(['content-security-policy', policy]);
|
|
75
79
|
}
|
|
76
80
|
if (!headers.some(([name]) => name.toLowerCase() === 'cross-origin-opener-policy')) {
|
|
77
|
-
out.push(['cross-origin-opener-policy',
|
|
81
|
+
out.push(['cross-origin-opener-policy', coop]);
|
|
78
82
|
}
|
|
79
83
|
return out;
|
|
80
84
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { useState } from 'react';
|
|
2
|
+
import { Auth, GoogleSignIn, TwoFactorRequiredError } from 'toiljs/client';
|
|
3
|
+
|
|
4
|
+
export const metadata: Toil.Metadata = { title: 'Google sign-in and Authenticator' };
|
|
5
|
+
|
|
6
|
+
/** Set AUTH_GOOGLE_CLIENT_ID and auth secrets as described in docs/auth/google-and-authenticator.md. */
|
|
7
|
+
export default function GoogleLogin(): React.JSX.Element {
|
|
8
|
+
const [message, setMessage] = useState('Sign in to manage your authenticator.');
|
|
9
|
+
const [challenge, setChallenge] = useState<string | null>(null);
|
|
10
|
+
const [signedIn, setSignedIn] = useState(false);
|
|
11
|
+
const [secret, setSecret] = useState<string | null>(null);
|
|
12
|
+
const [code, setCode] = useState('');
|
|
13
|
+
const [setup, setSetup] = useState(false);
|
|
14
|
+
const [retry, setRetry] = useState(0);
|
|
15
|
+
const [busy, setBusy] = useState(false);
|
|
16
|
+
const handleError = (error: unknown): void => {
|
|
17
|
+
if (error instanceof TwoFactorRequiredError) {
|
|
18
|
+
setChallenge(error.twoFaId);
|
|
19
|
+
setMessage('Enter the six-digit code from your authenticator or email.');
|
|
20
|
+
} else setMessage('Sign-in failed. Check the application configuration or retry.');
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const success = (): void => {
|
|
24
|
+
setSignedIn(true);
|
|
25
|
+
setChallenge(null);
|
|
26
|
+
setMessage('Signed in.');
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const verify = async (): Promise<void> => {
|
|
30
|
+
setBusy(true);
|
|
31
|
+
try {
|
|
32
|
+
if (challenge) {
|
|
33
|
+
await Auth.verifyTwoFactor(challenge, code);
|
|
34
|
+
success();
|
|
35
|
+
} else if (setup) {
|
|
36
|
+
await Auth.confirmTwoFactorSetup(code);
|
|
37
|
+
setSecret(null);
|
|
38
|
+
setSetup(false);
|
|
39
|
+
setSignedIn(false);
|
|
40
|
+
setRetry((n) => n + 1);
|
|
41
|
+
setMessage('Authenticator setting saved. Sign in again using a fresh code.');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
setCode('');
|
|
45
|
+
} catch {
|
|
46
|
+
setMessage('Code invalid, expired, or already used. Try a fresh code.');
|
|
47
|
+
} finally {
|
|
48
|
+
setBusy(false);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const enroll = async (): Promise<void> => {
|
|
53
|
+
setBusy(true);
|
|
54
|
+
try {
|
|
55
|
+
const result = await Auth.setupAuthenticator('Toil example', 'Your account');
|
|
56
|
+
setSecret(result.secret);
|
|
57
|
+
setSetup(true);
|
|
58
|
+
setMessage('Add this setup key to Google Authenticator, then enter its code.');
|
|
59
|
+
} catch {
|
|
60
|
+
setMessage('Unable to enroll. Disable the existing factor with its code first.');
|
|
61
|
+
} finally {
|
|
62
|
+
setBusy(false);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const disable = async (): Promise<void> => {
|
|
67
|
+
setBusy(true);
|
|
68
|
+
try {
|
|
69
|
+
await Auth.setupTwoFactor(Auth.TwoFactorMethod.None);
|
|
70
|
+
setSetup(true);
|
|
71
|
+
setSecret(null);
|
|
72
|
+
setMessage('Enter a fresh code from the current factor to disable it.');
|
|
73
|
+
} catch {
|
|
74
|
+
setMessage('Unable to start factor removal. Sign in and retry.');
|
|
75
|
+
} finally {
|
|
76
|
+
setBusy(false);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
return (
|
|
81
|
+
<main>
|
|
82
|
+
<h1>Google sign-in and Authenticator</h1>
|
|
83
|
+
<p role="status">{message}</p>
|
|
84
|
+
{!signedIn && !challenge && (
|
|
85
|
+
<>
|
|
86
|
+
<GoogleSignIn key={retry} onSuccess={success} onError={handleError} />
|
|
87
|
+
<button type="button" onClick={() => setRetry((n) => n + 1)}>
|
|
88
|
+
Retry sign-in
|
|
89
|
+
</button>
|
|
90
|
+
</>
|
|
91
|
+
)}
|
|
92
|
+
{signedIn && !setup && (
|
|
93
|
+
<>
|
|
94
|
+
<button type="button" disabled={busy} onClick={() => void enroll()}>
|
|
95
|
+
Set up Google Authenticator
|
|
96
|
+
</button>
|
|
97
|
+
<button type="button" disabled={busy} onClick={() => void disable()}>
|
|
98
|
+
Disable two-factor authentication
|
|
99
|
+
</button>
|
|
100
|
+
</>
|
|
101
|
+
)}
|
|
102
|
+
{secret && (
|
|
103
|
+
<p>
|
|
104
|
+
Setup key: <code>{secret}</code>
|
|
105
|
+
</p>
|
|
106
|
+
)}
|
|
107
|
+
{(challenge || setup) && (
|
|
108
|
+
<form
|
|
109
|
+
onSubmit={(event) => {
|
|
110
|
+
event.preventDefault();
|
|
111
|
+
void verify();
|
|
112
|
+
}}>
|
|
113
|
+
<label>
|
|
114
|
+
Verification code{' '}
|
|
115
|
+
<input
|
|
116
|
+
value={code}
|
|
117
|
+
onChange={(event) => setCode(event.target.value)}
|
|
118
|
+
inputMode="numeric"
|
|
119
|
+
autoComplete="one-time-code"
|
|
120
|
+
pattern="[0-9]{6}"
|
|
121
|
+
maxLength={6}
|
|
122
|
+
required
|
|
123
|
+
/>
|
|
124
|
+
</label>
|
|
125
|
+
<button type="submit" disabled={busy}>
|
|
126
|
+
Verify code
|
|
127
|
+
</button>
|
|
128
|
+
</form>
|
|
129
|
+
)}
|
|
130
|
+
</main>
|
|
131
|
+
);
|
|
132
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toiljs",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.134",
|
|
5
5
|
"author": "Dacely",
|
|
6
6
|
"description": "The modern React framework: a file-based React frontend and a ToilScript-compiled WebAssembly backend.",
|
|
7
7
|
"repository": {
|
|
@@ -159,27 +159,27 @@
|
|
|
159
159
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
160
160
|
"hash-wasm": "^4.12.0",
|
|
161
161
|
"juice": "^12.2.0",
|
|
162
|
-
"nodemailer": "^10.0
|
|
163
|
-
"oxc-parser": "^0.
|
|
164
|
-
"oxlint": "^1.
|
|
165
|
-
"oxlint-tsgolint": "^7.0.
|
|
162
|
+
"nodemailer": "^10.2.0",
|
|
163
|
+
"oxc-parser": "^0.155.0",
|
|
164
|
+
"oxlint": "^1.89.0",
|
|
165
|
+
"oxlint-tsgolint": "^7.0.2004",
|
|
166
166
|
"picocolors": "^1.1.1",
|
|
167
167
|
"semver": "^7.8.5",
|
|
168
168
|
"sharp": "^0.35.5",
|
|
169
169
|
"toilscript": ">=0.1.66",
|
|
170
|
-
"vite": "^8.3.
|
|
170
|
+
"vite": "^8.3.5",
|
|
171
171
|
"vite-imagetools": "^12.0.1",
|
|
172
172
|
"vite-plugin-node-polyfills": "^0.28.0"
|
|
173
173
|
},
|
|
174
174
|
"peerDependencies": {
|
|
175
175
|
"prettier": ">=3.0.0",
|
|
176
|
-
"react": "^19.3.
|
|
177
|
-
"react-dom": "^19.3.
|
|
176
|
+
"react": "^19.3.1",
|
|
177
|
+
"react-dom": "^19.3.1",
|
|
178
178
|
"toilscript": ">=0.1.66",
|
|
179
|
-
"vitest": "^5.0.
|
|
179
|
+
"vitest": "^5.0.5",
|
|
180
180
|
"@vitest/browser-webdriverio": "^5.0.0",
|
|
181
|
-
"@vitest/coverage-v8": "^5.0.
|
|
182
|
-
"webdriverio": "^10.0
|
|
181
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
182
|
+
"webdriverio": "^10.1.0"
|
|
183
183
|
},
|
|
184
184
|
"overrides": {
|
|
185
185
|
"elliptic": "file:./stubs/elliptic"
|
|
@@ -198,17 +198,17 @@
|
|
|
198
198
|
"@types/react-dom": "^19.3.0",
|
|
199
199
|
"@types/semver": "^7.8.0",
|
|
200
200
|
"@vitest/browser-webdriverio": "^5.0.0",
|
|
201
|
-
"@vitest/coverage-v8": "^5.0.
|
|
202
|
-
"@vitest/ui": "^5.0.
|
|
201
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
202
|
+
"@vitest/ui": "^5.0.5",
|
|
203
203
|
"esbuild": "^0.28.2",
|
|
204
|
-
"jsdom": "^30.1.
|
|
204
|
+
"jsdom": "^30.1.3",
|
|
205
205
|
"micromatch": "^4.0.8",
|
|
206
|
-
"prettier": "^3.9.
|
|
207
|
-
"react": "^19.3.
|
|
208
|
-
"react-dom": "^19.3.
|
|
206
|
+
"prettier": "^3.9.10",
|
|
207
|
+
"react": "^19.3.1",
|
|
208
|
+
"react-dom": "^19.3.1",
|
|
209
209
|
"typescript": "^7.0.2",
|
|
210
|
-
"vitest": "^5.0.
|
|
211
|
-
"webdriverio": "^10.0
|
|
210
|
+
"vitest": "^5.0.5",
|
|
211
|
+
"webdriverio": "^10.1.0"
|
|
212
212
|
},
|
|
213
213
|
"peerDependenciesMeta": {
|
|
214
214
|
"vitest": {
|