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.
Files changed (53) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/build/backend/security.js +4 -2
  3. package/build/cli/index.js +9 -9
  4. package/build/client/auth.d.ts +14 -0
  5. package/build/client/auth.js +31 -4
  6. package/build/client/components/GoogleSignIn.d.ts +8 -0
  7. package/build/client/components/GoogleSignIn.js +57 -0
  8. package/build/client/index.d.ts +3 -1
  9. package/build/client/index.js +2 -1
  10. package/build/compiler/config.d.ts +3 -1
  11. package/build/compiler/config.js +3 -0
  12. package/build/compiler/security.d.ts +4 -3
  13. package/build/compiler/security.js +8 -7
  14. package/build/compiler/sri.js +2 -2
  15. package/build/compiler/toil-docs.generated.js +3 -1
  16. package/build/compiler/vite.js +1 -1
  17. package/build/devserver/http/runtime.d.ts +1 -1
  18. package/build/devserver/http/runtime.js +5 -5
  19. package/build/devserver/production.js +3 -3
  20. package/build/devserver/runtime/base64.d.ts +2 -0
  21. package/build/devserver/runtime/base64.js +39 -0
  22. package/build/devserver/runtime/crypto.d.ts +1 -1
  23. package/build/devserver/runtime/crypto.js +24 -0
  24. package/build/devserver/runtime/google.d.ts +9 -0
  25. package/build/devserver/runtime/google.js +157 -0
  26. package/build/devserver/runtime/host.js +6 -0
  27. package/build/devserver/runtime/module.d.ts +2 -0
  28. package/build/devserver/runtime/module.js +19 -0
  29. package/build/shared/index.d.ts +2 -1
  30. package/build/shared/index.js +1 -1
  31. package/build/shared/security.d.ts +4 -2
  32. package/build/shared/security.js +6 -2
  33. package/examples/basic/client/routes/google-login.tsx +132 -0
  34. package/package.json +19 -19
  35. package/server/auth/AuthController.ts +201 -61
  36. package/server/auth/AuthMaintenance.ts +1 -1
  37. package/server/auth/AuthRealm.ts +22 -0
  38. package/server/auth/AuthStateDb.ts +14 -0
  39. package/server/auth/AuthStore.ts +4 -0
  40. package/server/auth/Authenticator.ts +93 -0
  41. package/server/auth/FactorSettings.ts +9 -8
  42. package/server/auth/GoogleIdentity.ts +63 -0
  43. package/server/auth/SessionEpochs.ts +54 -12
  44. package/server/globals/auth.ts +51 -20
  45. package/server/globals.d.ts +6 -0
  46. package/server/runtime/envelope.ts +9 -7
  47. package/server/runtime/http/base64.ts +18 -98
  48. package/server/runtime/http/percent.ts +4 -0
  49. package/server/runtime/http/securecookies.ts +1 -1
  50. package/server/runtime/request.ts +3 -0
  51. package/std/server/http/base64.d.ts +2 -18
  52. package/std/server/http/securecookies.d.ts +1 -1
  53. package/std/server/request.d.ts +3 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [v0.0.134] - 2026-10-22
4
+
5
+ - Include Google sign-in, Google Authenticator, and hardened session management. Deploy the matching updated toil-backend first; session format 3 requires users to sign in again.
6
+ - Upgrade all available runtime and development dependencies to current stable versions, refresh root and example lockfiles, and align generated app defaults and optional Sass tooling.
7
+ - Publish version tags using npm trusted publishing through GitHub OIDC, with the current npm toolchain and no token-based registry configuration.
8
+
9
+ ## [v0.0.133] - 2026-10-22
10
+
11
+ - Add Google Identity Services login and an official React sign-in button, with browser-bound nonces, offline token verification, bounded replay state, and existing sessions and two-factor controls.
12
+ - Add Google Authenticator-compatible TOTP enrollment, encrypted binary secrets, account-wide attempt limits, single-use codes, and safe factor changes. Optimize auth database calls and native codecs without weakening revocation races.
13
+ - Require owner-authoritative backend unique lookups so replication lag cannot hide revocation or factor claims.
14
+ - Harden factor changes with an atomic policy/revocation commit, conditional challenge updates, account-wide replacement limits, independent third-party email confirmation, and optional JWT not-before validation. Session format 3 requires users to sign in again and isolates security state by Host.
15
+ - Add `client.coop` for Google popup compatibility. Deploy the updated toil-backend first; see `docs/auth/google-and-authenticator.md` for configuration and runtime requirements.
16
+
17
+ ## [v0.0.132] - 2026-10-19
18
+
19
+ - Declare the compiler-provided `AuthUser` type and `__toildbResolve` collection resolver in the shipped server globals so editors recognize them without application shims or generated lint output. Preserve custom `@user` fields through the generated principal declarations.
20
+
3
21
  ## [v0.0.131] - 2026-10-19
