@appgrowstack/app-auth 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +134 -0
- package/LICENSE +21 -0
- package/README.md +320 -2
- package/dist/apple-revoke.d.ts +23 -0
- package/dist/apple-revoke.js +100 -0
- package/dist/apple-web.d.ts +33 -0
- package/dist/apple-web.js +92 -0
- package/dist/authenticate.d.ts +29 -0
- package/dist/authenticate.js +64 -0
- package/dist/config.d.ts +88 -0
- package/dist/config.js +5 -0
- package/dist/contract.d.ts +93 -0
- package/dist/contract.js +0 -0
- package/dist/d1.d.ts +17 -0
- package/dist/d1.js +0 -0
- package/dist/delete-user.d.ts +14 -0
- package/dist/delete-user.js +17 -0
- package/dist/device-routes.d.ts +9 -0
- package/dist/device-routes.js +144 -0
- package/dist/device.d.ts +31 -0
- package/dist/device.js +88 -0
- package/dist/firebase-refresh.d.ts +14 -0
- package/dist/firebase-refresh.js +33 -0
- package/dist/http.d.ts +25 -0
- package/dist/http.js +32 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/providers.d.ts +24 -0
- package/dist/providers.js +74 -0
- package/dist/routes.d.ts +6 -0
- package/dist/routes.js +349 -0
- package/dist/store.d.ts +35 -0
- package/dist/store.js +135 -0
- package/dist/tokens.d.ts +34 -0
- package/dist/tokens.js +105 -0
- package/migrations/0001_app_auth.sql +25 -0
- package/migrations/0002_app_auth_apple_web.sql +7 -0
- package/migrations/0003_app_auth_device.sql +12 -0
- package/package.json +47 -4
- package/scripts/import-firebase-users.ts +117 -0
package/dist/routes.js
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { appleAuthorizeUrl, appleWebErrorFrom, appleWebReturnUrl, codeChallengeFor, consumeAppleWebCode, createAppleWebCode, findAppleWebCode, isCodeChallenge, newNonce, signAppleWebState, verifyAppleWebState, } from "./apple-web.js";
|
|
3
|
+
import { ownsAccount, resolveBearer } from "./authenticate.js";
|
|
4
|
+
import { deviceRoutes } from "./device-routes.js";
|
|
5
|
+
import { DEFAULT_ACCESS_TOKEN_TTL_MS, DEFAULT_REFRESH_TOKEN_IDLE_TTL_MS, fromEnv } from "./config.js";
|
|
6
|
+
import { bearerToken, fail, nonEmptyString, rateLimited, readObject } from "./http.js";
|
|
7
|
+
import { exchangeFirebaseRefreshToken } from "./firebase-refresh.js";
|
|
8
|
+
import { hashedNonce, verifyAppleIdToken, verifyAppleToken, verifyFirebaseToken, verifyGoogleToken } from "./providers.js";
|
|
9
|
+
import { claimIdentity, createAnonymousUser, ensureUser, findOrCreateUserFor, identityOwner, registerDevice, revokeDevice, sessionUser, unlinkIdentity, useRefreshToken, userState, } from "./store.js";
|
|
10
|
+
import { parseTokenSecrets, signAccessToken, splitRefreshToken } from "./tokens.js";
|
|
11
|
+
const MAX_INSTALL_ID = 128;
|
|
12
|
+
const MAX_TOKEN = 8192;
|
|
13
|
+
const MAX_NONCE = 256;
|
|
14
|
+
const SIGN_IN_MODES = ["link_or_sign_in", "sign_in_existing"];
|
|
15
|
+
const LINKABLE = ["apple", "google"];
|
|
16
|
+
function signInMode(value) {
|
|
17
|
+
if (value === undefined || value === null)
|
|
18
|
+
return "link_or_sign_in";
|
|
19
|
+
return SIGN_IN_MODES.find((mode) => mode === value) ?? null;
|
|
20
|
+
}
|
|
21
|
+
async function anonymousAllowed(limiter, ip, installId) {
|
|
22
|
+
if (!limiter)
|
|
23
|
+
return true;
|
|
24
|
+
const { byIp, byInstall } = "limit" in limiter ? { byIp: limiter, byInstall: limiter } : limiter;
|
|
25
|
+
const checks = [];
|
|
26
|
+
if (byIp && ip)
|
|
27
|
+
checks.push(byIp.limit({ key: `ip:${ip}` }));
|
|
28
|
+
if (byInstall)
|
|
29
|
+
checks.push(byInstall.limit({ key: `install:${installId}` }));
|
|
30
|
+
return (await Promise.all(checks)).every((result) => result.success);
|
|
31
|
+
}
|
|
32
|
+
async function refreshAllowed(limiter, ip, deviceId) {
|
|
33
|
+
if (!limiter)
|
|
34
|
+
return true;
|
|
35
|
+
const { byIp, byDevice } = "limit" in limiter ? { byIp: limiter, byDevice: limiter } : limiter;
|
|
36
|
+
const checks = [];
|
|
37
|
+
if (byIp && ip)
|
|
38
|
+
checks.push(byIp.limit({ key: `ip:${ip}` }));
|
|
39
|
+
if (byDevice && deviceId)
|
|
40
|
+
checks.push(byDevice.limit({ key: `device:${deviceId}` }));
|
|
41
|
+
return (await Promise.all(checks)).every((result) => result.success);
|
|
42
|
+
}
|
|
43
|
+
function firebaseUnavailable(c) {
|
|
44
|
+
c.header("retry-after", "60");
|
|
45
|
+
return fail(c, 503, "firebase_unavailable", "could not exchange the Firebase refresh token now; keep it and retry later");
|
|
46
|
+
}
|
|
47
|
+
const nothingToConsume = async () => true;
|
|
48
|
+
export async function issueSession(config, env, userId, installId, at) {
|
|
49
|
+
const db = config.db(env);
|
|
50
|
+
const device = await registerDevice(db, userId, installId, at);
|
|
51
|
+
const access = await signAccessToken(parseTokenSecrets(config.tokenSecrets(env)), config.app, { userId, deviceId: device.deviceId }, at, config.accessTokenTtlMs ?? DEFAULT_ACCESS_TOKEN_TTL_MS);
|
|
52
|
+
return { user: await sessionUser(db, userId), ...access, refreshToken: device.refreshToken };
|
|
53
|
+
}
|
|
54
|
+
export function authRoutes(config) {
|
|
55
|
+
const app = new Hono();
|
|
56
|
+
const now = () => config.now?.() ?? Date.now();
|
|
57
|
+
const ttl = config.accessTokenTtlMs ?? DEFAULT_ACCESS_TOKEN_TTL_MS;
|
|
58
|
+
const refreshIdleTtl = config.refreshTokenIdleTtlMs ?? DEFAULT_REFRESH_TOKEN_IDLE_TTL_MS;
|
|
59
|
+
const keyring = (env) => parseTokenSecrets(config.tokenSecrets(env));
|
|
60
|
+
async function accessFor(env, userId, deviceId, at) {
|
|
61
|
+
return signAccessToken(keyring(env), config.app, { userId, deviceId }, at, ttl);
|
|
62
|
+
}
|
|
63
|
+
const newSession = (env, userId, installId, at) => issueSession(config, env, userId, installId, at);
|
|
64
|
+
const anonymousEnabled = (env) => fromEnv(config.anonymous, env) ?? true;
|
|
65
|
+
async function expectedNonce(env, value) {
|
|
66
|
+
const raw = nonEmptyString(value, MAX_NONCE);
|
|
67
|
+
if (raw)
|
|
68
|
+
return { ok: true, nonce: await hashedNonce(raw) };
|
|
69
|
+
if (value !== undefined && value !== null)
|
|
70
|
+
return { ok: false };
|
|
71
|
+
return (fromEnv(config.requireNonce, env) ?? true) ? { ok: false } : { ok: true, nonce: undefined };
|
|
72
|
+
}
|
|
73
|
+
const nonceRejected = (c) => fail(c, 401, "invalid_nonce", "nonce is missing or does not match the token");
|
|
74
|
+
app.post("/v1/auth/anonymous", async (c) => {
|
|
75
|
+
if (!anonymousEnabled(c.env))
|
|
76
|
+
return fail(c, 404, "provider_not_enabled", "anonymous sign-up is not enabled");
|
|
77
|
+
const body = await readObject(c);
|
|
78
|
+
if (body instanceof Response)
|
|
79
|
+
return body;
|
|
80
|
+
const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
|
|
81
|
+
if (!installId)
|
|
82
|
+
return fail(c, 400, "bad_request", "installId is required");
|
|
83
|
+
if (!(await anonymousAllowed(fromEnv(config.rateLimit, c.env)?.anonymous, c.req.header("cf-connecting-ip"), installId))) {
|
|
84
|
+
return rateLimited(c, "anonymous sign-ups");
|
|
85
|
+
}
|
|
86
|
+
const at = now();
|
|
87
|
+
const userId = await createAnonymousUser(config.db(c.env), at);
|
|
88
|
+
await config.hooks?.onUserCreated?.(userId, c.env);
|
|
89
|
+
return c.json(await newSession(c.env, userId, installId, at));
|
|
90
|
+
});
|
|
91
|
+
app.post("/v1/auth/refresh", async (c) => {
|
|
92
|
+
const body = await readObject(c);
|
|
93
|
+
if (body instanceof Response)
|
|
94
|
+
return body;
|
|
95
|
+
const refreshToken = nonEmptyString(body.refreshToken, MAX_TOKEN);
|
|
96
|
+
if (!refreshToken)
|
|
97
|
+
return fail(c, 400, "bad_request", "refreshToken is required");
|
|
98
|
+
const limiter = fromEnv(config.rateLimit, c.env)?.refresh;
|
|
99
|
+
if (!(await refreshAllowed(limiter, c.req.header("cf-connecting-ip"), splitRefreshToken(refreshToken)?.deviceId))) {
|
|
100
|
+
return rateLimited(c, "refreshes");
|
|
101
|
+
}
|
|
102
|
+
const at = now();
|
|
103
|
+
const db = config.db(c.env);
|
|
104
|
+
const device = await useRefreshToken(db, refreshToken, at, refreshIdleTtl);
|
|
105
|
+
if (!device)
|
|
106
|
+
return fail(c, 401, "invalid_refresh_token", "refresh token is not valid");
|
|
107
|
+
const session = { user: await sessionUser(db, device.userId), ...(await accessFor(c.env, device.userId, device.deviceId, at)), refreshToken };
|
|
108
|
+
return c.json(session);
|
|
109
|
+
});
|
|
110
|
+
async function signInOrLink(c, provider, subject, installId, mode, consume = nothingToConsume) {
|
|
111
|
+
const at = now();
|
|
112
|
+
const db = config.db(c.env);
|
|
113
|
+
const codeAlreadyUsed = () => fail(c, 401, "invalid_code", "code is not valid");
|
|
114
|
+
if (mode === "sign_in_existing") {
|
|
115
|
+
const owner = await identityOwner(db, provider, subject);
|
|
116
|
+
if (!owner)
|
|
117
|
+
return fail(c, 404, "account_not_found", `no account uses this ${provider} account`, { provider });
|
|
118
|
+
if (!(await consume()))
|
|
119
|
+
return codeAlreadyUsed();
|
|
120
|
+
return c.json(await newSession(c.env, owner, installId, at));
|
|
121
|
+
}
|
|
122
|
+
const token = bearerToken(c);
|
|
123
|
+
if (token) {
|
|
124
|
+
const current = await resolveBearer(config, c.env, token, { allowLegacy: false });
|
|
125
|
+
if (current.kind === "deleted")
|
|
126
|
+
return fail(c, 410, "account_deleted", "account was deleted");
|
|
127
|
+
if (!ownsAccount(current))
|
|
128
|
+
return fail(c, 401, "invalid_token", "access token is not valid");
|
|
129
|
+
const inUse = () => fail(c, 409, "credential_already_in_use", `this ${provider} account belongs to another user`, { provider });
|
|
130
|
+
const owner = await identityOwner(db, provider, subject);
|
|
131
|
+
if (owner && owner !== current.userId)
|
|
132
|
+
return inUse();
|
|
133
|
+
if (!(await consume()))
|
|
134
|
+
return codeAlreadyUsed();
|
|
135
|
+
const claim = await claimIdentity(db, provider, subject, current.userId, at);
|
|
136
|
+
if (claim.kind === "in_use")
|
|
137
|
+
return inUse();
|
|
138
|
+
if (claim.kind === "linked")
|
|
139
|
+
await config.hooks?.onIdentityLinked?.(current.userId, provider, c.env);
|
|
140
|
+
return c.json(await newSession(c.env, current.userId, installId, at));
|
|
141
|
+
}
|
|
142
|
+
if (!(await consume()))
|
|
143
|
+
return codeAlreadyUsed();
|
|
144
|
+
const { userId, created } = await findOrCreateUserFor(db, provider, subject, at);
|
|
145
|
+
if (created) {
|
|
146
|
+
await config.hooks?.onUserCreated?.(userId, c.env);
|
|
147
|
+
await config.hooks?.onIdentityLinked?.(userId, provider, c.env);
|
|
148
|
+
}
|
|
149
|
+
return c.json(await newSession(c.env, userId, installId, at));
|
|
150
|
+
}
|
|
151
|
+
app.post("/v1/auth/apple", async (c) => {
|
|
152
|
+
const apple = fromEnv(config.apple, c.env);
|
|
153
|
+
if (!apple)
|
|
154
|
+
return fail(c, 404, "provider_not_enabled", "Sign in with Apple is not enabled");
|
|
155
|
+
const body = await readObject(c);
|
|
156
|
+
if (body instanceof Response)
|
|
157
|
+
return body;
|
|
158
|
+
const identityToken = nonEmptyString(body.identityToken, MAX_TOKEN);
|
|
159
|
+
const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
|
|
160
|
+
const mode = signInMode(body.mode);
|
|
161
|
+
if (!identityToken || !installId)
|
|
162
|
+
return fail(c, 400, "bad_request", "identityToken and installId are required");
|
|
163
|
+
if (!mode)
|
|
164
|
+
return fail(c, 400, "bad_request", "mode must be link_or_sign_in or sign_in_existing");
|
|
165
|
+
const expected = await expectedNonce(c.env, body.nonce);
|
|
166
|
+
if (!expected.ok)
|
|
167
|
+
return nonceRejected(c);
|
|
168
|
+
const verified = await verifyAppleIdToken(apple, identityToken, now());
|
|
169
|
+
if (!verified)
|
|
170
|
+
return fail(c, 401, "invalid_apple_token", "Apple identity token is not valid");
|
|
171
|
+
if (expected.nonce !== undefined && verified.nonce !== expected.nonce)
|
|
172
|
+
return nonceRejected(c);
|
|
173
|
+
return signInOrLink(c, "apple", verified.sub, installId, mode);
|
|
174
|
+
});
|
|
175
|
+
app.post("/v1/auth/google", async (c) => {
|
|
176
|
+
const google = fromEnv(config.google, c.env);
|
|
177
|
+
if (!google)
|
|
178
|
+
return fail(c, 404, "provider_not_enabled", "Google sign-in is not enabled");
|
|
179
|
+
const body = await readObject(c);
|
|
180
|
+
if (body instanceof Response)
|
|
181
|
+
return body;
|
|
182
|
+
const idToken = nonEmptyString(body.idToken, MAX_TOKEN);
|
|
183
|
+
const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
|
|
184
|
+
const mode = signInMode(body.mode);
|
|
185
|
+
if (!idToken || !installId)
|
|
186
|
+
return fail(c, 400, "bad_request", "idToken and installId are required");
|
|
187
|
+
if (!mode)
|
|
188
|
+
return fail(c, 400, "bad_request", "mode must be link_or_sign_in or sign_in_existing");
|
|
189
|
+
const expected = await expectedNonce(c.env, body.nonce);
|
|
190
|
+
if (!expected.ok)
|
|
191
|
+
return nonceRejected(c);
|
|
192
|
+
const verified = await verifyGoogleToken(google, idToken, now());
|
|
193
|
+
if (!verified)
|
|
194
|
+
return fail(c, 401, "invalid_google_token", "Google ID token is not valid");
|
|
195
|
+
if (expected.nonce !== undefined && verified.nonce !== expected.nonce)
|
|
196
|
+
return nonceRejected(c);
|
|
197
|
+
return signInOrLink(c, "google", verified.sub, installId, mode);
|
|
198
|
+
});
|
|
199
|
+
app.get("/v1/auth/apple/web/start", async (c) => {
|
|
200
|
+
const web = fromEnv(config.apple, c.env)?.web;
|
|
201
|
+
if (!web)
|
|
202
|
+
return fail(c, 404, "provider_not_enabled", "Sign in with Apple on the web is not enabled");
|
|
203
|
+
const installId = nonEmptyString(c.req.query("installId"), MAX_INSTALL_ID);
|
|
204
|
+
const platform = c.req.query("platform");
|
|
205
|
+
const codeChallenge = c.req.query("codeChallenge");
|
|
206
|
+
if (!installId || platform !== "android" || !isCodeChallenge(codeChallenge)) {
|
|
207
|
+
return fail(c, 400, "bad_request", "installId, platform=android and codeChallenge (S256, base64url) are required");
|
|
208
|
+
}
|
|
209
|
+
const nonce = newNonce();
|
|
210
|
+
const state = await signAppleWebState(keyring(c.env), config.app, { installId, platform, nonce, codeChallenge }, now());
|
|
211
|
+
c.header("cache-control", "no-store");
|
|
212
|
+
return c.redirect(appleAuthorizeUrl(web, state, nonce), 302);
|
|
213
|
+
});
|
|
214
|
+
app.post("/v1/auth/apple/web/callback", async (c) => {
|
|
215
|
+
const apple = fromEnv(config.apple, c.env);
|
|
216
|
+
const web = apple?.web;
|
|
217
|
+
if (!apple || !web)
|
|
218
|
+
return fail(c, 404, "provider_not_enabled", "Sign in with Apple on the web is not enabled");
|
|
219
|
+
c.header("cache-control", "no-store");
|
|
220
|
+
const form = await c.req.parseBody().catch(() => ({}));
|
|
221
|
+
const at = now();
|
|
222
|
+
const state = typeof form.state === "string" ? await verifyAppleWebState(keyring(c.env), config.app, form.state, at) : null;
|
|
223
|
+
if (!state)
|
|
224
|
+
return c.redirect(appleWebReturnUrl(web, { error: "invalid_state" }), 302);
|
|
225
|
+
if (form.error !== undefined)
|
|
226
|
+
return c.redirect(appleWebReturnUrl(web, { error: appleWebErrorFrom(form.error) }), 302);
|
|
227
|
+
const idToken = typeof form.id_token === "string" ? form.id_token : null;
|
|
228
|
+
const subject = idToken ? await verifyAppleToken(apple, idToken, at, { audience: web.servicesId, nonce: state.nonce }) : null;
|
|
229
|
+
if (!subject)
|
|
230
|
+
return c.redirect(appleWebReturnUrl(web, { error: "invalid_apple_token" }), 302);
|
|
231
|
+
const code = await createAppleWebCode(config.db(c.env), subject, state.installId, state.codeChallenge, at);
|
|
232
|
+
return c.redirect(appleWebReturnUrl(web, { code }), 302);
|
|
233
|
+
});
|
|
234
|
+
app.post("/v1/auth/apple/web/exchange", async (c) => {
|
|
235
|
+
const web = fromEnv(config.apple, c.env)?.web;
|
|
236
|
+
if (!web)
|
|
237
|
+
return fail(c, 404, "provider_not_enabled", "Sign in with Apple on the web is not enabled");
|
|
238
|
+
const body = await readObject(c);
|
|
239
|
+
if (body instanceof Response)
|
|
240
|
+
return body;
|
|
241
|
+
const code = nonEmptyString(body.code, MAX_TOKEN);
|
|
242
|
+
const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
|
|
243
|
+
const mode = signInMode(body.mode);
|
|
244
|
+
const codeChallenge = await codeChallengeFor(body.codeVerifier);
|
|
245
|
+
if (!code || !installId || !codeChallenge)
|
|
246
|
+
return fail(c, 400, "bad_request", "code, installId and codeVerifier are required");
|
|
247
|
+
if (!mode)
|
|
248
|
+
return fail(c, 400, "bad_request", "mode must be link_or_sign_in or sign_in_existing");
|
|
249
|
+
const db = config.db(c.env);
|
|
250
|
+
const found = await findAppleWebCode(db, code, codeChallenge, now());
|
|
251
|
+
if (!found || found.installId !== installId)
|
|
252
|
+
return fail(c, 401, "invalid_code", "code is not valid");
|
|
253
|
+
return signInOrLink(c, "apple", found.subject, installId, mode, () => consumeAppleWebCode(db, found.codeHash));
|
|
254
|
+
});
|
|
255
|
+
app.post("/v1/auth/firebase", async (c) => {
|
|
256
|
+
const firebase = fromEnv(config.legacyFirebase, c.env);
|
|
257
|
+
if (!firebase)
|
|
258
|
+
return fail(c, 404, "provider_not_enabled", "Firebase exchange is not enabled");
|
|
259
|
+
const body = await readObject(c);
|
|
260
|
+
if (body instanceof Response)
|
|
261
|
+
return body;
|
|
262
|
+
const idToken = nonEmptyString(body.idToken, MAX_TOKEN);
|
|
263
|
+
const refreshToken = nonEmptyString(body.refreshToken, MAX_TOKEN);
|
|
264
|
+
const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
|
|
265
|
+
if (!installId || (idToken === null) === (refreshToken === null)) {
|
|
266
|
+
return fail(c, 400, "bad_request", "installId and exactly one of idToken or refreshToken are required");
|
|
267
|
+
}
|
|
268
|
+
const limiter = fromEnv(config.rateLimit, c.env)?.firebase;
|
|
269
|
+
const ip = c.req.header("cf-connecting-ip");
|
|
270
|
+
if (limiter && ip && !(await limiter.limit({ key: `ip:${ip}` })).success)
|
|
271
|
+
return rateLimited(c, "Firebase exchanges");
|
|
272
|
+
let identity;
|
|
273
|
+
if (refreshToken) {
|
|
274
|
+
if (!firebase.webApiKey)
|
|
275
|
+
return fail(c, 404, "provider_not_enabled", "Firebase refresh-token exchange is not enabled");
|
|
276
|
+
const exchanged = await exchangeFirebaseRefreshToken(config.fetch ?? fetch, firebase.webApiKey, refreshToken);
|
|
277
|
+
if (exchanged.kind === "rejected") {
|
|
278
|
+
return fail(c, 401, "legacy_credential_rejected", "Firebase refresh token can no longer be used", { cause: exchanged.cause });
|
|
279
|
+
}
|
|
280
|
+
if (exchanged.kind === "unavailable") {
|
|
281
|
+
console.warn(JSON.stringify({ msg: "app_auth: securetoken unavailable", httpStatus: exchanged.httpStatus ?? null, message: exchanged.message ?? null }));
|
|
282
|
+
return firebaseUnavailable(c);
|
|
283
|
+
}
|
|
284
|
+
identity = await verifyFirebaseToken(firebase, exchanged.idToken, now());
|
|
285
|
+
if (!identity) {
|
|
286
|
+
console.warn(JSON.stringify({ msg: "app_auth: securetoken id_token did not verify" }));
|
|
287
|
+
return firebaseUnavailable(c);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
identity = await verifyFirebaseToken(firebase, idToken, now());
|
|
292
|
+
if (!identity)
|
|
293
|
+
return fail(c, 401, "invalid_firebase_token", "Firebase ID token is not valid");
|
|
294
|
+
}
|
|
295
|
+
const at = now();
|
|
296
|
+
const db = config.db(c.env);
|
|
297
|
+
if ((await userState(db, identity.uid)) === "deleted")
|
|
298
|
+
return fail(c, 410, "account_deleted", "account was deleted");
|
|
299
|
+
await ensureUser(db, identity.uid, at);
|
|
300
|
+
await claimIdentity(db, "firebase", identity.uid, identity.uid, at);
|
|
301
|
+
const copies = [
|
|
302
|
+
...identity.appleSubjects.map((s) => ["apple", s]),
|
|
303
|
+
...identity.googleSubjects.map((s) => ["google", s]),
|
|
304
|
+
];
|
|
305
|
+
for (const [provider, subject] of copies) {
|
|
306
|
+
const claim = await claimIdentity(db, provider, subject, identity.uid, at);
|
|
307
|
+
if (claim.kind === "linked")
|
|
308
|
+
await config.hooks?.onIdentityLinked?.(identity.uid, provider, c.env);
|
|
309
|
+
}
|
|
310
|
+
return c.json(await newSession(c.env, identity.uid, installId, at));
|
|
311
|
+
});
|
|
312
|
+
app.delete("/v1/auth/identities/:provider", async (c) => {
|
|
313
|
+
const provider = LINKABLE.find((p) => p === c.req.param("provider"));
|
|
314
|
+
if (!provider)
|
|
315
|
+
return fail(c, 400, "bad_request", "provider must be apple or google");
|
|
316
|
+
const token = bearerToken(c);
|
|
317
|
+
if (!token)
|
|
318
|
+
return fail(c, 401, "missing_token", "Authorization: Bearer <token> is required");
|
|
319
|
+
const current = await resolveBearer(config, c.env, token, { allowLegacy: false });
|
|
320
|
+
if (current.kind === "deleted")
|
|
321
|
+
return fail(c, 410, "account_deleted", "account was deleted");
|
|
322
|
+
if (!ownsAccount(current))
|
|
323
|
+
return fail(c, 401, "invalid_token", "access token is not valid");
|
|
324
|
+
const db = config.db(c.env);
|
|
325
|
+
if (!anonymousEnabled(c.env)) {
|
|
326
|
+
const linked = (await sessionUser(db, current.userId)).linkedProviders;
|
|
327
|
+
if (linked.length === 1 && linked[0] === provider) {
|
|
328
|
+
return fail(c, 409, "last_identity", `${provider} is the only sign-in of this account; anonymous accounts are not enabled`, { provider });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if ((await unlinkIdentity(db, current.userId, provider)) === 0) {
|
|
332
|
+
return fail(c, 404, "identity_not_linked", `${provider} is not linked to this account`, { provider });
|
|
333
|
+
}
|
|
334
|
+
const user = await sessionUser(db, current.userId);
|
|
335
|
+
return c.json(user);
|
|
336
|
+
});
|
|
337
|
+
app.post("/v1/auth/sign-out", async (c) => {
|
|
338
|
+
const token = bearerToken(c);
|
|
339
|
+
if (!token)
|
|
340
|
+
return fail(c, 401, "missing_token", "Authorization: Bearer <token> is required");
|
|
341
|
+
const current = await resolveBearer(config, c.env, token, { allowLegacy: false });
|
|
342
|
+
if (current.kind !== "session" || !current.deviceId)
|
|
343
|
+
return fail(c, 401, "invalid_token", "access token is not valid");
|
|
344
|
+
await revokeDevice(config.db(c.env), current.deviceId, now());
|
|
345
|
+
return c.body(null, 204);
|
|
346
|
+
});
|
|
347
|
+
app.route("/", deviceRoutes(config, { now, newSession }));
|
|
348
|
+
return app;
|
|
349
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { IdentityProvider, LinkableProvider, SessionUser } from "./contract.js";
|
|
2
|
+
import type { D1Like } from "./d1.js";
|
|
3
|
+
export type UserState = "live" | "deleted" | "missing";
|
|
4
|
+
export declare function userState(db: D1Like, userId: string): Promise<UserState>;
|
|
5
|
+
export declare function sessionIsLive(db: D1Like, userId: string, deviceId: string): Promise<boolean>;
|
|
6
|
+
export declare function sessionUser(db: D1Like, userId: string): Promise<SessionUser>;
|
|
7
|
+
export declare function createAnonymousUser(db: D1Like, now: number): Promise<string>;
|
|
8
|
+
export declare function ensureUser(db: D1Like, userId: string, now: number): Promise<void>;
|
|
9
|
+
export declare function identityOwner(db: D1Like, provider: IdentityProvider, subject: string): Promise<string | null>;
|
|
10
|
+
export type ClaimResult = {
|
|
11
|
+
kind: "linked";
|
|
12
|
+
} | {
|
|
13
|
+
kind: "already_linked";
|
|
14
|
+
} | {
|
|
15
|
+
kind: "in_use";
|
|
16
|
+
ownerId: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function claimIdentity(db: D1Like, provider: IdentityProvider, subject: string, userId: string, now: number): Promise<ClaimResult>;
|
|
19
|
+
export declare function findOrCreateUserFor(db: D1Like, provider: LinkableProvider, subject: string, now: number): Promise<{
|
|
20
|
+
userId: string;
|
|
21
|
+
created: boolean;
|
|
22
|
+
}>;
|
|
23
|
+
export interface RegisteredDevice {
|
|
24
|
+
deviceId: string;
|
|
25
|
+
refreshToken: string;
|
|
26
|
+
}
|
|
27
|
+
export declare function registerDevice(db: D1Like, userId: string, installId: string, now: number): Promise<RegisteredDevice>;
|
|
28
|
+
export declare const LAST_SEEN_WRITE_INTERVAL_MS: number;
|
|
29
|
+
export declare function useRefreshToken(db: D1Like, refreshToken: string, now: number, idleTtlMs: number): Promise<{
|
|
30
|
+
userId: string;
|
|
31
|
+
deviceId: string;
|
|
32
|
+
} | null>;
|
|
33
|
+
export declare function revokeDevice(db: D1Like, deviceId: string, now: number): Promise<void>;
|
|
34
|
+
export declare function deleteAuthRows(db: D1Like, userId: string, now: number): Promise<void>;
|
|
35
|
+
export declare function unlinkIdentity(db: D1Like, userId: string, provider: LinkableProvider): Promise<number>;
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { constantTimeEqual, hashSecret, joinRefreshToken, newRefreshSecret, splitRefreshToken } from "./tokens.js";
|
|
2
|
+
export async function userState(db, userId) {
|
|
3
|
+
const row = await db.prepare("SELECT deleted_at AS deletedAt FROM auth_users WHERE id = ?").bind(userId).first();
|
|
4
|
+
if (!row)
|
|
5
|
+
return "missing";
|
|
6
|
+
return row.deletedAt === null ? "live" : "deleted";
|
|
7
|
+
}
|
|
8
|
+
export async function sessionIsLive(db, userId, deviceId) {
|
|
9
|
+
const row = await db
|
|
10
|
+
.prepare(`SELECT 1 AS ok FROM auth_users u JOIN auth_devices d ON d.user_id = u.id
|
|
11
|
+
WHERE u.id = ? AND d.id = ? AND u.deleted_at IS NULL AND d.revoked_at IS NULL`)
|
|
12
|
+
.bind(userId, deviceId)
|
|
13
|
+
.first();
|
|
14
|
+
return row !== null;
|
|
15
|
+
}
|
|
16
|
+
export async function sessionUser(db, userId) {
|
|
17
|
+
const user = await db.prepare("SELECT created_at AS createdAt FROM auth_users WHERE id = ?").bind(userId).first();
|
|
18
|
+
if (!user)
|
|
19
|
+
throw new Error(`auth_users has no row for ${userId}`);
|
|
20
|
+
const { results } = await db
|
|
21
|
+
.prepare("SELECT DISTINCT provider FROM auth_identities WHERE user_id = ? AND provider IN ('apple', 'google') ORDER BY provider")
|
|
22
|
+
.bind(userId)
|
|
23
|
+
.all();
|
|
24
|
+
const linkedProviders = results.length > 0 ? results.map((r) => r.provider) : ["anonymous"];
|
|
25
|
+
return { id: userId, linkedProviders, createdAt: user.createdAt };
|
|
26
|
+
}
|
|
27
|
+
export async function createAnonymousUser(db, now) {
|
|
28
|
+
const userId = crypto.randomUUID();
|
|
29
|
+
await db.prepare("INSERT INTO auth_users (id, created_at) VALUES (?, ?)").bind(userId, now).run();
|
|
30
|
+
return userId;
|
|
31
|
+
}
|
|
32
|
+
export async function ensureUser(db, userId, now) {
|
|
33
|
+
await db.prepare("INSERT INTO auth_users (id, created_at) VALUES (?, ?) ON CONFLICT (id) DO NOTHING").bind(userId, now).run();
|
|
34
|
+
}
|
|
35
|
+
export async function identityOwner(db, provider, subject) {
|
|
36
|
+
const row = await db
|
|
37
|
+
.prepare(`SELECT i.user_id AS userId FROM auth_identities i JOIN auth_users u ON u.id = i.user_id
|
|
38
|
+
WHERE i.provider = ? AND i.subject = ? AND u.deleted_at IS NULL`)
|
|
39
|
+
.bind(provider, subject)
|
|
40
|
+
.first();
|
|
41
|
+
return row?.userId ?? null;
|
|
42
|
+
}
|
|
43
|
+
const RELEASE_DELETED_OWNER = `DELETE FROM auth_identities WHERE provider = ? AND subject = ?
|
|
44
|
+
AND user_id IN (SELECT id FROM auth_users WHERE deleted_at IS NOT NULL)`;
|
|
45
|
+
export async function claimIdentity(db, provider, subject, userId, now) {
|
|
46
|
+
const [, inserted] = await db.batch([
|
|
47
|
+
db.prepare(RELEASE_DELETED_OWNER).bind(provider, subject),
|
|
48
|
+
db
|
|
49
|
+
.prepare("INSERT INTO auth_identities (provider, subject, user_id, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (provider, subject) DO NOTHING")
|
|
50
|
+
.bind(provider, subject, userId, now),
|
|
51
|
+
]);
|
|
52
|
+
if (inserted?.meta.changes === 1)
|
|
53
|
+
return { kind: "linked" };
|
|
54
|
+
const ownerId = await identityOwner(db, provider, subject);
|
|
55
|
+
if (ownerId === null || ownerId === userId)
|
|
56
|
+
return { kind: "already_linked" };
|
|
57
|
+
return { kind: "in_use", ownerId };
|
|
58
|
+
}
|
|
59
|
+
export async function findOrCreateUserFor(db, provider, subject, now) {
|
|
60
|
+
const existing = await identityOwner(db, provider, subject);
|
|
61
|
+
if (existing)
|
|
62
|
+
return { userId: existing, created: false };
|
|
63
|
+
const userId = crypto.randomUUID();
|
|
64
|
+
try {
|
|
65
|
+
await db.batch([
|
|
66
|
+
db.prepare(RELEASE_DELETED_OWNER).bind(provider, subject),
|
|
67
|
+
db.prepare("INSERT INTO auth_users (id, created_at) VALUES (?, ?)").bind(userId, now),
|
|
68
|
+
db.prepare("INSERT INTO auth_identities (provider, subject, user_id, created_at) VALUES (?, ?, ?, ?)").bind(provider, subject, userId, now),
|
|
69
|
+
]);
|
|
70
|
+
return { userId, created: true };
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
const winner = await identityOwner(db, provider, subject);
|
|
74
|
+
if (winner)
|
|
75
|
+
return { userId: winner, created: false };
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export async function registerDevice(db, userId, installId, now) {
|
|
80
|
+
const deviceId = crypto.randomUUID();
|
|
81
|
+
const secret = newRefreshSecret();
|
|
82
|
+
await db
|
|
83
|
+
.prepare("INSERT INTO auth_devices (id, user_id, install_id, secret_hash, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?)")
|
|
84
|
+
.bind(deviceId, userId, installId, await hashSecret(secret), now, now)
|
|
85
|
+
.run();
|
|
86
|
+
return { deviceId, refreshToken: joinRefreshToken({ deviceId, secret }) };
|
|
87
|
+
}
|
|
88
|
+
export const LAST_SEEN_WRITE_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
89
|
+
export async function useRefreshToken(db, refreshToken, now, idleTtlMs) {
|
|
90
|
+
const parts = splitRefreshToken(refreshToken);
|
|
91
|
+
if (!parts)
|
|
92
|
+
return null;
|
|
93
|
+
const device = await db
|
|
94
|
+
.prepare(`SELECT d.user_id AS userId, d.secret_hash AS secretHash, d.last_seen_at AS lastSeenAt FROM auth_devices d JOIN auth_users u ON u.id = d.user_id
|
|
95
|
+
WHERE d.id = ? AND d.revoked_at IS NULL AND u.deleted_at IS NULL`)
|
|
96
|
+
.bind(parts.deviceId)
|
|
97
|
+
.first();
|
|
98
|
+
if (!device || !constantTimeEqual(device.secretHash, await hashSecret(parts.secret)))
|
|
99
|
+
return null;
|
|
100
|
+
if (now - device.lastSeenAt > idleTtlMs && (await hasLinkedIdentity(db, device.userId))) {
|
|
101
|
+
await revokeDevice(db, parts.deviceId, now);
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
if (now - device.lastSeenAt >= LAST_SEEN_WRITE_INTERVAL_MS) {
|
|
105
|
+
await db
|
|
106
|
+
.prepare("UPDATE auth_devices SET last_seen_at = ? WHERE id = ? AND last_seen_at <= ?")
|
|
107
|
+
.bind(now, parts.deviceId, now - LAST_SEEN_WRITE_INTERVAL_MS)
|
|
108
|
+
.run();
|
|
109
|
+
}
|
|
110
|
+
return { userId: device.userId, deviceId: parts.deviceId };
|
|
111
|
+
}
|
|
112
|
+
async function hasLinkedIdentity(db, userId) {
|
|
113
|
+
const row = await db
|
|
114
|
+
.prepare("SELECT 1 AS ok FROM auth_identities WHERE user_id = ? AND provider IN ('apple', 'google') LIMIT 1")
|
|
115
|
+
.bind(userId)
|
|
116
|
+
.first();
|
|
117
|
+
return row !== null;
|
|
118
|
+
}
|
|
119
|
+
export async function revokeDevice(db, deviceId, now) {
|
|
120
|
+
await db.prepare("UPDATE auth_devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").bind(now, deviceId).run();
|
|
121
|
+
}
|
|
122
|
+
export async function deleteAuthRows(db, userId, now) {
|
|
123
|
+
await db.batch([
|
|
124
|
+
db
|
|
125
|
+
.prepare("INSERT INTO auth_users (id, created_at, deleted_at) VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE SET deleted_at = COALESCE(auth_users.deleted_at, excluded.deleted_at)")
|
|
126
|
+
.bind(userId, now, now),
|
|
127
|
+
db.prepare("DELETE FROM auth_identities WHERE user_id = ?").bind(userId),
|
|
128
|
+
db.prepare("UPDATE auth_devices SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL").bind(now, userId),
|
|
129
|
+
db.prepare("DELETE FROM auth_device_codes WHERE user_id = ?").bind(userId),
|
|
130
|
+
]);
|
|
131
|
+
}
|
|
132
|
+
export async function unlinkIdentity(db, userId, provider) {
|
|
133
|
+
const result = await db.prepare("DELETE FROM auth_identities WHERE user_id = ? AND provider = ?").bind(userId, provider).run();
|
|
134
|
+
return result.meta.changes;
|
|
135
|
+
}
|
package/dist/tokens.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export interface TokenSecret {
|
|
2
|
+
kid: string;
|
|
3
|
+
key: Uint8Array;
|
|
4
|
+
}
|
|
5
|
+
export interface TokenKeyring {
|
|
6
|
+
signing: TokenSecret;
|
|
7
|
+
byKid: ReadonlyMap<string, Uint8Array>;
|
|
8
|
+
}
|
|
9
|
+
export declare function parseTokenSecrets(raw: string | undefined): TokenKeyring;
|
|
10
|
+
export interface AccessClaims {
|
|
11
|
+
userId: string;
|
|
12
|
+
deviceId: string;
|
|
13
|
+
}
|
|
14
|
+
export interface IssuedAccessToken {
|
|
15
|
+
accessToken: string;
|
|
16
|
+
accessTokenExpiresAt: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function signAccessToken(keyring: TokenKeyring, app: string, claims: AccessClaims, now: number, ttlMs: number): Promise<IssuedAccessToken>;
|
|
19
|
+
export declare function verifyAccessToken(keyring: TokenKeyring, app: string, token: string, now: number): Promise<AccessClaims | null>;
|
|
20
|
+
export declare function verifyLegacyAccessToken(config: {
|
|
21
|
+
secret: string | undefined;
|
|
22
|
+
issuer: string;
|
|
23
|
+
audience: string;
|
|
24
|
+
}, token: string, now: number): Promise<string | null>;
|
|
25
|
+
export interface RefreshTokenParts {
|
|
26
|
+
deviceId: string;
|
|
27
|
+
secret: string;
|
|
28
|
+
}
|
|
29
|
+
export declare function newRefreshSecret(): string;
|
|
30
|
+
export declare function joinRefreshToken(parts: RefreshTokenParts): string;
|
|
31
|
+
export declare function splitRefreshToken(token: string): RefreshTokenParts | null;
|
|
32
|
+
export declare function hashSecret(secret: string): Promise<string>;
|
|
33
|
+
export declare function constantTimeEqual(a: string, b: string): boolean;
|
|
34
|
+
export declare function base64url(bytes: Uint8Array): string;
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
2
|
+
const MIN_SECRET_LENGTH = 32;
|
|
3
|
+
export function parseTokenSecrets(raw) {
|
|
4
|
+
const entries = (raw ?? "")
|
|
5
|
+
.split(",")
|
|
6
|
+
.map((part) => part.trim())
|
|
7
|
+
.filter((part) => part.length > 0);
|
|
8
|
+
if (entries.length === 0)
|
|
9
|
+
throw new Error("AUTH_TOKEN_SECRETS is not set");
|
|
10
|
+
const byKid = new Map();
|
|
11
|
+
const secrets = [];
|
|
12
|
+
for (const [index, entry] of entries.entries()) {
|
|
13
|
+
const colon = entry.indexOf(":");
|
|
14
|
+
const kid = colon > 0 ? entry.slice(0, colon) : "";
|
|
15
|
+
const secret = colon > 0 ? entry.slice(colon + 1) : "";
|
|
16
|
+
if (!kid || secret.length < MIN_SECRET_LENGTH) {
|
|
17
|
+
throw new Error(`AUTH_TOKEN_SECRETS entry #${index + 1} must be "kid:secret" with a secret of ${MIN_SECRET_LENGTH}+ characters`);
|
|
18
|
+
}
|
|
19
|
+
if (byKid.has(kid))
|
|
20
|
+
throw new Error(`AUTH_TOKEN_SECRETS has kid "${kid}" twice`);
|
|
21
|
+
const key = new TextEncoder().encode(secret);
|
|
22
|
+
byKid.set(kid, key);
|
|
23
|
+
secrets.push({ kid, key });
|
|
24
|
+
}
|
|
25
|
+
return { signing: secrets[0], byKid };
|
|
26
|
+
}
|
|
27
|
+
export async function signAccessToken(keyring, app, claims, now, ttlMs) {
|
|
28
|
+
const accessTokenExpiresAt = now + ttlMs;
|
|
29
|
+
const accessToken = await new SignJWT({ did: claims.deviceId })
|
|
30
|
+
.setProtectedHeader({ alg: "HS256", typ: "JWT", kid: keyring.signing.kid })
|
|
31
|
+
.setIssuer(app)
|
|
32
|
+
.setAudience(app)
|
|
33
|
+
.setSubject(claims.userId)
|
|
34
|
+
.setIssuedAt(Math.floor(now / 1000))
|
|
35
|
+
.setExpirationTime(Math.floor(accessTokenExpiresAt / 1000))
|
|
36
|
+
.sign(keyring.signing.key);
|
|
37
|
+
return { accessToken, accessTokenExpiresAt };
|
|
38
|
+
}
|
|
39
|
+
export async function verifyAccessToken(keyring, app, token, now) {
|
|
40
|
+
try {
|
|
41
|
+
const { payload } = await jwtVerify(token, (header) => {
|
|
42
|
+
const key = header.kid ? keyring.byKid.get(header.kid) : undefined;
|
|
43
|
+
if (!key)
|
|
44
|
+
throw new Error("unknown kid");
|
|
45
|
+
return key;
|
|
46
|
+
}, { issuer: app, audience: app, algorithms: ["HS256"], requiredClaims: ["exp"], currentDate: new Date(now) });
|
|
47
|
+
if (typeof payload.sub !== "string" || payload.sub.length === 0)
|
|
48
|
+
return null;
|
|
49
|
+
if (typeof payload.did !== "string" || payload.did.length === 0)
|
|
50
|
+
return null;
|
|
51
|
+
return { userId: payload.sub, deviceId: payload.did };
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function verifyLegacyAccessToken(config, token, now) {
|
|
58
|
+
if (!config.secret || config.secret.length < MIN_SECRET_LENGTH)
|
|
59
|
+
return null;
|
|
60
|
+
try {
|
|
61
|
+
const { payload } = await jwtVerify(token, new TextEncoder().encode(config.secret), {
|
|
62
|
+
issuer: config.issuer,
|
|
63
|
+
audience: config.audience,
|
|
64
|
+
algorithms: ["HS256"],
|
|
65
|
+
requiredClaims: ["exp"],
|
|
66
|
+
currentDate: new Date(now),
|
|
67
|
+
});
|
|
68
|
+
return typeof payload.sub === "string" && payload.sub.length > 0 ? payload.sub : null;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function newRefreshSecret() {
|
|
75
|
+
const bytes = new Uint8Array(32);
|
|
76
|
+
crypto.getRandomValues(bytes);
|
|
77
|
+
return base64url(bytes);
|
|
78
|
+
}
|
|
79
|
+
export function joinRefreshToken(parts) {
|
|
80
|
+
return `${parts.deviceId}.${parts.secret}`;
|
|
81
|
+
}
|
|
82
|
+
export function splitRefreshToken(token) {
|
|
83
|
+
const dot = token.indexOf(".");
|
|
84
|
+
if (dot <= 0 || dot === token.length - 1)
|
|
85
|
+
return null;
|
|
86
|
+
return { deviceId: token.slice(0, dot), secret: token.slice(dot + 1) };
|
|
87
|
+
}
|
|
88
|
+
export async function hashSecret(secret) {
|
|
89
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
|
|
90
|
+
return base64url(new Uint8Array(digest));
|
|
91
|
+
}
|
|
92
|
+
export function constantTimeEqual(a, b) {
|
|
93
|
+
if (a.length !== b.length)
|
|
94
|
+
return false;
|
|
95
|
+
let diff = 0;
|
|
96
|
+
for (let i = 0; i < a.length; i++)
|
|
97
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
98
|
+
return diff === 0;
|
|
99
|
+
}
|
|
100
|
+
export function base64url(bytes) {
|
|
101
|
+
let text = "";
|
|
102
|
+
for (const b of bytes)
|
|
103
|
+
text += String.fromCharCode(b);
|
|
104
|
+
return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
105
|
+
}
|