@monetize.software/sdk-extension 0.1.0-alpha.0 → 3.0.0-alpha.2

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 CHANGED
@@ -1,14 +1,14 @@
1
1
  # @monetize.software/sdk-extension
2
2
 
3
- SDK для Chrome-расширений. Один offscreen-документ держит BillingClient,
4
- AuthClient, EventTracker — единственный source of truth для всех вкладок,
5
- popup'ов, side-panel'ов и extension-страниц расширения.
3
+ SDK for Chrome extensions. A single offscreen document holds the BillingClient,
4
+ AuthClient and EventTracker — the single source of truth for all tabs, popups,
5
+ side panels, and extension pages.
6
6
 
7
- Public API content-script **drop-in совместим** с `@monetize.software/sdk` —
8
- host пишет `import { PaywallUI } from '@monetize.software/sdk-extension'` и получает
9
- тот же класс, тот же метод-сет.
7
+ The content-script public API is **drop-in compatible** with `@monetize.software/sdk` —
8
+ the host writes `import { PaywallUI } from '@monetize.software/sdk-extension'` and
9
+ gets the same class with the same method set.
10
10
 
11
- ## Архитектура
11
+ ## Architecture
12
12
 
13
13
  ```
14
14
  content script (per tab) ──port──▶ service worker ──port──▶ offscreen
@@ -19,23 +19,23 @@ content script (per tab) ──port──▶ service worker ──port──▶
19
19
  UserWatcher
20
20
  ```
21
21
 