4
22
 
5
23
  - Preserve the browser Host header through the development Vite proxy so application origin-specific response policies, including localhost popup handoffs, receive the public origin instead of the internal loopback address. Retain multiple Set-Cookie headers, manual redirects, binary bodies, and HEAD handling.
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { builtContentSecurityPolicy, withSecurityHeaders } from 'toiljs/shared';
3
+ import { builtContentSecurityPolicy, builtCrossOriginOpenerPolicy, withSecurityHeaders } from 'toiljs/shared';
4
4
  export function installSecurityHeaders(app) {
5
5
  app.use((_request, response, next) => {
6
6
  for (const [name, value] of withSecurityHeaders([]))
@@ -11,7 +11,9 @@ export function installSecurityHeaders(app) {
11
11
  export function sendSecureStaticFile(response, file) {
12
12
  if (/^\.html?$/i.test(path.extname(file))) {
13
13
  const body = fs.readFileSync(file);
14
- const policy = builtContentSecurityPolicy(body.toString('utf8'));
14
+ const html = body.toString('utf8');
15
+ const policy = builtContentSecurityPolicy(html);
16
+ response.header('cross-origin-opener-policy', builtCrossOriginOpenerPolicy(html), true);
15
17
  if (policy !== null)
16
18
  response.header('content-security-policy', policy, true);
17
19
  response.header('content-type', 'text/html; charset=utf-8', true);
@@ -3510,7 +3510,7 @@ var PREPROCESSOR_PKG = {
3510
3510
  };
3511
3511
  var TAILWIND_PKGS = ["tailwindcss", "@tailwindcss/vite"];
3512
3512
  var PKG_VERSION = {
3513
- sass: "^1.105.1",
3513
+ sass: "^1.106.1",
3514
3514
  less: "^4.9.1",
3515
3515
  stylus: "^0.64.0",
3516
3516
  tailwindcss: "^4.3.3",
@@ -4026,10 +4026,10 @@ import {
4026
4026
 
4027
4027
  // src/cli/testing.ts
4028
4028
  var TEST_DEPENDENCIES = {
4029
- vitest: "^5.0.3",
4029
+ vitest: "^5.0.5",
4030
4030
  "@vitest/browser-webdriverio": "^5.0.0",
4031
- "@vitest/coverage-v8": "^5.0.3",
4032
- webdriverio: "^10.0.2"
4031
+ "@vitest/coverage-v8": "^5.0.5",
4032
+ webdriverio: "^10.1.0"
4033
4033
  };
4034
4034
  var TEST_SCRIPTS = {
4035
4035
  test: "toiljs test",
@@ -4153,9 +4153,9 @@ function scaffold(name, template, features, aiTools, images) {
4153
4153
  ...TEST_DEPENDENCIES,
4154
4154
  "@types/react": "^19.3.0",
4155
4155
  "@types/react-dom": "^19.3.0",
4156
- oxlint: "^1.87.0",
4157
- "oxlint-tsgolint": "^7.0.2003",
4158
- prettier: "^3.9.9",
4156
+ oxlint: "^1.89.0",
4157
+ "oxlint-tsgolint": "^7.0.2004",
4158
+ prettier: "^3.9.10",
4159
4159
  toilscript: ">=0.1.66",
4160
4160
  typescript: "^7.0.2"
4161
4161
  };
@@ -4178,8 +4178,8 @@ function scaffold(name, template, features, aiTools, images) {
4178
4178
  },
4179
4179
  dependencies: {
4180
4180
  toiljs: `^${toilVersion}`,
4181
- react: "^19.3.0",
4182
- "react-dom": "^19.3.0"
4181
+ react: "^19.3.1",
4182
+ "react-dom": "^19.3.1"
4183
4183
  },
4184
4184
  devDependencies
4185
4185
  };
@@ -99,12 +99,22 @@ export declare class InvalidEmailError extends AuthError {
99
99
  export declare class InvalidUsernameError extends AuthError {
100
100
  constructor();
101
101
  }
102
+ export declare function googleLoginStart(opts?: AuthOptions): Promise<{
103
+ clientId: string;
104
+ nonce: string;
105
+ }>;
106
+ export declare function loginWithGoogle(credential: string, opts?: AuthOptions): Promise<Uint8Array>;
102
107
  export declare const TwoFactorMethod: {
103
108
  readonly None: 0;
104
109
  readonly Email: 1;
110
+ readonly Authenticator: 2;
105
111
  };
106
112
  export declare function verifyTwoFactor(twoFaId: string, code: string, opts?: AuthOptions): Promise<Uint8Array>;
107
113
  export declare function setupTwoFactor(method: number, opts?: AuthOptions): Promise<void>;
114
+ export declare function setupAuthenticator(issuer: string, account: string, opts?: AuthOptions, currentCode?: string): Promise<{
115
+ secret: string;
116
+ uri: string;
117
+ }>;
108
118
  export declare function confirmTwoFactorSetup(code: string, opts?: AuthOptions): Promise<void>;
109
119
  export declare function twoFactorStatus(opts?: AuthOptions): Promise<number>;
110
120
  export declare function confirmEmail(token: string, opts?: AuthOptions): Promise<void>;
@@ -122,11 +132,15 @@ export declare const Auth: {
122
132
  readonly resetPassword: typeof resetPassword;
123
133
  readonly verifyTwoFactor: typeof verifyTwoFactor;
124
134
  readonly setupTwoFactor: typeof setupTwoFactor;
135
+ readonly setupAuthenticator: typeof setupAuthenticator;
136
+ readonly googleLoginStart: typeof googleLoginStart;
137
+ readonly loginWithGoogle: typeof loginWithGoogle;
125
138
  readonly confirmTwoFactorSetup: typeof confirmTwoFactorSetup;
126
139
  readonly twoFactorStatus: typeof twoFactorStatus;
127
140
  readonly TwoFactorMethod: {
128
141
  readonly None: 0;
129
142
  readonly Email: 1;
143
+ readonly Authenticator: 2;
130
144
  };
131
145
  readonly buildLoginMessage: typeof buildLoginMessage;
132
146
  readonly LOGIN_CONTEXT: "qauth:login:v1";
@@ -345,7 +345,7 @@ export function isValidEmail(email) {
345
345
  return email.length >= 3 && email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
346
346
  }
347
347
  export function isValidUsername(username) {
348
- return username.length >= 1 && username.length <= 64;
348
+ return username.length >= 1 && username.length <= 64 && !username.startsWith('google_');
349
349
  }
350
350
  export class WeakPasswordError extends AuthError {
351
351
  unmet;
@@ -363,14 +363,29 @@ export class InvalidEmailError extends AuthError {
363
363
  }
364
364
  export class InvalidUsernameError extends AuthError {
365
365
  constructor() {
366
- super(AuthErrorCode.InvalidUsername, 'Username must be 1 to 64 characters.');
366
+ super(AuthErrorCode.InvalidUsername, 'Username must be 1 to 64 characters and cannot begin with google_.');
367
367
  this.name = 'InvalidUsernameError';
368
368
  }
369
369
  }
370
- export const TwoFactorMethod = { None: 0, Email: 1 };
370
+ export async function googleLoginStart(opts = {}) {
371
+ const r = await postBinary(opts.baseUrl ?? '/auth', '/google/start', new Uint8Array(0), opts);
372
+ return { clientId: r.readString(), nonce: r.readString() };
373
+ }
374
+ export async function loginWithGoogle(credential, opts = {}) {
375
+ const r = await postBinary(opts.baseUrl ?? '/auth', '/google/login', new DataWriter().writeString(credential).toBytes(), opts);
376
+ const status = r.readU8();
377
+ if (status === 3)
378
+ throw new TwoFactorRequiredError(toHex(r.readBytes()));
379
+ if (status === 2)
380
+ throw new EmailNotConfirmedError();
381
+ if (status !== 0)
382
+ throw new InvalidCredentialsError();
383
+ return r.readBytes();
384
+ }
385
+ export const TwoFactorMethod = { None: 0, Email: 1, Authenticator: 2 };
371
386
  export async function verifyTwoFactor(twoFaId, code, opts = {}) {
372
387
  const baseUrl = opts.baseUrl ?? '/auth';
373
- const res = await postBinary(baseUrl, '/2fa/verify', new DataWriter().writeBytes(fromHex(twoFaId)).writeString(code).toBytes());
388
+ const res = await postBinary(baseUrl, '/2fa/verify', new DataWriter().writeBytes(fromHex(twoFaId)).writeString(code).toBytes(), opts);
374
389
  if (res.readU8() !== 0)
375
390
  throw new TwoFactorCodeError();
376
391
  return res.readBytes();
@@ -381,6 +396,15 @@ export async function setupTwoFactor(method, opts = {}) {
381
396
  if (res.readU8() !== 0)
382
397
  throw new AuthError(AuthErrorCode.TwoFactorSetupFailed, 'Enabling or disabling two-factor failed.');
383
398
  }
399
+ export async function setupAuthenticator(issuer, account, opts = {}, currentCode = '') {
400
+ const res = await postBinary(opts.baseUrl ?? '/auth', '/2fa/setup', new DataWriter().writeU8(TwoFactorMethod.Authenticator).writeString(currentCode).toBytes(), opts);
401
+ if (res.readU8() !== 0)
402
+ throw new TwoFactorCodeError();
403
+ const secret = res.readString();
404
+ if (!/^[A-Z2-7]{32}$/.test(secret))
405
+ throw new TwoFactorCodeError();
406
+ return { secret, uri: `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=30` };
407
+ }
384
408
  export async function confirmTwoFactorSetup(code, opts = {}) {
385
409
  const baseUrl = opts.baseUrl ?? '/auth';
386
410
  const res = await postBinary(baseUrl, '/2fa/setup/verify', new DataWriter().writeString(code).toBytes(), opts);
@@ -470,6 +494,9 @@ export const Auth = {
470
494
  resetPassword,
471
495
  verifyTwoFactor,
472
496
  setupTwoFactor,
497
+ setupAuthenticator,
498
+ googleLoginStart,
499
+ loginWithGoogle,
473
500
  confirmTwoFactorSetup,
474
501
  twoFactorStatus,
475
502
  TwoFactorMethod,
@@ -0,0 +1,8 @@
1
+ import { type AuthOptions } from '../auth.js';
2
+ export interface GoogleSignInProps {
3
+ onSuccess: (session: Uint8Array) => void;
4
+ onError: (error: unknown) => void;
5
+ options?: AuthOptions;
6
+ className?: string;
7
+ }
8
+ export declare function GoogleSignIn({ onSuccess, onError, options, className, }: GoogleSignInProps): React.JSX.Element;
@@ -0,0 +1,57 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { googleLoginStart, loginWithGoogle } from '../auth.js';
4
+ import { Script } from './Script.js';
5
+ export function GoogleSignIn({ onSuccess, onError, options, className, }) {
6
+ const element = useRef(null);
7
+ const callbacks = useRef({ onSuccess, onError });
8
+ callbacks.current = { onSuccess, onError };
9
+ const [loaded, setLoaded] = useState(false);
10
+ const ready = useCallback(() => setLoaded(true), []);
11
+ const baseUrl = options?.baseUrl;
12
+ const headers = options?.headers;
13
+ const onRequestFailed = options?.onRequestFailed;
14
+ useEffect(() => {
15
+ if (!loaded || !element.current)
16
+ return;
17
+ let cancelled = false;
18
+ const parent = element.current;
19
+ void googleLoginStart({ baseUrl, headers, onRequestFailed })
20
+ .then(({ clientId, nonce }) => {
21
+ if (cancelled)
22
+ return;
23
+ const id = window.google
24
+ .accounts.id;
25
+ id.initialize({
26
+ client_id: clientId,
27
+ nonce,
28
+ use_fedcm_for_button: true,
29
+ callback({ credential }) {
30
+ if (cancelled)
31
+ return;
32
+ void loginWithGoogle(credential, {
33
+ baseUrl,
34
+ headers,
35
+ onRequestFailed,
36
+ }).then((session) => {
37
+ if (!cancelled)
38
+ callbacks.current.onSuccess(session);
39
+ }, (error) => {
40
+ if (!cancelled)
41
+ callbacks.current.onError(error);
42
+ });
43
+ },
44
+ });
45
+ id.renderButton(parent, { type: 'standard', theme: 'outline', size: 'large' });
46
+ })
47
+ .catch((error) => {
48
+ if (!cancelled)
49
+ callbacks.current.onError(error);
50
+ });
51
+ return () => {
52
+ cancelled = true;
53
+ parent.replaceChildren();
54
+ };
55
+ }, [loaded, baseUrl, headers, onRequestFailed]);
56
+ return (_jsxs(_Fragment, { children: [_jsx(Script, { src: "https://accounts.google.com/gsi/client", onReady: ready, onError: (error) => callbacks.current.onError(error) }), _jsx("div", { ref: element, className: className })] }));
57
+ }
@@ -1,6 +1,6 @@
1
1
  export { mount } from './routing/mount.js';
2
2
  export { Router } from './routing/Router.js';
3
- export { Auth, register as authRegister, login as authLogin, buildLoginMessage, LOGIN_CONTEXT, AuthError, AuthErrorCode, UsernameTakenError, EmailInUseError, InvalidCredentialsError, EmailNotConfirmedError, TwoFactorRequiredError, ServerAuthFailedError, TwoFactorCodeError, ConfirmationInvalidError, PasswordResetInvalidError, WeakPasswordError, InvalidEmailError, InvalidUsernameError, checkPassword, isValidEmail, isValidUsername, DEFAULT_PASSWORD_POLICY, PASSWORD_RULE_LABELS, SERVER_KEM_PUBLIC_KEY, } from './auth.js';
3
+ export { Auth, setupAuthenticator, googleLoginStart, loginWithGoogle, register as authRegister, login as authLogin, buildLoginMessage, LOGIN_CONTEXT, AuthError, AuthErrorCode, UsernameTakenError, EmailInUseError, InvalidCredentialsError, EmailNotConfirmedError, TwoFactorRequiredError, ServerAuthFailedError, TwoFactorCodeError, ConfirmationInvalidError, PasswordResetInvalidError, WeakPasswordError, InvalidEmailError, InvalidUsernameError, checkPassword, isValidEmail, isValidUsername, DEFAULT_PASSWORD_POLICY, PASSWORD_RULE_LABELS, SERVER_KEM_PUBLIC_KEY, } from './auth.js';
4
4
  export type { KdfParams, AuthOptions, PasswordPolicy, PasswordRule } from './auth.js';
5
5
  export { Link } from './navigation/Link.js';
6
6
  export type { LinkProps } from './navigation/Link.js';
@@ -43,3 +43,5 @@ export { parseError } from './errors.js';
43
43
  export { Hole, RawHtml, Repeat, Island, attr, __setSsrBuild, __isSsrBuild } from './ssr/markers.js';
44
44
  export type { HoleProps, RawHtmlProps, RepeatProps, IslandProps } from './ssr/markers.js';
45
45
  export { sanitizeHtml } from './html.js';
46
+ export { GoogleSignIn } from './components/GoogleSignIn.js';
47
+ export type { GoogleSignInProps } from './components/GoogleSignIn.js';
@@ -1,6 +1,6 @@
1
1
  export { mount } from './routing/mount.js';
2
2
  export { Router } from './routing/Router.js';
3
- export { Auth, register as authRegister, login as authLogin, buildLoginMessage, LOGIN_CONTEXT, AuthError, AuthErrorCode, UsernameTakenError, EmailInUseError, InvalidCredentialsError, EmailNotConfirmedError, TwoFactorRequiredError, ServerAuthFailedError, TwoFactorCodeError, ConfirmationInvalidError, PasswordResetInvalidError, WeakPasswordError, InvalidEmailError, InvalidUsernameError, checkPassword, isValidEmail, isValidUsername, DEFAULT_PASSWORD_POLICY, PASSWORD_RULE_LABELS, SERVER_KEM_PUBLIC_KEY, } from './auth.js';
3
+ export { Auth, setupAuthenticator, googleLoginStart, loginWithGoogle, register as authRegister, login as authLogin, buildLoginMessage, LOGIN_CONTEXT, AuthError, AuthErrorCode, UsernameTakenError, EmailInUseError, InvalidCredentialsError, EmailNotConfirmedError, TwoFactorRequiredError, ServerAuthFailedError, TwoFactorCodeError, ConfirmationInvalidError, PasswordResetInvalidError, WeakPasswordError, InvalidEmailError, InvalidUsernameError, checkPassword, isValidEmail, isValidUsername, DEFAULT_PASSWORD_POLICY, PASSWORD_RULE_LABELS, SERVER_KEM_PUBLIC_KEY, } from './auth.js';
4
4
  export { Link } from './navigation/Link.js';
5
5
  export { NavLink, matchActive } from './navigation/NavLink.js';
6
6
  export { navigate, back, forward, refresh, setViewTransitions, setTransitions, href, } from './navigation/navigation.js';
@@ -23,3 +23,4 @@ export { Server } from './rpc.js';
23
23
  export { parseError } from './errors.js';
24
24
  export { Hole, RawHtml, Repeat, Island, attr, __setSsrBuild, __isSsrBuild } from './ssr/markers.js';
25
25
  export { sanitizeHtml } from './html.js';
26
+ export { GoogleSignIn } from './components/GoogleSignIn.js';
@@ -1,5 +1,5 @@
1
1
  import { type InlineConfig } from 'vite';
2
- import { type EmailBackendConfig } from 'toiljs/shared';
2
+ import { type EmailBackendConfig, type CoopPolicy } from 'toiljs/shared';
3
3
  import { type SeoConfig } from './seo.js';
4
4
  export type { SeoConfig } from './seo.js';
5
5
  export type { EmailBackendConfig, SmtpBackendConfig } from 'toiljs/shared';
@@ -26,6 +26,7 @@ export interface ClientConfig {
26
26
  readonly host?: string;
27
27
  readonly images?: boolean;
28
28
  readonly fonts?: boolean;
29
+ readonly coop?: CoopPolicy;
29
30
  readonly cspSources?: Readonly<Record<string, readonly string[]>>;
30
31
  readonly viewTransitions?: boolean;
31
32
  readonly transitions?: boolean;
@@ -77,6 +78,7 @@ export interface ResolvedToilConfig {
77
78
  readonly host: string;
78
79
  readonly images: boolean;
79
80
  readonly fonts: boolean;
81
+ readonly coop?: CoopPolicy;
80
82
  readonly cspSources?: Readonly<Record<string, readonly string[]>>;
81
83
  readonly viewTransitions: boolean;
82
84
  readonly transitions: boolean;
@@ -35,6 +35,8 @@ export async function loadConfig(opts = {}) {
35
35
  }
36
36
  }
37
37
  const client = user.client ?? {};
38
+ if (client.coop !== undefined && !['same-origin', 'same-origin-allow-popups'].includes(client.coop))
39
+ throw new Error('client.coop must be same-origin or same-origin-allow-popups');
38
40
  const srcDir = client.srcDir ?? 'client';
39
41
  const routesDir = client.routesDir ?? 'routes';
40
42
  const clientAbsDir = path.join(root, srcDir);
@@ -53,6 +55,7 @@ export async function loadConfig(opts = {}) {
53
55
  host: opts.host ?? envHost() ?? client.host ?? '127.0.0.1',
54
56
  images: client.images ?? true,
55
57
  fonts: client.fonts ?? true,
58
+ coop: client.coop ?? 'same-origin',
56
59
  cspSources: client.cspSources ?? {},
57
60
  viewTransitions: client.viewTransitions ?? false,
58
61
  transitions: client.transitions ?? false,
@@ -1,7 +1,8 @@
1
1
  import type { Plugin } from 'vite';
2
- export declare function injectSecurityPolicy(html: string, policy: string): string;
3
- export declare function secureBuiltHtml(html: string, extraSources?: Readonly<Record<string, readonly string[]>>): {
2
+ import { type CoopPolicy } from 'toiljs/shared';
3
+ export declare function injectSecurityPolicy(html: string, policy: string, coop?: CoopPolicy): string;
4
+ export declare function secureBuiltHtml(html: string, extraSources?: Readonly<Record<string, readonly string[]>>, coop?: CoopPolicy): {
4
5
  html: string;
5
6
  policy: string;
6
7
  };
7
- export declare function devSecurityPlugin(extraSources?: Readonly<Record<string, readonly string[]>>): Plugin;
8
+ export declare function devSecurityPlugin(extraSources?: Readonly<Record<string, readonly string[]>>, coop?: CoopPolicy): Plugin;
@@ -4,8 +4,9 @@ import { contentSecurityPolicy, DEFAULT_COOP } from 'toiljs/shared';
4
4
  function escapeAttr(value) {
5
5
  return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
6
6
  }
7
- export function injectSecurityPolicy(html, policy) {
8
- const tags = `<meta name="toil-csp" content="${escapeAttr(policy)}">\n` +
7
+ export function injectSecurityPolicy(html, policy, coop = DEFAULT_COOP) {
8
+ const tags = (coop === DEFAULT_COOP ? '' : `<meta name="toil-coop" content="${coop}">\n`) +
9
+ `<meta name="toil-csp" content="${escapeAttr(policy)}">\n` +
9
10
  `<meta http-equiv="Content-Security-Policy" content="${escapeAttr(policy.replace(/frame-ancestors [^;]+; /, ''))}">`;
10
11
  const head = /<head\b[^>]*>/i.exec(html);
11
12
  const charset = head
@@ -18,7 +19,7 @@ export function injectSecurityPolicy(html, policy) {
18
19
  : 0;
19
20
  return html.slice(0, at) + '\n' + tags + html.slice(at);
20
21
  }
21
- export function secureBuiltHtml(html, extraSources = {}) {
22
+ export function secureBuiltHtml(html, extraSources = {}, coop = DEFAULT_COOP) {
22
23
  const sources = new Set();
23
24
  for (const match of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
24
25
  const attrs = match[1];
@@ -44,9 +45,9 @@ export function secureBuiltHtml(html, extraSources = {}) {
44
45
  }
45
46
  }
46
47
  const policy = contentSecurityPolicy([...sources], false, extraSources);
47
- return { html: injectSecurityPolicy(html, policy), policy };
48
+ return { html: injectSecurityPolicy(html, policy, coop), policy };
48
49
  }
49
- export function devSecurityPlugin(extraSources = {}) {
50
+ export function devSecurityPlugin(extraSources = {}, coop = DEFAULT_COOP) {
50
51
  const requestNonce = new AsyncLocalStorage();
51
52
  return {
52
53
  name: 'toil:security-dev',
@@ -55,7 +56,7 @@ export function devSecurityPlugin(extraSources = {}) {
55
56
  server.middlewares.use((_request, response, next) => {
56
57
  const nonce = randomBytes(24).toString('base64');
57
58
  response.setHeader('Content-Security-Policy', contentSecurityPolicy([`'nonce-${nonce}'`], true, extraSources));
58
- response.setHeader('Cross-Origin-Opener-Policy', DEFAULT_COOP);
59
+ response.setHeader('Cross-Origin-Opener-Policy', coop);
59
60
  requestNonce.run(nonce, next);
60
61
  });
61
62
  },
@@ -67,7 +68,7 @@ export function devSecurityPlugin(extraSources = {}) {
67
68
  const clean = attrs.replace(/\snonce(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?/gi, '');
68
69
  return `<script nonce="${nonce}"${clean}>`;
69
70
  });
70
- return injectSecurityPolicy(out, contentSecurityPolicy([`'nonce-${nonce}'`], true, extraSources));
71
+ return injectSecurityPolicy(out, contentSecurityPolicy([`'nonce-${nonce}'`], true, extraSources), coop);
71
72
  },
72
73
  },
73
74
  };
@@ -108,12 +108,12 @@ export function sriPlugin(cfg) {
108
108
  const importMap = buildImportMapIntegrity(outDir, cfg.base, cache);
109
109
  if (importMap !== null)
110
110
  out = injectImportMap(out, importMap);
111
- const secured = secureBuiltHtml(out, cfg.cspSources);
111
+ const secured = secureBuiltHtml(out, cfg.cspSources, cfg.coop);
112
112
  fs.writeFileSync(shell, secured.html);
113
113
  const headersFile = path.join(outDir, '_headers');
114
114
  const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf8') : '';
115
115
  fs.writeFileSync(headersFile, existing +
116
- `\n/*\n Content-Security-Policy: ${secured.policy}\n Cross-Origin-Opener-Policy: same-origin\n`);
116
+ `\n/*\n Content-Security-Policy: ${secured.policy}\n Cross-Origin-Opener-Policy: ${cfg.coop ?? 'same-origin'}\n`);
117
117
  },
118
118
  };
119
119
  }