Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add option to controll request mode #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: add option to controll request mode
HofmannZ committed Nov 17, 2020
commit c62e99f26b6d1d95c395641f38baa5028b552cf5
46 changes: 28 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -23,13 +23,18 @@ Use the module if you are building your service worker [using a bundler](https:/
Example:

```js
import { registerRoute } from 'workbox-routing/registerRoute.mjs';
import { NetworkFirst } from 'workbox-strategies/NetworkFirst.mjs';
import { initializeFirebase, Plugin as FirebaseAuthPlugin } from 'workbox-plugin-firebase-auth';
import { registerRoute } from 'workbox-routing/registerRoute.mjs'
import { NetworkFirst } from 'workbox-strategies/NetworkFirst.mjs'
import {
initializeFirebase,
Plugin as FirebaseAuthPlugin,
} from 'workbox-plugin-firebase-auth'

initializeFirebase({
config: { /* your firebase config */ },
services: ['messaging']
config: {
/* your firebase config */
},
services: ['messaging'],
})

// `firebase` is now available in worker scope
@@ -40,11 +45,9 @@ Use the module if you are building your service worker [using a bundler](https:/
/\/api\/.*/,
new NetworkFirst({
cacheName: 'authorizedApi',
plugins: [
new FirebaseAuthPlugin(),
],
}),
);
plugins: [new FirebaseAuthPlugin()],
})
)
```

### CDN
@@ -61,8 +64,10 @@ importScripts(
)

WorkboxFirebaseAuth.initializeFirebase({
config: { /* your firebase config */ },
services: ['messaging']
config: {
/* your firebase config */
},
services: ['messaging'],
})

// `firebase` is now available in worker scope
@@ -73,10 +78,8 @@ workbox.routing.registerRoute(
/\/api\/.*/,
new workbox.strategies.NetworkFirst({
cacheName: 'authorizedApi',
plugins: [
new WorkboxFirebaseAuth.Plugin(),
],
}),
plugins: [new WorkboxFirebaseAuth.Plugin()],
})
)
```

@@ -95,7 +98,7 @@ The [firebase config object](https://firebase.google.com/docs/web/setup?authuser
### version

**Type:** `string` (Firebase version)
**Default:** `7.19.1`
**Default:** `8.0.2`

This option can be used to specify the firebase version to use.

@@ -156,12 +159,19 @@ Only allow requests to secure origins (`https://` or `localhost`) to be authoriz

Only allow requests to the same origin as the service worker to be authorized.

#### constraints.mode

**Type:** `'cors' | 'navigate' | 'no-cors' | 'same-origin'`
**Default:** `'same-origin'`

Set the request mode of the request by the plugin.s

#### constraints.ignorePaths

**Type:** `(string | RegExp)[]`
**Default:** `[]`

Paths to ignore when authorizing requests.
Paths to ignore when authorizing requests.

> **Note:** Checks against the pathname of the request (e.g. `/api/some-resource`)
> If the argument is a `string` a request will be ignored if the pathname starts with that `string`.
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -33,14 +33,14 @@
"@commitlint/config-conventional": "^9.1.2",
"@rollup/plugin-commonjs": "^15.0.0",
"@rollup/plugin-typescript": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^4.1.0",
"@typescript-eslint/eslint-plugin": "^4.8.0",
"@typescript-eslint/parser": "^4.1.0",
"cross-env": "^7.0.2",
"cz-conventional-changelog": "3.3.0",
"eslint": "^7.8.1",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.3",
"firebase": "^7.14.2",
"firebase": "^8.0.2",
"husky": "^4.2.5",
"lint-staged": "^10.2.2",
"prettier": "^2.0.5",
@@ -49,8 +49,8 @@
"rollup-plugin-strip-banner": "^2.0.0",
"rollup-plugin-terser": "^7.0.2",
"standard-version": "^9.0.0",
"typescript": "^4.0.2",
"workbox-core": "^5.1.3"
"typescript": "^4.0.5",
"workbox-core": "^5.1.4"
},
"config": {
"commitizen": {
22 changes: 15 additions & 7 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { WorkboxPlugin } from 'workbox-core'

declare const firebase: typeof import('firebase')
declare const firebase: typeof import('firebase').default

export interface FirebaseOptions {
version?: string
@@ -14,6 +14,7 @@ export interface Options {
types?: string | string[]
https?: boolean
sameOrigin?: boolean
mode?: RequestMode
ignorePaths?: (string | RegExp)[]
}
}
@@ -22,10 +23,11 @@ interface ResolvedConstraints {
types: string[]
https: boolean
sameOrigin: boolean
mode: RequestMode
ignorePaths: (string | RegExp)[]
}

const DEFAULT_FIREBASE_VERSION = '7.19.1'
const DEFAULT_FIREBASE_VERSION = '8.0.2'

const AVAILABLE_SERVICES = [
'analytics',
@@ -151,7 +153,11 @@ const shouldAuthorizeRequest = (
return isSameOrigin && hasCorrectType && isHttps && !isIgnored
}

const authorizeRequest = (original: Request, token: string): Request => {
const authorizeRequest = (
original: Request,
token: string,
constraints: ResolvedConstraints
): Request => {
// Clone headers as request headers are immutable.
const headers = new Headers()
original.headers.forEach((value, key) => {
@@ -165,7 +171,7 @@ const authorizeRequest = (original: Request, token: string): Request => {
const { url, ...props } = original.clone()
const authorized = new Request(url, {
...props,
mode: 'same-origin',
mode: constraints.mode,
redirect: 'manual',
headers,
})
@@ -180,11 +186,13 @@ export class Plugin implements WorkboxPlugin {
constructor(options: Options = {}) {
this.awaitResponse = options.awaitResponse || false

const { types, https, sameOrigin, ignorePaths } = options.constraints || {}
const { types, https, sameOrigin, mode, ignorePaths } =
options.constraints || {}
this.constraints = {
types: typeof types === 'string' ? [types] : types || ['*'],
https: !!https,
sameOrigin: typeof sameOrigin === 'boolean' ? sameOrigin : true,
mode: mode || 'same-origin',
ignorePaths: ignorePaths || [],
}
}
@@ -201,7 +209,7 @@ export class Plugin implements WorkboxPlugin {
const token = await getIdToken()
if (!token) return request

return authorizeRequest(request, token)
return authorizeRequest(request, token, this.constraints)
} catch (e) {
console.error(e)

@@ -225,7 +233,7 @@ export class Plugin implements WorkboxPlugin {
const token = await getIdToken()
if (!token) return response

const authorized = authorizeRequest(request, token)
const authorized = authorizeRequest(request, token, this.constraints)
return await fetch(authorized)
} catch (e) {
console.error(e)
Loading