22
- - **content-script:** UI + RemoteBillingClient (proxy через port в offscreen).
23
- - **service worker:** маршрутизатор content↔offscreen, OAuth-флоу через
24
- `chrome.identity` (offscreen его не видит).
25
- - **offscreen:** реальный SDK state, переживает закрытие вкладок, единственная
26
- точка координации auth-refresh / trial-counter / analytics-batch.
22
+ - **content-script:** UI + RemoteBillingClient (proxy over a port into offscreen).
23
+ - **service worker:** content↔offscreen router; OAuth flow via `chrome.identity`
24
+ (offscreen can't access it directly).
25
+ - **offscreen:** the real SDK state, survives tab closes, the sole coordination
26
+ point for auth refresh / trial counter / analytics batching.
27
27
 
28
- ## Статус
28
+ ## Status
29
29
 
30
- Phase 0 — скелет: package.json, vite multi-entry, wire-protocol типы,
31
- заглушки на content/offscreen/sw + demo-extension манифест. Реальная
32
- маршрутизация и RemoteBillingClient следующие фазы.
30
+ Phase 0 — skeleton: package.json, vite multi-entry, wire-protocol types,
31
+ stubs for content/offscreen/sw and a demo-extension manifest. Actual routing
32
+ and `RemoteBillingClient` come in the next phases.
33
33
 
34
- См. TODO в репозитории и `src/shared/protocol.ts` для контракта сообщений.
34
+ See TODO in the repo and `src/shared/protocol.ts` for the message contract.
35
35
 
36
- ## Использование (целевое, в финале)
36
+ ## Usage (target shape, when complete)
37
37
 
38
- **В extension'е:**
38
+ **In the extension:**
39
39
 
40
40
  ```ts
41
41
  // service-worker.ts
@@ -50,18 +50,18 @@ startOffscreenServer({ paywallId: '...', apiOrigin: 'https://...' });
50
50
  ```
51
51
 
52
52
  ```ts
53
- // content-script.ts (на каждой вкладке)
53
+ // content-script.ts (in every tab)
54
54
  import { PaywallUI } from '@monetize.software/sdk-extension';
55
55
  const paywall = new PaywallUI({ paywallId: '...', apiOrigin: '...' });
56
- paywall.open(); // ровно как в @monetize.software/sdk
56
+ paywall.open(); // exactly like @monetize.software/sdk
57
57
  ```
58
58
 
59
- **На сайтах**продолжаем использовать `@monetize.software/sdk`, не меняется.
59
+ **On websites**keep using `@monetize.software/sdk`, nothing changes.
60
60
 
61
- ## Manifest: что прописывать в host extension
61
+ ## Manifest: what to declare in the host extension
62
62
 
63
- SDK сам по себе ничего в манифест не добавляет — host extension решает permissions
64
- под свой UX. Минимум для работы SDK:
63
+ The SDK itself does not add anything to the manifestthe host extension picks
64
+ permissions to match its own UX. Minimum for the SDK to work:
65
65
 
66
66
  ```json
67
67
  {
@@ -71,43 +71,43 @@ SDK сам по себе ничего в манифест не добавляе
71
71
  }
72
72
  ```
73
73
 
74
- Опционально:
74
+ Optional:
75
75
 
76
- - `"permissions": ["identity"]` — если включаете OAuth-флоу (`auth: true` + Google/etc.).
77
- - `web_accessible_resources` для `offscreen.html` **не нужен**документ создаётся
78
- service worker'ом через `chrome.offscreen.createDocument`, это chrome-API и WAR
79
- не требует. Указывать его лишняя attack surface (любой сайт сможет `<iframe>`-нить
80
- ваш offscreen, плюс это fingerprint вашего extension ID).
76
+ - `"permissions": ["identity"]` — if you enable OAuth flows (`auth: true` + Google/etc.).
77
+ - `web_accessible_resources` for `offscreen.html` is **not required** the
78
+ document is created by the service worker via `chrome.offscreen.createDocument`,
79
+ that's a Chrome API and doesn't need WAR. Listing it adds attack surface (any
80
+ site could `<iframe>` your offscreen, plus it fingerprints your extension ID).
81
81
 
82
- ### `host_permissions` — что выбрать
82
+ ### `host_permissions` — what to pick
83
83
 
84
- `host_permissions` управляют двумя вещами: куда extension может делать `fetch` (из
85
- offscreen / SW / content-script) и на какие origin'ы content-script может
86
- инжектиться (вместе с `content_scripts.matches`).
84
+ `host_permissions` control two things: where the extension can `fetch` (from
85
+ offscreen / SW / content-script) and which origins the content-script can be
86
+ injected into (together with `content_scripts.matches`).
87
87
 
88
- | Сценарий | Рекомендация |
88
+ | Scenario | Recommendation |
89
89
  |---|---|
90
- | **Host extension `<all_urls>` уже нужен** (рекордер, тулза-на-всех-сайтах, ассистент) | Оставляйте `<all_urls>`. SDK работает как есть. **Риск:** Chrome Web Store review для `<all_urls>` идёт через ручной audit и занимает дольше; AV-вендоры (Avast/Kaspersky/etc.) активнее метят такие расширения как PUA. Это «цена» широкого инжектане SDK'шный риск, а вашего use-case'а. |
91
- | **Host extension ходит только на ваш бекенд и paywall'ит свои фичи** (popup-tool, side-panel app) | НЕ ставьте `<all_urls>`. Достаточно вашего apiOrigin: `["https://api.your-domain.com/*"]`. Никакого content-script инжекта на все сайты не нужно. |
92
- | **Хотите гибрид** — popup-tool, но иногда content-script нужен на узком списке доменов | `host_permissions` + `content_scripts.matches` ограничьте до этих доменов: `["https://*.your-target.com/*", "https://api.your-domain.com/*"]`. |
90
+ | **Host extension already needs `<all_urls>`** (recorder, all-sites tool, assistant) | Keep `<all_urls>`. SDK works as-is. **Risk:** Chrome Web Store review for `<all_urls>` is a manual audit and takes longer; AV vendors (Avast/Kaspersky/etc.) are more likely to flag such extensions as PUA. That's the price of broad injection it's a property of your use case, not an SDK risk. |
91
+ | **Host extension only talks to your backend and gates its own features** (popup tool, side-panel app) | Do NOT request `<all_urls>`. Your `apiOrigin` is enough: `["https://api.your-domain.com/*"]`. No content-script injection on every site needed. |
92
+ | **Hybrid** — popup tool, but content-script needed on a narrow list of domains | Constrain both `host_permissions` and `content_scripts.matches` to those domains: `["https://*.your-target.com/*", "https://api.your-domain.com/*"]`. |
93
93
 
94
- Главный сигнал для CWS/AV: чем уже `host_permissions`, тем меньше подозрений.
95
- `<all_urls>` оставляйте только если он реально нужен для UX, и будьте готовы
96
- обосновать его в CWS review (поле "Permission justification").
94
+ The main signal to CWS/AV: the narrower `host_permissions`, the less suspicion.
95
+ Keep `<all_urls>` only when it's genuinely required for your UX, and be ready to
96
+ justify it in CWS review (the "Permission justification" field).
97
97
 
98
- ## Demo extension'а: build modes
98
+ ## Demo extension: build modes
99
99
 
100
- Для self-проверки и e2e-тестов есть `demo-extension/` — reference-imple­ментация.
101
- Билдов два:
100
+ For self-testing and e2e there's `demo-extension/` — a reference implementation.
101
+ Two builds are available:
102
102
 
103
103
  ```bash
104
- pnpm build:demo # production build (= шаблон, который можно копировать клиентам)
105
- pnpm build:demo:e2e # debug build — экспонирует window.__paywall для playwright'а
104
+ pnpm build:demo # production build (= the template clients can copy)
105
+ pnpm build:demo:e2e # debug build — exposes window.__paywall for Playwright
106
106
  ```
107
107
 
108
- `build:demo` НЕ кладёт `window.__paywall` в bundle (dead-code elimination через
109
- `import.meta.env.MODE !== 'e2e'`). Шаблон, который клиент копирует, остаётся
110
- чистым: любой script на странице иначе мог бы дёрнуть `paywall.open()` /
111
- `paywall.track()` и злоупотреблять чужим extension'ом.
108
+ `build:demo` does NOT put `window.__paywall` into the bundle (dead-code-eliminated
109
+ via `import.meta.env.MODE !== 'e2e'`). The template clients copy stays clean: any
110
+ script on the page could otherwise call `paywall.open()` / `paywall.track()` and
111
+ abuse someone else's extension.
112
112
 
113
- `pnpm dev:demo` собирает в e2e-режиме (для удобной отладки из DevTools-консоли).
113
+ `pnpm dev:demo` builds in e2e mode (handy for live debugging from the DevTools console).