@hanzo/app 0.2.27 → 0.2.29
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/dist/Betas.d.ts +4 -0
- package/dist/Betas.js +27 -6
- package/dist/SettingsPane.js +2 -1
- package/dist/Setup.d.ts +0 -6
- package/dist/Setup.js +18 -149
- package/dist/experimental.d.ts +7 -0
- package/dist/experimental.js +45 -0
- package/dist/lib/gmail.d.ts +61 -0
- package/dist/lib/gmail.js +310 -0
- package/dist/lib/optin.d.ts +36 -0
- package/dist/lib/optin.js +74 -0
- package/package.json +1 -1
package/dist/Betas.d.ts
CHANGED
|
@@ -4,6 +4,10 @@ export declare function useBetas(): {
|
|
|
4
4
|
open: (id: string) => boolean;
|
|
5
5
|
/** Whether they asked for it. */
|
|
6
6
|
asked: (id: string) => boolean;
|
|
7
|
+
/** Whether it is a public beta, one an admin promoted (lib/optin). */
|
|
8
|
+
promoted: (id: string) => boolean;
|
|
9
|
+
/** Their organization turned experimental features off. */
|
|
10
|
+
blocked: boolean;
|
|
7
11
|
/** Ask for these apps. */
|
|
8
12
|
request: (ids: string[]) => Promise<void>;
|
|
9
13
|
/** The cloud has answered for this reader. */
|
package/dist/Betas.js
CHANGED
|
@@ -13,6 +13,12 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
13
13
|
// stamped with the time and stated on the event plane under the person and the
|
|
14
14
|
// org, so the request reaches the team where it works the person.
|
|
15
15
|
//
|
|
16
|
+
// WHICH ARE PUBLIC is lib/optin's answer: a public beta is one an admin promoted,
|
|
17
|
+
// on for a reader who opted in to experimental features unless their
|
|
18
|
+
// organization turned that off. The cloud still says who is in, through the same
|
|
19
|
+
// GET /v1/flag/platform, so `opens` stays the one predicate; a public beta only
|
|
20
|
+
// reads as one, and says how to turn it on instead of asking for access.
|
|
21
|
+
//
|
|
16
22
|
// Signed out, still loading, or on any error nothing is open: a flags outage
|
|
17
23
|
// cannot leak an unfinished app.
|
|
18
24
|
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
|
|
@@ -24,7 +30,8 @@ import { Button, Dialog, DialogContent, DialogTitle, Text, XStack, YStack } from
|
|
|
24
30
|
import { api } from './lib/api.js';
|
|
25
31
|
import { BETAS, GROUPS, opens } from './lib/betas.js';
|
|
26
32
|
import { bearer, scope, superAdmin } from './lib/session.js';
|
|
27
|
-
|
|
33
|
+
import { CHANGED, optin } from './lib/optin.js';
|
|
34
|
+
const NONE = { flags: {}, asked: [], public: [], blocked: false };
|
|
28
35
|
/** A group's heading as the list draws it: authored English, drawn through `t`. */
|
|
29
36
|
const HEADING = {
|
|
30
37
|
Business: phrase('Business'),
|
|
@@ -52,9 +59,10 @@ function read(token) {
|
|
|
52
59
|
reading = Promise.all([
|
|
53
60
|
get('/v1/flag/platform').catch(() => null),
|
|
54
61
|
get('/v1/marketing/beta').catch(() => null),
|
|
62
|
+
optin().catch(() => null),
|
|
55
63
|
])
|
|
56
|
-
.then(([f, b]) => {
|
|
57
|
-
held = { token, said: { flags: f?.flags ?? {}, asked: b?.betas ?? [] }, at: Date.now() };
|
|
64
|
+
.then(([f, b, o]) => {
|
|
65
|
+
held = { token, said: { flags: f?.flags ?? {}, asked: b?.betas ?? [], public: o?.public ?? [], blocked: o?.blocked ?? false }, at: Date.now() };
|
|
58
66
|
})
|
|
59
67
|
.finally(() => {
|
|
60
68
|
reading = null;
|
|
@@ -82,9 +90,18 @@ export function useBetas() {
|
|
|
82
90
|
if (token && (!held || held.token !== token || Date.now() - held.at > FRESH))
|
|
83
91
|
void read(token);
|
|
84
92
|
}, [token]);
|
|
93
|
+
// A change of the opt-in changes what the cloud opens: read it all again.
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
if (!token)
|
|
96
|
+
return;
|
|
97
|
+
const again = () => void read(token);
|
|
98
|
+
window.addEventListener(CHANGED, again);
|
|
99
|
+
return () => window.removeEventListener(CHANGED, again);
|
|
100
|
+
}, [token]);
|
|
85
101
|
const said = token && now?.token === token ? now.said : NONE;
|
|
86
102
|
const open = useCallback((id) => opens(id, said.flags, sudo || local), [said, sudo, local]);
|
|
87
103
|
const asked = useCallback((id) => said.asked.includes(id), [said]);
|
|
104
|
+
const promoted = useCallback((id) => said.public.includes(id), [said]);
|
|
88
105
|
const request = useCallback(async (ids) => {
|
|
89
106
|
const r = await fetch(`${api()}/v1/marketing/beta/request`, {
|
|
90
107
|
method: 'POST',
|
|
@@ -99,7 +116,7 @@ export function useBetas() {
|
|
|
99
116
|
tell();
|
|
100
117
|
}
|
|
101
118
|
}, [token, t]);
|
|
102
|
-
return { open, asked, request, ready: Boolean(token) && now?.token === token };
|
|
119
|
+
return { open, asked, promoted, blocked: said.blocked, request, ready: Boolean(token) && now?.token === token };
|
|
103
120
|
}
|
|
104
121
|
/**
|
|
105
122
|
* Whether this page is served from a developer's own machine, where every app
|
|
@@ -115,12 +132,15 @@ function here() {
|
|
|
115
132
|
/** One app's action: Open where it may, Requested once asked, else Request access. */
|
|
116
133
|
function Ask({ beta, go }) {
|
|
117
134
|
const { t } = useI18n();
|
|
118
|
-
const { open, asked, request } = useBetas();
|
|
135
|
+
const { open, asked, promoted, blocked, request } = useBetas();
|
|
119
136
|
const [busy, setBusy] = useState(false);
|
|
120
137
|
const [wrong, setWrong] = useState(null);
|
|
121
138
|
if (open(beta.id)) {
|
|
122
139
|
return beta.href && go ? (_jsx(Button, { size: "sm", rounded: 999, onPress: () => go(beta.href), "data-slot": "beta-open", children: t('Open') })) : (_jsx(Text, { fontSize: "$2", color: "$color11", "data-slot": "beta-on", children: t('You’re in') }));
|
|
123
140
|
}
|
|
141
|
+
if (promoted(beta.id)) {
|
|
142
|
+
return (_jsx(Text, { fontSize: "$2", color: "$color11", text: "right", maxW: 200, "data-slot": "beta-optin", children: t(blocked ? 'Turned off by your organization' : 'Turn on experimental features in Settings') }));
|
|
143
|
+
}
|
|
124
144
|
if (asked(beta.id)) {
|
|
125
145
|
return (_jsx(Text, { fontSize: "$2", color: "$color11", "data-slot": "beta-requested", children: t('Requested') }));
|
|
126
146
|
}
|
|
@@ -135,7 +155,8 @@ function Ask({ beta, go }) {
|
|
|
135
155
|
/** Every app in beta, by group, each with its action. */
|
|
136
156
|
export function BetasList({ go }) {
|
|
137
157
|
const { t } = useI18n();
|
|
138
|
-
|
|
158
|
+
const { promoted } = useBetas();
|
|
159
|
+
return (_jsx(YStack, { gap: "$4", "data-slot": "betas", children: GROUPS.map((group) => (_jsxs(YStack, { gap: "$2", children: [_jsx(Text, { fontSize: "$1", color: "$color10", textTransform: "uppercase", letterSpacing: 0.6, children: t(HEADING[group]) }), BETAS.filter((b) => b.group === group).map((b) => (_jsxs(XStack, { items: "center", gap: "$3", "data-beta": b.id, children: [_jsxs(YStack, { flex: 1, minW: 0, children: [_jsxs(XStack, { items: "center", gap: "$2", children: [_jsx(Text, { fontSize: "$3", fontWeight: "500", children: b.name }), promoted(b.id) ? (_jsx(Text, { fontSize: "$1", color: "$color11", "data-slot": "beta-public", children: t('Public beta') })) : null] }), _jsx(Text, { fontSize: "$2", color: "$color11", children: t(b.line) })] }), _jsx(Ask, { beta: b, go: go })] }, b.id)))] }, group))) }));
|
|
139
160
|
}
|
|
140
161
|
/** The Betas list in a dialog, from the rail's More. */
|
|
141
162
|
export function BetasDialog({ open, onOpenChange, go }) {
|
package/dist/SettingsPane.js
CHANGED
|
@@ -26,6 +26,7 @@ import { showSettings } from './open.js';
|
|
|
26
26
|
import { Look } from './look.js';
|
|
27
27
|
import { ProviderMark } from './ProviderMark.js';
|
|
28
28
|
import { bearer, org, pick } from './lib/session.js';
|
|
29
|
+
import { Experimental } from './experimental.js';
|
|
29
30
|
import { site } from './where.js';
|
|
30
31
|
import { named, ROWS } from './Settings.js';
|
|
31
32
|
/** A choice among a few: a hairline edge and a corner. The fill and the edge's
|
|
@@ -49,7 +50,7 @@ function Pane({ id, note }) {
|
|
|
49
50
|
if (id === 'apps' || id === 'channels')
|
|
50
51
|
return _jsx(Catalog, { tab: id });
|
|
51
52
|
if (id === 'general')
|
|
52
|
-
return _jsx(Look, {});
|
|
53
|
+
return (_jsxs(YStack, { gap: "$5", children: [_jsx(Look, {}), _jsx(Experimental, {})] }));
|
|
53
54
|
if (id === 'account')
|
|
54
55
|
return _jsx(Account, {});
|
|
55
56
|
if (id === 'billing')
|
package/dist/Setup.d.ts
CHANGED
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
export declare const LATER_KEY = "hanzo.onboarding.later";
|
|
2
2
|
export declare const GITHUB_KEY = "hanzo.onboarding.github";
|
|
3
3
|
export declare const SLACK_KEY = "hanzo.onboarding.slack";
|
|
4
|
-
export declare const GOOGLE_KEY = "hanzo.onboarding.google.v2";
|
|
5
|
-
export declare const GOOGLE_ACCOUNTS_KEY = "hanzo.onboarding.google.accounts";
|
|
6
|
-
export declare const GOOGLE_TOKENS_KEY = "hanzo.onboarding.google.tokens";
|
|
7
4
|
export declare const STEP_KEY = "hanzo.onboarding.step";
|
|
8
|
-
export declare const DEFAULT_GOOGLE_CLIENT_ID = "113591532635-s8pvqrebprkbndluhftddmdap4htvu1p.apps.googleusercontent.com";
|
|
9
|
-
export declare const GOOGLE_WORKSPACE_SCOPES: string;
|
|
10
|
-
export declare function buildGoogleWorkspaceAuthorizeUrl(origin: string, clientId?: string, state?: string): string;
|
|
11
5
|
export declare function Setup(): import("react").JSX.Element;
|
package/dist/Setup.js
CHANGED
|
@@ -15,42 +15,15 @@ import { Check, Maximize2, Plus, Sparkles, X } from 'lucide-react';
|
|
|
15
15
|
import { ProviderMark } from './ProviderMark.js';
|
|
16
16
|
import { useKept } from './kept.js';
|
|
17
17
|
import { api } from './lib/api.js';
|
|
18
|
-
import { answers } from './lib/host.js';
|
|
19
18
|
import { scope } from './lib/session.js';
|
|
20
19
|
import { enter } from './lib/destination.js';
|
|
21
20
|
import { brand } from './where.js';
|
|
21
|
+
import { GOOGLE_ACCOUNTS_KEY, GOOGLE_KEY, accounts, connect, drop, keep } from './lib/gmail.js';
|
|
22
22
|
import { GOOD } from './lib/mix.js';
|
|
23
|
-
const here = () => typeof window !== 'undefined' && answers(window.location.hostname);
|
|
24
23
|
export const LATER_KEY = 'hanzo.onboarding.later';
|
|
25
24
|
export const GITHUB_KEY = 'hanzo.onboarding.github';
|
|
26
25
|
export const SLACK_KEY = 'hanzo.onboarding.slack';
|
|
27
|
-
export const GOOGLE_KEY = 'hanzo.onboarding.google.v2';
|
|
28
|
-
export const GOOGLE_ACCOUNTS_KEY = 'hanzo.onboarding.google.accounts';
|
|
29
|
-
export const GOOGLE_TOKENS_KEY = 'hanzo.onboarding.google.tokens';
|
|
30
26
|
export const STEP_KEY = 'hanzo.onboarding.step';
|
|
31
|
-
export const DEFAULT_GOOGLE_CLIENT_ID = '113591532635-s8pvqrebprkbndluhftddmdap4htvu1p.apps.googleusercontent.com';
|
|
32
|
-
export const GOOGLE_WORKSPACE_SCOPES = [
|
|
33
|
-
'openid',
|
|
34
|
-
'email',
|
|
35
|
-
'profile',
|
|
36
|
-
'https://www.googleapis.com/auth/drive',
|
|
37
|
-
'https://www.googleapis.com/auth/documents',
|
|
38
|
-
'https://www.googleapis.com/auth/spreadsheets',
|
|
39
|
-
'https://www.googleapis.com/auth/gmail.modify',
|
|
40
|
-
'https://www.googleapis.com/auth/calendar',
|
|
41
|
-
].join(' ');
|
|
42
|
-
export function buildGoogleWorkspaceAuthorizeUrl(origin, clientId = DEFAULT_GOOGLE_CLIENT_ID, state = 'gws') {
|
|
43
|
-
const cleanOrigin = origin.replace(/\/+$/, '');
|
|
44
|
-
const u = new URL('https://accounts.google.com/o/oauth2/v2/auth');
|
|
45
|
-
u.searchParams.set('client_id', clientId || DEFAULT_GOOGLE_CLIENT_ID);
|
|
46
|
-
u.searchParams.set('redirect_uri', `${cleanOrigin}/v1/iam/oauth/callback`);
|
|
47
|
-
u.searchParams.set('response_type', 'token');
|
|
48
|
-
u.searchParams.set('scope', GOOGLE_WORKSPACE_SCOPES);
|
|
49
|
-
u.searchParams.set('include_granted_scopes', 'true');
|
|
50
|
-
u.searchParams.set('prompt', 'select_account consent');
|
|
51
|
-
u.searchParams.set('state', state);
|
|
52
|
-
return u.toString();
|
|
53
|
-
}
|
|
54
27
|
/** Inline Slack Mark */
|
|
55
28
|
function SlackMark({ size = 18 }) {
|
|
56
29
|
return (_jsxs("svg", { width: size, height: size, viewBox: "0 0 54 54", fill: "none", "aria-hidden": true, children: [_jsx("path", { d: "M11.379 33.9993C11.379 37.1358 8.84512 39.6507 5.7276 39.6507C2.61008 39.6507 0.0572205 37.1168 0.0572205 33.9993C0.0572205 30.8817 2.5911 28.3479 5.70862 28.3479H11.36V33.9993H11.379Z", fill: "#E01E5A" }), _jsx("path", { d: "M14.1962 33.9997C14.1962 30.8632 16.7301 28.3483 19.8476 28.3483C22.9651 28.3483 25.499 30.8822 25.499 33.9997V48.1353C25.499 51.2718 22.9651 53.7867 19.8476 53.7867C16.7301 53.7867 14.1962 51.2718 14.1962 48.1353V33.9997Z", fill: "#E01E5A" }), _jsx("path", { d: "M19.8662 11.2673C16.7296 11.2673 14.2148 8.73347 14.2148 5.61594C14.2148 2.49842 16.7486 -0.0354538 19.8662 -0.0354538C22.9837 -0.0354538 25.5175 2.49842 25.5175 5.61594V11.2673H19.8662Z", fill: "#36C5F0" }), _jsx("path", { d: "M19.8682 14.1334C23.0047 14.1334 25.5196 16.6673 25.5196 19.7848C25.5196 22.9023 22.9857 25.4362 19.8682 25.4362H5.67566C2.53916 25.4362 0.0242615 22.9023 0.0242615 19.7848C0.0242615 16.6673 2.55814 14.1334 5.67566 14.1334H19.8682Z", fill: "#36C5F0" }), _jsx("path", { d: "M42.5323 19.7853C42.5323 16.6488 45.0662 14.1339 48.1837 14.1339C51.3012 14.1339 53.8351 16.6678 53.8351 19.7853C53.8351 22.9028 51.3012 25.4367 48.1837 25.4367H42.5323V19.7853Z", fill: "#2EB67D" }), _jsx("path", { d: "M39.7126 19.7934C39.7126 22.9299 37.1787 25.4448 34.0612 25.4448C30.9436 25.4448 28.4098 22.911 28.4098 19.7934V5.61986C28.4098 2.48336 30.9436 -0.0315399 34.0612 -0.0315399C37.1787 -0.0315399 39.7126 2.48336 39.7126 5.61986V19.7934Z", fill: "#2EB67D" }), _jsx("path", { d: "M34.0376 42.482C37.1741 42.482 39.689 45.0158 39.689 48.1334C39.689 51.2509 37.1552 53.7848 34.0376 53.7848C30.9201 53.7848 28.3862 51.2509 28.3862 48.1334V42.482H34.0376Z", fill: "#ECB22E" }), _jsx("path", { d: "M34.0381 39.6507C30.9016 39.6507 28.3867 37.1168 28.3867 33.9993C28.3867 30.8818 30.9206 28.3479 34.0381 28.3479H48.2306C51.3671 28.3479 53.882 30.8818 53.882 33.9993C53.882 37.1168 51.3482 39.6507 48.2306 39.6507H34.0381Z", fill: "#ECB22E" })] }));
|
|
@@ -71,48 +44,21 @@ export function Setup() {
|
|
|
71
44
|
const signed = isAuthenticated && Boolean(accessToken);
|
|
72
45
|
const accountList = Array.isArray(googleAccounts) ? googleAccounts : [];
|
|
73
46
|
const hasGoogle = googleDone || accountList.length > 0;
|
|
47
|
+
// The token itself is lib/gmail's to keep; Setup lists the addresses.
|
|
74
48
|
const addGoogleAccount = (rawEmail, tokenData) => {
|
|
49
|
+
if (tokenData?.accessToken)
|
|
50
|
+
keep(rawEmail, tokenData);
|
|
75
51
|
const clean = rawEmail.trim().toLowerCase();
|
|
76
52
|
const current = Array.isArray(googleAccounts) ? googleAccounts : [];
|
|
77
|
-
|
|
78
|
-
setGoogleAccounts(next);
|
|
53
|
+
setGoogleAccounts(clean && !current.includes(clean) ? [...current, clean] : current);
|
|
79
54
|
setGoogleDone(true);
|
|
80
|
-
if (typeof window !== 'undefined' && tokenData?.accessToken) {
|
|
81
|
-
try {
|
|
82
|
-
const rawTokens = window.localStorage.getItem(GOOGLE_TOKENS_KEY);
|
|
83
|
-
const parsed = rawTokens ? JSON.parse(rawTokens) : {};
|
|
84
|
-
parsed[clean || 'default'] = {
|
|
85
|
-
accessToken: tokenData.accessToken,
|
|
86
|
-
scope: tokenData.scope || GOOGLE_WORKSPACE_SCOPES,
|
|
87
|
-
connectedAt: new Date().toISOString(),
|
|
88
|
-
};
|
|
89
|
-
window.localStorage.setItem(GOOGLE_TOKENS_KEY, JSON.stringify(parsed));
|
|
90
|
-
}
|
|
91
|
-
catch {
|
|
92
|
-
// ignore storage errors
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
55
|
};
|
|
96
56
|
const removeGoogleAccount = (targetEmail) => {
|
|
97
|
-
|
|
98
|
-
const next =
|
|
57
|
+
drop(targetEmail);
|
|
58
|
+
const next = (Array.isArray(googleAccounts) ? googleAccounts : []).filter((a) => a !== targetEmail);
|
|
99
59
|
setGoogleAccounts(next);
|
|
100
|
-
if (next.length === 0)
|
|
60
|
+
if (next.length === 0)
|
|
101
61
|
setGoogleDone(false);
|
|
102
|
-
}
|
|
103
|
-
if (typeof window !== 'undefined') {
|
|
104
|
-
try {
|
|
105
|
-
const rawTokens = window.localStorage.getItem(GOOGLE_TOKENS_KEY);
|
|
106
|
-
if (rawTokens) {
|
|
107
|
-
const parsed = JSON.parse(rawTokens);
|
|
108
|
-
delete parsed[targetEmail];
|
|
109
|
-
window.localStorage.setItem(GOOGLE_TOKENS_KEY, JSON.stringify(parsed));
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
catch {
|
|
113
|
-
// ignore
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
62
|
};
|
|
117
63
|
// Sync with remote workspace integrations & connectors (never from IAM login linked-accounts,
|
|
118
64
|
// because basic IAM sign-in does not grant Google Drive/Docs/Sheets/Gmail/Calendar permissions).
|
|
@@ -221,34 +167,6 @@ export function Setup() {
|
|
|
221
167
|
const activeStep = step === 1 || step === 2 || step === 3 ? step : 1;
|
|
222
168
|
if (later && !modalOpen)
|
|
223
169
|
return null;
|
|
224
|
-
const completeGoogleToken = async (accessTokenValue, grantedScope, onDone) => {
|
|
225
|
-
let email = '';
|
|
226
|
-
try {
|
|
227
|
-
const userRes = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
|
|
228
|
-
headers: { Authorization: `Bearer ${accessTokenValue}` },
|
|
229
|
-
});
|
|
230
|
-
if (userRes.ok) {
|
|
231
|
-
const userJson = (await userRes.json());
|
|
232
|
-
if (typeof userJson?.email === 'string') {
|
|
233
|
-
email = userJson.email.trim().toLowerCase();
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
catch {
|
|
238
|
-
// best-effort userinfo fetch
|
|
239
|
-
}
|
|
240
|
-
addGoogleAccount(email, {
|
|
241
|
-
accessToken: accessTokenValue,
|
|
242
|
-
scope: grantedScope || GOOGLE_WORKSPACE_SCOPES,
|
|
243
|
-
});
|
|
244
|
-
// Best-effort custody sync with backend
|
|
245
|
-
fetch(`${api()}/v1/integrations/google/connect`, {
|
|
246
|
-
method: 'POST',
|
|
247
|
-
headers: { ...scope(), 'Content-Type': 'application/json' },
|
|
248
|
-
body: JSON.stringify({ token: accessTokenValue, accountId: email }),
|
|
249
|
-
}).catch(() => null);
|
|
250
|
-
onDone();
|
|
251
|
-
};
|
|
252
170
|
const openOAuthPopup = (authorizeUrl, provider, onDone) => {
|
|
253
171
|
const popup = window.open(authorizeUrl, `hanzo-oauth-${provider}`, 'width=600,height=700');
|
|
254
172
|
if (!popup) {
|
|
@@ -261,66 +179,9 @@ export function Setup() {
|
|
|
261
179
|
setSyncTurn((n) => n + 1);
|
|
262
180
|
return;
|
|
263
181
|
}
|
|
264
|
-
if (provider === 'google') {
|
|
265
|
-
try {
|
|
266
|
-
if (popup.location.origin === window.location.origin) {
|
|
267
|
-
const hash = popup.location.hash || '';
|
|
268
|
-
if (hash.includes('access_token=') || hash.includes('error=')) {
|
|
269
|
-
const params = new URLSearchParams(hash.replace(/^#/, ''));
|
|
270
|
-
const tokenVal = params.get('access_token');
|
|
271
|
-
const scopeVal = params.get('scope');
|
|
272
|
-
window.clearInterval(timer);
|
|
273
|
-
popup.close();
|
|
274
|
-
if (tokenVal) {
|
|
275
|
-
void completeGoogleToken(tokenVal, scopeVal, onDone);
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
catch {
|
|
281
|
-
// Cross-origin while user is on accounts.google.com; ignore until callback redirects to same origin
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
182
|
}, 250);
|
|
285
183
|
}
|
|
286
184
|
};
|
|
287
|
-
const resolveGoogleWorkspaceUrl = async () => {
|
|
288
|
-
let clientId = DEFAULT_GOOGLE_CLIENT_ID;
|
|
289
|
-
try {
|
|
290
|
-
const res = await fetch(`${api()}/v1/integrations/google/connect`, {
|
|
291
|
-
method: 'POST',
|
|
292
|
-
headers: { ...scope(), 'Content-Type': 'application/json' },
|
|
293
|
-
body: '{}',
|
|
294
|
-
}).catch(() => null);
|
|
295
|
-
if (res?.ok) {
|
|
296
|
-
const j = (await res.json().catch(() => null));
|
|
297
|
-
if (j?.authorizeUrl) {
|
|
298
|
-
try {
|
|
299
|
-
const parsed = new URL(j.authorizeUrl);
|
|
300
|
-
const cid = parsed.searchParams.get('client_id');
|
|
301
|
-
if (cid)
|
|
302
|
-
clientId = cid;
|
|
303
|
-
if (!here()) {
|
|
304
|
-
parsed.searchParams.set('scope', GOOGLE_WORKSPACE_SCOPES);
|
|
305
|
-
parsed.searchParams.set('access_type', 'offline');
|
|
306
|
-
parsed.searchParams.set('include_granted_scopes', 'true');
|
|
307
|
-
parsed.searchParams.set('prompt', 'select_account consent');
|
|
308
|
-
return parsed.toString();
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
catch {
|
|
312
|
-
// fall through
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
catch {
|
|
318
|
-
// fall through
|
|
319
|
-
}
|
|
320
|
-
const origin = typeof window !== 'undefined' ? window.location.origin : 'https://hanzo.ai';
|
|
321
|
-
const state = `gws_${Date.now().toString(36)}`;
|
|
322
|
-
return buildGoogleWorkspaceAuthorizeUrl(origin, clientId, state);
|
|
323
|
-
};
|
|
324
185
|
const connectOAuthProvider = async (provider, label, onDone) => {
|
|
325
186
|
if (!signed) {
|
|
326
187
|
enter();
|
|
@@ -330,8 +191,16 @@ export function Setup() {
|
|
|
330
191
|
setErrorMsg(null);
|
|
331
192
|
try {
|
|
332
193
|
if (provider === 'google') {
|
|
333
|
-
|
|
334
|
-
|
|
194
|
+
try {
|
|
195
|
+
await connect();
|
|
196
|
+
setGoogleAccounts(accounts());
|
|
197
|
+
setGoogleDone(true);
|
|
198
|
+
setSyncTurn((n) => n + 1);
|
|
199
|
+
onDone();
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
setErrorMsg(err instanceof Error ? err.message : t('Could not connect {provider} right now. Please try again.', { provider: label }));
|
|
203
|
+
}
|
|
335
204
|
return;
|
|
336
205
|
}
|
|
337
206
|
const res = await fetch(`${api()}/v1/integrations/${provider}/connect`, {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The opt-in to what is experimental (lib/optin): on, the reader gets every
|
|
3
|
+
* public beta; their team or organization can turn it off for everyone in it,
|
|
4
|
+
* and then the switch is held off with a note. Signed out there is nothing to
|
|
5
|
+
* choose, so nothing is drawn.
|
|
6
|
+
*/
|
|
7
|
+
export declare function Experimental(): import("react").JSX.Element;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// The General pane's switch for what is experimental (SettingsPane.tsx draws it
|
|
4
|
+
// under Look). Its own module so it is drawn and tested without the pane's world.
|
|
5
|
+
import { useEffect, useState } from 'react';
|
|
6
|
+
import { useI18n } from '@hanzo/i18n/react';
|
|
7
|
+
import { useIam } from '@hanzo/iam/react';
|
|
8
|
+
import { Switch, Text, XStack, YStack } from '@hanzo/ui';
|
|
9
|
+
import { opt, optin } from './lib/optin.js';
|
|
10
|
+
/**
|
|
11
|
+
* The opt-in to what is experimental (lib/optin): on, the reader gets every
|
|
12
|
+
* public beta; their team or organization can turn it off for everyone in it,
|
|
13
|
+
* and then the switch is held off with a note. Signed out there is nothing to
|
|
14
|
+
* choose, so nothing is drawn.
|
|
15
|
+
*/
|
|
16
|
+
export function Experimental() {
|
|
17
|
+
const { t } = useI18n();
|
|
18
|
+
const { isAuthenticated } = useIam();
|
|
19
|
+
const [held, setHeld] = useState(null);
|
|
20
|
+
const [busy, setBusy] = useState(false);
|
|
21
|
+
const [wrong, setWrong] = useState(null);
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
if (!isAuthenticated)
|
|
24
|
+
return;
|
|
25
|
+
let live = true;
|
|
26
|
+
optin()
|
|
27
|
+
.then((o) => live && setHeld(o))
|
|
28
|
+
.catch((e) => live && setWrong(e instanceof Error ? e.message : String(e)));
|
|
29
|
+
return () => {
|
|
30
|
+
live = false;
|
|
31
|
+
};
|
|
32
|
+
}, [isAuthenticated]);
|
|
33
|
+
if (!isAuthenticated)
|
|
34
|
+
return null;
|
|
35
|
+
const blocked = held?.blocked === true;
|
|
36
|
+
const title = t('Automatically opt-in for future experimental features');
|
|
37
|
+
return (_jsxs(YStack, { p: "$3", rounded: "$3", borderWidth: 1, borderColor: "$borderColor", gap: "$2", "data-slot": "optin", children: [_jsxs(XStack, { items: "center", justify: "space-between", gap: "$3", children: [_jsxs(YStack, { flex: 1, pr: "$2", children: [_jsx(Text, { fontSize: "$3", fontWeight: "600", color: "$ink", children: title }), _jsx(Text, { fontSize: "$2", color: "$soft", children: t('Automatically opt into new experimental features, unless disabled by your team or organization') })] }), _jsx(Switch, { "aria-label": title, checked: held?.on === true && !blocked, disabled: !held || busy || blocked, onCheckedChange: (on) => {
|
|
38
|
+
setBusy(true);
|
|
39
|
+
setWrong(null);
|
|
40
|
+
opt(on)
|
|
41
|
+
.then(setHeld)
|
|
42
|
+
.catch((e) => setWrong(e instanceof Error ? e.message : String(e)))
|
|
43
|
+
.finally(() => setBusy(false));
|
|
44
|
+
} })] }), blocked ? (_jsx(Text, { fontSize: "$2", color: "$soft", "data-slot": "optin-blocked", children: t('Turned off by your team or organization.') })) : null, wrong ? (_jsx(Text, { fontSize: "$2", color: "$red10", children: t(wrong) })) : null] }));
|
|
45
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gmail, from the browser: the Google Workspace token Setup's connect keeps,
|
|
3
|
+
* the consent that gets one, and one message sent with it.
|
|
4
|
+
*
|
|
5
|
+
* THE TOKEN NEVER LEAVES THIS BROWSER. Setup's connect is Google's browser
|
|
6
|
+
* consent (response_type=token): an access token of about an hour, no refresh,
|
|
7
|
+
* kept in localStorage under TOKENS as `{ [email]: { accessToken, scope,
|
|
8
|
+
* connectedAt, expiresAt? } }` (`default` when Google named no address), the
|
|
9
|
+
* addresses under ACCOUNTS. This module is the one reader and writer of both;
|
|
10
|
+
* Setup and the site's portal call it rather than the keys.
|
|
11
|
+
*
|
|
12
|
+
* WHICH ACCOUNT. `gmail(email)` answers the account the person chose; with no
|
|
13
|
+
* choice it answers the live one connected most recently, the token least
|
|
14
|
+
* likely to have run out. A token that may not send (its scope names neither
|
|
15
|
+
* gmail.modify, gmail.send nor the full mail scope) or that expires within a
|
|
16
|
+
* minute is no token: the answer is null and the person reconnects.
|
|
17
|
+
*/
|
|
18
|
+
export declare const GOOGLE_KEY = "hanzo.onboarding.google.v2";
|
|
19
|
+
export declare const GOOGLE_ACCOUNTS_KEY = "hanzo.onboarding.google.accounts";
|
|
20
|
+
export declare const GOOGLE_TOKENS_KEY = "hanzo.onboarding.google.tokens";
|
|
21
|
+
export declare const DEFAULT_GOOGLE_CLIENT_ID = "113591532635-s8pvqrebprkbndluhftddmdap4htvu1p.apps.googleusercontent.com";
|
|
22
|
+
export declare const GOOGLE_WORKSPACE_SCOPES: string;
|
|
23
|
+
/** The connected addresses, as Setup lists them. */
|
|
24
|
+
export declare function accounts(): string[];
|
|
25
|
+
/** Keep a token Google handed back for `email`, and list the address. */
|
|
26
|
+
export declare function keep(email: string, token: {
|
|
27
|
+
accessToken: string;
|
|
28
|
+
scope?: string;
|
|
29
|
+
expiresIn?: number;
|
|
30
|
+
}): void;
|
|
31
|
+
/** Forget `email`'s token and address. */
|
|
32
|
+
export declare function drop(email: string): void;
|
|
33
|
+
/** The live token that may send for `email`, or the most recently connected one; null when there is none. */
|
|
34
|
+
export declare function gmail(email?: string): {
|
|
35
|
+
token: string;
|
|
36
|
+
email?: string;
|
|
37
|
+
expires: number;
|
|
38
|
+
} | null;
|
|
39
|
+
/** Google's consent address for this origin. */
|
|
40
|
+
export declare function buildGoogleWorkspaceAuthorizeUrl(origin: string, clientId?: string, state?: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* Google's consent in a popup, the one Setup opens: resolves with the address
|
|
43
|
+
* once the token is kept, and refuses if the window closes without one or
|
|
44
|
+
* Google answers an error. A blocked popup opens the consent in a tab instead,
|
|
45
|
+
* and the token arrives through the site's callback (`message` below).
|
|
46
|
+
*/
|
|
47
|
+
export declare function connect(): Promise<string>;
|
|
48
|
+
/** One message to send. `from` is the connected address; Gmail fills it in when absent. */
|
|
49
|
+
export interface Message {
|
|
50
|
+
to: string;
|
|
51
|
+
subject: string;
|
|
52
|
+
text: string;
|
|
53
|
+
html: string;
|
|
54
|
+
from?: string;
|
|
55
|
+
}
|
|
56
|
+
/** The RFC 2822 message, multipart/alternative with the text and the HTML, as Gmail's `raw` (base64url, no padding). */
|
|
57
|
+
export declare function raw(m: Message, boundary?: string): string;
|
|
58
|
+
/** Send one message from the connected account. Every refusal is a sentence a person can act on. */
|
|
59
|
+
export declare function send(token: string, m: Message): Promise<{
|
|
60
|
+
id: string;
|
|
61
|
+
}>;
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gmail, from the browser: the Google Workspace token Setup's connect keeps,
|
|
3
|
+
* the consent that gets one, and one message sent with it.
|
|
4
|
+
*
|
|
5
|
+
* THE TOKEN NEVER LEAVES THIS BROWSER. Setup's connect is Google's browser
|
|
6
|
+
* consent (response_type=token): an access token of about an hour, no refresh,
|
|
7
|
+
* kept in localStorage under TOKENS as `{ [email]: { accessToken, scope,
|
|
8
|
+
* connectedAt, expiresAt? } }` (`default` when Google named no address), the
|
|
9
|
+
* addresses under ACCOUNTS. This module is the one reader and writer of both;
|
|
10
|
+
* Setup and the site's portal call it rather than the keys.
|
|
11
|
+
*
|
|
12
|
+
* WHICH ACCOUNT. `gmail(email)` answers the account the person chose; with no
|
|
13
|
+
* choice it answers the live one connected most recently, the token least
|
|
14
|
+
* likely to have run out. A token that may not send (its scope names neither
|
|
15
|
+
* gmail.modify, gmail.send nor the full mail scope) or that expires within a
|
|
16
|
+
* minute is no token: the answer is null and the person reconnects.
|
|
17
|
+
*/
|
|
18
|
+
import { phrase } from '@hanzo/i18n';
|
|
19
|
+
import { api } from './api.js';
|
|
20
|
+
import { answers } from './host.js';
|
|
21
|
+
import { scope } from './session.js';
|
|
22
|
+
export const GOOGLE_KEY = 'hanzo.onboarding.google.v2';
|
|
23
|
+
export const GOOGLE_ACCOUNTS_KEY = 'hanzo.onboarding.google.accounts';
|
|
24
|
+
export const GOOGLE_TOKENS_KEY = 'hanzo.onboarding.google.tokens';
|
|
25
|
+
export const DEFAULT_GOOGLE_CLIENT_ID = '113591532635-s8pvqrebprkbndluhftddmdap4htvu1p.apps.googleusercontent.com';
|
|
26
|
+
export const GOOGLE_WORKSPACE_SCOPES = [
|
|
27
|
+
'openid',
|
|
28
|
+
'email',
|
|
29
|
+
'profile',
|
|
30
|
+
'https://www.googleapis.com/auth/drive',
|
|
31
|
+
'https://www.googleapis.com/auth/documents',
|
|
32
|
+
'https://www.googleapis.com/auth/spreadsheets',
|
|
33
|
+
'https://www.googleapis.com/auth/gmail.modify',
|
|
34
|
+
'https://www.googleapis.com/auth/calendar',
|
|
35
|
+
].join(' ');
|
|
36
|
+
/** Google's own lifetime for a browser token, for one kept before `expiresAt` was. */
|
|
37
|
+
const LIFE = 3600_000;
|
|
38
|
+
/** A token this close to its end is treated as ended: a send must not race it. */
|
|
39
|
+
const MARGIN = 60_000;
|
|
40
|
+
/** The scopes that may send mail. */
|
|
41
|
+
const SENDS = ['https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.send', 'https://mail.google.com/'];
|
|
42
|
+
function storage() {
|
|
43
|
+
try {
|
|
44
|
+
return typeof window === 'undefined' ? null : window.localStorage;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function read(key, fallback) {
|
|
51
|
+
try {
|
|
52
|
+
const raw = storage()?.getItem(key);
|
|
53
|
+
return raw ? JSON.parse(raw) : fallback;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return fallback;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function write(key, value) {
|
|
60
|
+
try {
|
|
61
|
+
storage()?.setItem(key, JSON.stringify(value));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
/* no storage: the token lives as long as the page */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The connected addresses, as Setup lists them. */
|
|
68
|
+
export function accounts() {
|
|
69
|
+
const list = read(GOOGLE_ACCOUNTS_KEY, []);
|
|
70
|
+
return Array.isArray(list) ? list.filter((a) => typeof a === 'string') : [];
|
|
71
|
+
}
|
|
72
|
+
/** Keep a token Google handed back for `email`, and list the address. */
|
|
73
|
+
export function keep(email, token) {
|
|
74
|
+
const clean = email.trim().toLowerCase();
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const held = read(GOOGLE_TOKENS_KEY, {});
|
|
77
|
+
held[clean || 'default'] = {
|
|
78
|
+
accessToken: token.accessToken,
|
|
79
|
+
scope: token.scope || GOOGLE_WORKSPACE_SCOPES,
|
|
80
|
+
connectedAt: new Date(now).toISOString(),
|
|
81
|
+
expiresAt: new Date(now + (token.expiresIn && token.expiresIn > 0 ? token.expiresIn * 1000 : LIFE)).toISOString(),
|
|
82
|
+
};
|
|
83
|
+
write(GOOGLE_TOKENS_KEY, held);
|
|
84
|
+
const list = accounts();
|
|
85
|
+
if (clean && !list.includes(clean))
|
|
86
|
+
write(GOOGLE_ACCOUNTS_KEY, [...list, clean]);
|
|
87
|
+
write(GOOGLE_KEY, true);
|
|
88
|
+
}
|
|
89
|
+
/** Forget `email`'s token and address. */
|
|
90
|
+
export function drop(email) {
|
|
91
|
+
const held = read(GOOGLE_TOKENS_KEY, {});
|
|
92
|
+
delete held[email];
|
|
93
|
+
write(GOOGLE_TOKENS_KEY, held);
|
|
94
|
+
const list = accounts().filter((a) => a !== email);
|
|
95
|
+
write(GOOGLE_ACCOUNTS_KEY, list);
|
|
96
|
+
if (list.length === 0)
|
|
97
|
+
write(GOOGLE_KEY, false);
|
|
98
|
+
}
|
|
99
|
+
const ends = (h) => {
|
|
100
|
+
const at = Date.parse(h.expiresAt ?? '');
|
|
101
|
+
if (Number.isFinite(at))
|
|
102
|
+
return at;
|
|
103
|
+
const from = Date.parse(h.connectedAt ?? '');
|
|
104
|
+
return Number.isFinite(from) ? from + LIFE : 0;
|
|
105
|
+
};
|
|
106
|
+
const sends = (h) => {
|
|
107
|
+
const granted = (h.scope ?? '').split(/\s+/);
|
|
108
|
+
return SENDS.some((s) => granted.includes(s));
|
|
109
|
+
};
|
|
110
|
+
/** The live token that may send for `email`, or the most recently connected one; null when there is none. */
|
|
111
|
+
export function gmail(email) {
|
|
112
|
+
const held = read(GOOGLE_TOKENS_KEY, {});
|
|
113
|
+
const now = Date.now();
|
|
114
|
+
const live = Object.entries(held)
|
|
115
|
+
.filter(([, h]) => h && typeof h.accessToken === 'string' && h.accessToken && sends(h) && ends(h) - MARGIN > now)
|
|
116
|
+
.sort(([, a], [, b]) => (Date.parse(b.connectedAt ?? '') || 0) - (Date.parse(a.connectedAt ?? '') || 0));
|
|
117
|
+
const want = email?.trim().toLowerCase();
|
|
118
|
+
const hit = want ? live.find(([who]) => who === want) : live[0];
|
|
119
|
+
if (!hit)
|
|
120
|
+
return null;
|
|
121
|
+
const [who, h] = hit;
|
|
122
|
+
return { token: h.accessToken, email: who === 'default' ? undefined : who, expires: ends(h) };
|
|
123
|
+
}
|
|
124
|
+
/** Google's consent address for this origin. */
|
|
125
|
+
export function buildGoogleWorkspaceAuthorizeUrl(origin, clientId = DEFAULT_GOOGLE_CLIENT_ID, state = 'gws') {
|
|
126
|
+
const cleanOrigin = origin.replace(/\/+$/, '');
|
|
127
|
+
const u = new URL('https://accounts.google.com/o/oauth2/v2/auth');
|
|
128
|
+
u.searchParams.set('client_id', clientId || DEFAULT_GOOGLE_CLIENT_ID);
|
|
129
|
+
u.searchParams.set('redirect_uri', `${cleanOrigin}/v1/iam/oauth/callback`);
|
|
130
|
+
u.searchParams.set('response_type', 'token');
|
|
131
|
+
u.searchParams.set('scope', GOOGLE_WORKSPACE_SCOPES);
|
|
132
|
+
u.searchParams.set('include_granted_scopes', 'true');
|
|
133
|
+
u.searchParams.set('prompt', 'select_account consent');
|
|
134
|
+
u.searchParams.set('state', state);
|
|
135
|
+
return u.toString();
|
|
136
|
+
}
|
|
137
|
+
/** The consent address: the platform's client when it names one, else this origin's own. */
|
|
138
|
+
async function authorizeUrl() {
|
|
139
|
+
let clientId = DEFAULT_GOOGLE_CLIENT_ID;
|
|
140
|
+
try {
|
|
141
|
+
const res = await fetch(`${api()}/v1/integrations/google/connect`, {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
headers: { ...scope(), 'Content-Type': 'application/json' },
|
|
144
|
+
body: '{}',
|
|
145
|
+
});
|
|
146
|
+
if (res.ok) {
|
|
147
|
+
const j = (await res.json().catch(() => null));
|
|
148
|
+
if (j?.authorizeUrl) {
|
|
149
|
+
const parsed = new URL(j.authorizeUrl);
|
|
150
|
+
const cid = parsed.searchParams.get('client_id');
|
|
151
|
+
if (cid)
|
|
152
|
+
clientId = cid;
|
|
153
|
+
if (!answers(window.location.hostname)) {
|
|
154
|
+
parsed.searchParams.set('scope', GOOGLE_WORKSPACE_SCOPES);
|
|
155
|
+
parsed.searchParams.set('access_type', 'offline');
|
|
156
|
+
parsed.searchParams.set('include_granted_scopes', 'true');
|
|
157
|
+
parsed.searchParams.set('prompt', 'select_account consent');
|
|
158
|
+
return parsed.toString();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
/* the origin's own consent below */
|
|
165
|
+
}
|
|
166
|
+
return buildGoogleWorkspaceAuthorizeUrl(window.location.origin, clientId, `gws_${Date.now().toString(36)}`);
|
|
167
|
+
}
|
|
168
|
+
/** Keep the token, name its account, and tell the platform it was connected. */
|
|
169
|
+
async function complete(accessToken, granted, expiresIn) {
|
|
170
|
+
let email = '';
|
|
171
|
+
try {
|
|
172
|
+
const r = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', { headers: { Authorization: `Bearer ${accessToken}` } });
|
|
173
|
+
if (r.ok) {
|
|
174
|
+
const u = (await r.json());
|
|
175
|
+
if (typeof u?.email === 'string')
|
|
176
|
+
email = u.email.trim().toLowerCase();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
/* an unnamed account is kept as `default` */
|
|
181
|
+
}
|
|
182
|
+
keep(email, { accessToken, scope: granted || GOOGLE_WORKSPACE_SCOPES, expiresIn });
|
|
183
|
+
fetch(`${api()}/v1/integrations/google/connect`, {
|
|
184
|
+
method: 'POST',
|
|
185
|
+
headers: { ...scope(), 'Content-Type': 'application/json' },
|
|
186
|
+
body: JSON.stringify({ token: accessToken, accountId: email }),
|
|
187
|
+
}).catch(() => null);
|
|
188
|
+
return email;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Google's consent in a popup, the one Setup opens: resolves with the address
|
|
192
|
+
* once the token is kept, and refuses if the window closes without one or
|
|
193
|
+
* Google answers an error. A blocked popup opens the consent in a tab instead,
|
|
194
|
+
* and the token arrives through the site's callback (`message` below).
|
|
195
|
+
*/
|
|
196
|
+
export async function connect() {
|
|
197
|
+
if (typeof window === 'undefined')
|
|
198
|
+
throw new Error(phrase('Gmail can be connected only in a browser.'));
|
|
199
|
+
const url = await authorizeUrl();
|
|
200
|
+
const popup = window.open(url, 'hanzo-oauth-google', 'width=600,height=700');
|
|
201
|
+
return new Promise((resolve, reject) => {
|
|
202
|
+
let done = false;
|
|
203
|
+
let timer;
|
|
204
|
+
const finish = (fn) => {
|
|
205
|
+
if (done)
|
|
206
|
+
return;
|
|
207
|
+
done = true;
|
|
208
|
+
if (timer !== undefined)
|
|
209
|
+
window.clearInterval(timer);
|
|
210
|
+
window.removeEventListener('message', onMessage);
|
|
211
|
+
fn();
|
|
212
|
+
};
|
|
213
|
+
// The site's callback page posts the token it kept, whichever window it landed in.
|
|
214
|
+
const onMessage = (ev) => {
|
|
215
|
+
if (ev.origin !== window.location.origin)
|
|
216
|
+
return;
|
|
217
|
+
const data = ev.data;
|
|
218
|
+
if (data?.type === 'hanzo-google-workspace-connected')
|
|
219
|
+
finish(() => resolve((data.email ?? '').trim().toLowerCase()));
|
|
220
|
+
};
|
|
221
|
+
window.addEventListener('message', onMessage);
|
|
222
|
+
if (!popup) {
|
|
223
|
+
window.open(url, '_blank', 'noopener,noreferrer');
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
timer = window.setInterval(() => {
|
|
227
|
+
if (popup.closed) {
|
|
228
|
+
finish(() => (gmail() ? resolve(gmail()?.email ?? '') : reject(new Error(phrase('Gmail was not connected. Try again and allow access.')))));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
if (popup.location.origin !== window.location.origin)
|
|
233
|
+
return;
|
|
234
|
+
const hash = popup.location.hash || '';
|
|
235
|
+
if (!hash.includes('access_token=') && !hash.includes('error='))
|
|
236
|
+
return;
|
|
237
|
+
const params = new URLSearchParams(hash.replace(/^#/, ''));
|
|
238
|
+
const token = params.get('access_token');
|
|
239
|
+
popup.close();
|
|
240
|
+
if (!token) {
|
|
241
|
+
finish(() => reject(new Error(phrase('Google did not allow access. Try again and allow Gmail.'))));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const life = Number(params.get('expires_in') ?? '');
|
|
245
|
+
void complete(token, params.get('scope'), Number.isFinite(life) ? life : 0).then((email) => finish(() => resolve(email)));
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
/* still on accounts.google.com: cross-origin until the callback */
|
|
249
|
+
}
|
|
250
|
+
}, 250);
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
const CRLF = '\r\n';
|
|
254
|
+
function bytes64(bytes) {
|
|
255
|
+
let bin = '';
|
|
256
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
257
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
258
|
+
return btoa(bin);
|
|
259
|
+
}
|
|
260
|
+
const utf8 = (s) => bytes64(new TextEncoder().encode(s));
|
|
261
|
+
/** A header value: plain when it is ASCII, RFC 2047 encoded-word otherwise. */
|
|
262
|
+
const word = (s) => (/^[\x20-\x7e]*$/.test(s) ? s : `=?UTF-8?B?${utf8(s)}?=`);
|
|
263
|
+
/** A body part in base64, wrapped at 76 as RFC 2045 asks. */
|
|
264
|
+
const part = (type, body) => [`Content-Type: ${type}; charset="UTF-8"`, 'Content-Transfer-Encoding: base64', '', utf8(body).replace(/(.{76})/g, `$1${CRLF}`)].join(CRLF);
|
|
265
|
+
/** The RFC 2822 message, multipart/alternative with the text and the HTML, as Gmail's `raw` (base64url, no padding). */
|
|
266
|
+
export function raw(m, boundary = `hanzo_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`) {
|
|
267
|
+
for (const v of [m.to, m.subject, m.from ?? '']) {
|
|
268
|
+
if (/[\r\n]/.test(v))
|
|
269
|
+
throw new Error(phrase('An address or subject cannot hold a line break.'));
|
|
270
|
+
}
|
|
271
|
+
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(m.to.trim()))
|
|
272
|
+
throw new Error(phrase('That is not an email address.'));
|
|
273
|
+
const head = [
|
|
274
|
+
...(m.from ? [`From: ${m.from}`] : []),
|
|
275
|
+
`To: ${m.to.trim()}`,
|
|
276
|
+
`Subject: ${word(m.subject)}`,
|
|
277
|
+
'MIME-Version: 1.0',
|
|
278
|
+
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
|
279
|
+
];
|
|
280
|
+
const message = [...head, '', `--${boundary}`, part('text/plain', m.text), `--${boundary}`, part('text/html', m.html), `--${boundary}--`, ''].join(CRLF);
|
|
281
|
+
return utf8(message).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
282
|
+
}
|
|
283
|
+
/** Send one message from the connected account. Every refusal is a sentence a person can act on. */
|
|
284
|
+
export async function send(token, m) {
|
|
285
|
+
const body = JSON.stringify({ raw: raw(m) });
|
|
286
|
+
let res;
|
|
287
|
+
try {
|
|
288
|
+
res = await fetch('https://gmail.googleapis.com/gmail/v1/users/me/messages/send', {
|
|
289
|
+
method: 'POST',
|
|
290
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
291
|
+
body,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
throw new Error(phrase('Gmail could not be reached. Check your connection and try again.'));
|
|
296
|
+
}
|
|
297
|
+
if (res.ok) {
|
|
298
|
+
const j = (await res.json().catch(() => ({})));
|
|
299
|
+
return { id: j.id ?? '' };
|
|
300
|
+
}
|
|
301
|
+
if (res.status === 401)
|
|
302
|
+
throw new Error(phrase('Reconnect Gmail: the connection has expired.'));
|
|
303
|
+
if (res.status === 403)
|
|
304
|
+
throw new Error(phrase('Gmail did not allow sending from this account. Reconnect Gmail and allow it to send.'));
|
|
305
|
+
if (res.status === 429)
|
|
306
|
+
throw new Error(phrase('Gmail is limiting how fast this account sends. Try again in a few minutes.'));
|
|
307
|
+
if (res.status === 400)
|
|
308
|
+
throw new Error(phrase('Gmail refused this message. Check the address and try again.'));
|
|
309
|
+
throw new Error(phrase('Gmail could not send the message. Try again in a moment.'));
|
|
310
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OPTING IN TO WHAT IS EXPERIMENTAL: the one client for the reader's choice and
|
|
3
|
+
* their organization's block.
|
|
4
|
+
*
|
|
5
|
+
* A beta is PRIVATE (a SuperAdmin grants it, person by person) or PUBLIC (an
|
|
6
|
+
* admin promoted it). A reader who opts in gets every public beta, unless their
|
|
7
|
+
* organization turned it off; staff get every beta. Who is in is still the
|
|
8
|
+
* cloud's answer at GET /v1/flag/platform, so `opens` (lib/betas) stays the one
|
|
9
|
+
* predicate; this module only reads and writes the choice.
|
|
10
|
+
*
|
|
11
|
+
* GET /v1/flag/optin {on, blocked, public: [<beta id>]} 401 signed out
|
|
12
|
+
* PUT /v1/flag/optin {on} -> the same shape 403 when blocked and on
|
|
13
|
+
* PUT /v1/flag/optin/org {blocked} -> {blocked} an org admin or a SuperAdmin
|
|
14
|
+
*
|
|
15
|
+
* A refusal is said in words a person can act on, never as a status code: each
|
|
16
|
+
* is authored English (`phrase`), so a caller draws it through `t`.
|
|
17
|
+
*/
|
|
18
|
+
/** The reader's choice, their organization's block, and the betas that are public. */
|
|
19
|
+
export interface Optin {
|
|
20
|
+
/** The reader opted in. */
|
|
21
|
+
on: boolean;
|
|
22
|
+
/** Their organization turned it off for everyone in it. */
|
|
23
|
+
blocked: boolean;
|
|
24
|
+
/** The ids (lib/betas) of the public betas. */
|
|
25
|
+
public: string[];
|
|
26
|
+
}
|
|
27
|
+
/** Fired on window after the choice or the block changes, so a list can read again. */
|
|
28
|
+
export declare const CHANGED = "hanzo.optin";
|
|
29
|
+
/** The reader's choice as the cloud holds it. */
|
|
30
|
+
export declare function optin(): Promise<Optin>;
|
|
31
|
+
/** Opt the reader in or out. Refused while their organization has it turned off. */
|
|
32
|
+
export declare function opt(on: boolean): Promise<Optin>;
|
|
33
|
+
/** Turn experimental features off, or back on, for everyone in the organization in scope. */
|
|
34
|
+
export declare function block(blocked: boolean): Promise<{
|
|
35
|
+
blocked: boolean;
|
|
36
|
+
}>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OPTING IN TO WHAT IS EXPERIMENTAL: the one client for the reader's choice and
|
|
3
|
+
* their organization's block.
|
|
4
|
+
*
|
|
5
|
+
* A beta is PRIVATE (a SuperAdmin grants it, person by person) or PUBLIC (an
|
|
6
|
+
* admin promoted it). A reader who opts in gets every public beta, unless their
|
|
7
|
+
* organization turned it off; staff get every beta. Who is in is still the
|
|
8
|
+
* cloud's answer at GET /v1/flag/platform, so `opens` (lib/betas) stays the one
|
|
9
|
+
* predicate; this module only reads and writes the choice.
|
|
10
|
+
*
|
|
11
|
+
* GET /v1/flag/optin {on, blocked, public: [<beta id>]} 401 signed out
|
|
12
|
+
* PUT /v1/flag/optin {on} -> the same shape 403 when blocked and on
|
|
13
|
+
* PUT /v1/flag/optin/org {blocked} -> {blocked} an org admin or a SuperAdmin
|
|
14
|
+
*
|
|
15
|
+
* A refusal is said in words a person can act on, never as a status code: each
|
|
16
|
+
* is authored English (`phrase`), so a caller draws it through `t`.
|
|
17
|
+
*/
|
|
18
|
+
import { phrase } from '@hanzo/i18n';
|
|
19
|
+
import { api } from './api.js';
|
|
20
|
+
import { scope } from './session.js';
|
|
21
|
+
/** Fired on window after the choice or the block changes, so a list can read again. */
|
|
22
|
+
export const CHANGED = 'hanzo.optin';
|
|
23
|
+
const SIGNED_OUT = phrase('Sign in to choose experimental features.');
|
|
24
|
+
async function call(path, init, words) {
|
|
25
|
+
let res;
|
|
26
|
+
try {
|
|
27
|
+
res = await fetch(`${api()}${path}`, { ...init, headers: { ...(init?.body ? { 'Content-Type': 'application/json' } : {}), ...scope() } });
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new Error(words.offline);
|
|
31
|
+
}
|
|
32
|
+
if (res.status === 401)
|
|
33
|
+
throw new Error(SIGNED_OUT);
|
|
34
|
+
if (res.status === 403 && words.refused)
|
|
35
|
+
throw new Error(words.refused);
|
|
36
|
+
if (!res.ok)
|
|
37
|
+
throw new Error(words.failed);
|
|
38
|
+
return res.json();
|
|
39
|
+
}
|
|
40
|
+
const told = () => {
|
|
41
|
+
if (typeof window !== 'undefined')
|
|
42
|
+
window.dispatchEvent(new Event(CHANGED));
|
|
43
|
+
};
|
|
44
|
+
function shape(body) {
|
|
45
|
+
const b = (body ?? {});
|
|
46
|
+
return { on: b.on === true, blocked: b.blocked === true, public: Array.isArray(b.public) ? b.public.filter((id) => typeof id === 'string') : [] };
|
|
47
|
+
}
|
|
48
|
+
/** The reader's choice as the cloud holds it. */
|
|
49
|
+
export async function optin() {
|
|
50
|
+
return shape(await call('/v1/flag/optin', undefined, {
|
|
51
|
+
offline: phrase('Your experimental features setting could not be read. Check your connection and try again.'),
|
|
52
|
+
failed: phrase('Your experimental features setting could not be read. Try again in a moment.'),
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
/** Opt the reader in or out. Refused while their organization has it turned off. */
|
|
56
|
+
export async function opt(on) {
|
|
57
|
+
const out = shape(await call('/v1/flag/optin', { method: 'PUT', body: JSON.stringify({ on }) }, {
|
|
58
|
+
offline: phrase('Your choice was not saved. Check your connection and try again.'),
|
|
59
|
+
failed: phrase('Your choice was not saved. Try again in a moment.'),
|
|
60
|
+
refused: phrase('Your team or organization has turned experimental features off.'),
|
|
61
|
+
}));
|
|
62
|
+
told();
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
/** Turn experimental features off, or back on, for everyone in the organization in scope. */
|
|
66
|
+
export async function block(blocked) {
|
|
67
|
+
const b = (await call('/v1/flag/optin/org', { method: 'PUT', body: JSON.stringify({ blocked }) }, {
|
|
68
|
+
offline: phrase('The organization setting was not saved. Check your connection and try again.'),
|
|
69
|
+
failed: phrase('The organization setting was not saved. Try again in a moment.'),
|
|
70
|
+
refused: phrase('Only an admin of this organization can change this for everyone in it.'),
|
|
71
|
+
}));
|
|
72
|
+
told();
|
|
73
|
+
return { blocked: b?.blocked === true };
|
|
74
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hanzo/app",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.29",
|
|
4
4
|
"description": "Hanzo's app: the shell and its apps (Home, Chat, Inbox, Contacts, Meet, Calendar, Drive, Board, Work, Bots), once, for every Hanzo surface.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|