@aglyn/tenant-data-admin 1.22.3 → 1.23.0
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/package.json +7 -7
- package/src/lib/server/edit-access-token.d.ts +26 -1
- package/src/lib/server/edit-access-token.js +23 -2
- package/src/lib/server/edit-access-token.js.map +1 -1
- package/src/lib/server/edit-hint-end.d.ts +104 -0
- package/src/lib/server/edit-hint-end.js +130 -0
- package/src/lib/server/edit-hint-end.js.map +1 -0
- package/src/lib/server/edit-hint-token.d.ts +33 -1
- package/src/lib/server/edit-hint-token.js +32 -2
- package/src/lib/server/edit-hint-token.js.map +1 -1
- package/src/lib/server/token-revocation.d.ts +18 -0
- package/src/lib/server/token-revocation.js +12 -0
- package/src/lib/server/token-revocation.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +1 -0
- package/src/tenancy.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.23.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-util-email": "1.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.23.0",
|
|
29
|
+
"@aglyn/shared-util-email": "1.23.0",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.23.0",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.23.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.23.0",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.23.0",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.24",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -49,6 +49,31 @@ export interface EditAccessClaims {
|
|
|
49
49
|
uid: string;
|
|
50
50
|
/** Expiry, epoch ms. */
|
|
51
51
|
exp: number;
|
|
52
|
+
/**
|
|
53
|
+
* The console browser behind this token (its `aglyn_device` id) and when
|
|
54
|
+
* that browser's console session was last proven live, epoch ms. Set when
|
|
55
|
+
* the minter knows them; the tenant's `/api/edit-context` then refuses the
|
|
56
|
+
* token once that browser has signed out of the console since `since`
|
|
57
|
+
* (`edit-hint-end.ts`), instead of honouring it for the rest of its 30
|
|
58
|
+
* minutes.
|
|
59
|
+
*/
|
|
60
|
+
did?: string;
|
|
61
|
+
since?: number;
|
|
62
|
+
/**
|
|
63
|
+
* The auth pool the uid lives in: a GCIP tenant id, or `''` for the
|
|
64
|
+
* project pool (AGL-2005). Lets `/api/edit-context` ask the RIGHT pool
|
|
65
|
+
* whether the account signed out everywhere since `since`, without a
|
|
66
|
+
* cross-pool search on every page view. Only ever present beside `did` and
|
|
67
|
+
* `since`; a token without it skips that check and keeps its short life.
|
|
68
|
+
*/
|
|
69
|
+
pool?: string;
|
|
70
|
+
}
|
|
71
|
+
/** The browser binding a mint may carry; see {@link EditAccessClaims}. */
|
|
72
|
+
export interface EditAccessBinding {
|
|
73
|
+
did: string;
|
|
74
|
+
since: number;
|
|
75
|
+
/** See {@link EditAccessClaims.pool}. */
|
|
76
|
+
pool?: string;
|
|
52
77
|
}
|
|
53
78
|
export interface MintedEditAccessToken {
|
|
54
79
|
token: string;
|
|
@@ -62,7 +87,7 @@ export interface MintedEditAccessToken {
|
|
|
62
87
|
* (a verified signed hint, AGL-1842). The mint itself checks nothing, which is
|
|
63
88
|
* why it must never be reachable from unverified input.
|
|
64
89
|
*/
|
|
65
|
-
export declare function mintEditAccessToken(hostId: string, uid: string, nowMs?: number): MintedEditAccessToken;
|
|
90
|
+
export declare function mintEditAccessToken(hostId: string, uid: string, nowMs?: number, binding?: EditAccessBinding): MintedEditAccessToken;
|
|
66
91
|
/**
|
|
67
92
|
* Verifies a presented token and returns its claims, or `null` for anything
|
|
68
93
|
* else — expired, tampered, malformed, wrong version, or a deploy with no
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -57,10 +58,18 @@ function signPayload(payloadB64) {
|
|
|
57
58
|
* (a verified Firebase ID token) and the tenant's `/api/edit-access/exchange`
|
|
58
59
|
* (a verified signed hint, AGL-1842). The mint itself checks nothing, which is
|
|
59
60
|
* why it must never be reachable from unverified input.
|
|
60
|
-
*/ export function mintEditAccessToken(hostId, uid, nowMs = Date.now()) {
|
|
61
|
+
*/ export function mintEditAccessToken(hostId, uid, nowMs = Date.now(), binding) {
|
|
61
62
|
if (!hostId || !uid) throw new Error('hostId and uid are required');
|
|
62
63
|
const exp = nowMs + EDIT_ACCESS_TOKEN_TTL_MS;
|
|
63
|
-
const claims = {
|
|
64
|
+
const claims = binding ? _extends({
|
|
65
|
+
hostId,
|
|
66
|
+
uid,
|
|
67
|
+
exp,
|
|
68
|
+
did: binding.did,
|
|
69
|
+
since: binding.since
|
|
70
|
+
}, typeof binding.pool === 'string' ? {
|
|
71
|
+
pool: binding.pool
|
|
72
|
+
} : {}) : {
|
|
64
73
|
hostId,
|
|
65
74
|
uid,
|
|
66
75
|
exp
|
|
@@ -106,6 +115,18 @@ function signPayload(payloadB64) {
|
|
|
106
115
|
if (!Number.isFinite(exp) || exp <= nowMs) return null;
|
|
107
116
|
if (typeof claims.hostId !== 'string' || !claims.hostId) return null;
|
|
108
117
|
if (typeof claims.uid !== 'string' || !claims.uid) return null;
|
|
118
|
+
const since = Number(claims.since);
|
|
119
|
+
if (typeof claims.did === 'string' && claims.did && Number.isFinite(since) && since > 0) {
|
|
120
|
+
return _extends({
|
|
121
|
+
hostId: claims.hostId,
|
|
122
|
+
uid: claims.uid,
|
|
123
|
+
exp,
|
|
124
|
+
did: claims.did,
|
|
125
|
+
since
|
|
126
|
+
}, typeof claims.pool === 'string' && claims.pool.length <= 128 ? {
|
|
127
|
+
pool: claims.pool
|
|
128
|
+
} : {});
|
|
129
|
+
}
|
|
109
130
|
return {
|
|
110
131
|
hostId: claims.hostId,
|
|
111
132
|
uid: claims.uid,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-access-token.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac } from 'crypto'\nimport { safeEqual } from './safe-equal'\nimport { tokenSigningSecret } from './media-signing'\n\n/**\n * Edit-access tokens for the tenant admin bar (admin edit bar, AGL-1302\n * follow-on).\n *\n * The console session lives first-party on app.aglyn.com; published sites\n * live on aglyn.app subdomains and customer domains, and with third-party\n * cookies gone an embedded console frame cannot see its own session. So the\n * console VERIFIES edit access server-side (the same host-scoped gate the\n * presence broker applies for co-editing: a role on this host that may write\n * content, or an org-wide role above viewer) and bakes the verdict into a\n * short-lived token the tenant can check without asking anyone:\n * `{hostId, uid, exp}` HMAC-signed with the shared, fail-closed\n * `TOKEN_SIGNING_SECRET` (docs/COMMERCE_TOKEN_SIGNING.md) — already\n * provisioned on both the console and tenant projects, which is the whole\n * reason to reuse it rather than mint a second secret to keep in step.\n *\n * Deliberately NOT an auth system: the token grants nothing but the admin\n * bar's convenience UI, a read of routing facts the page HTML already\n * carries, and the site's page-view counts for today, which are not public —\n * the reason the mint must scope to the host. It is scoped to ONE host,\n * expires in {@link EDIT_ACCESS_TOKEN_TTL_MS}, and revocation is the\n * `release_edit_bar` flag — flipping it off makes every outstanding token\n * useless at the verify site.\n * The `edit-bar:` context string domain-separates the signature so a token\n * minted here can never replay as a media or commerce signature (they share\n * the secret, so the namespace is the isolation).\n */\n\n/** 30 minutes — well under the ≤1h ceiling; reconnecting is one click. */\nexport const EDIT_ACCESS_TOKEN_TTL_MS = 30 * 60 * 1000\n\n/**\n * Version tag on the wire so a future claim change can reject old tokens by\n * shape instead of by signature failure (clearer to debug).\n */\nconst TOKEN_PREFIX = 'aglyn-edit-bar-v1'\n\nexport interface EditAccessClaims {\n /** The ONE host the console proved the caller may edit. */\n hostId: string\n uid: string\n /** Expiry, epoch ms. */\n exp: number\n}\n\nfunction signPayload(payloadB64: string): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`edit-bar:${payloadB64}`)\n .digest('base64url')\n}\n\nexport interface MintedEditAccessToken {\n token: string\n expiresAtMs: number\n}\n\n/**\n * Mints a token asserting \"this uid may edit this host, until exp\". Two\n * routes call this, each only AFTER proving who the caller is and passing the\n * shared `editAccessMintRefusal` gate: the console's `/api/edit-access/token`\n * (a verified Firebase ID token) and the tenant's `/api/edit-access/exchange`\n * (a verified signed hint, AGL-1842). The mint itself checks nothing, which is\n * why it must never be reachable from unverified input.\n */\nexport function mintEditAccessToken(\n hostId: string,\n uid: string,\n nowMs: number = Date.now(),\n): MintedEditAccessToken {\n if (!hostId || !uid) throw new Error('hostId and uid are required')\n const exp = nowMs + EDIT_ACCESS_TOKEN_TTL_MS\n const claims: EditAccessClaims = { hostId, uid, exp }\n const payload = Buffer.from(JSON.stringify(claims), 'utf8').toString(\n 'base64url',\n )\n // The signature covers the ENCODED payload, so there is exactly one byte\n // string being signed and verified — no re-serialization ambiguity.\n return {\n token: `${TOKEN_PREFIX}.${payload}.${signPayload(payload)}`,\n expiresAtMs: exp,\n }\n}\n\n/**\n * Verifies a presented token and returns its claims, or `null` for anything\n * else — expired, tampered, malformed, wrong version, or a deploy with no\n * signing secret (fail closed, like the media signatures). Callers must still\n * check `claims.hostId` against the host actually being served.\n */\nexport function verifyEditAccessToken(\n token: unknown,\n nowMs: number = Date.now(),\n): EditAccessClaims | null {\n if (typeof token !== 'string' || token.length === 0 || token.length > 4096) {\n return null\n }\n const parts = token.split('.')\n if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null\n const [, payload, sig] = parts\n let expected: string\n try {\n expected = signPayload(payload)\n } catch {\n // Secret missing — refuse rather than trusting anything.\n return null\n }\n // `safeEqual` length-checks before `timingSafeEqual`, which THROWS on\n // mismatched lengths an attacker controls — a 500 where a 401 belongs. One\n // implementation since AGL-1902; this was one of six hand-written copies.\n if (!safeEqual(sig, expected)) return null\n let claims: EditAccessClaims\n try {\n claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n } catch {\n return null\n }\n const exp = Number(claims?.exp)\n if (!Number.isFinite(exp) || exp <= nowMs) return null\n if (typeof claims.hostId !== 'string' || !claims.hostId) return null\n if (typeof claims.uid !== 'string' || !claims.uid) return null\n return { hostId: claims.hostId, uid: claims.uid, exp }\n}\n"],"names":["createHmac","safeEqual","tokenSigningSecret","EDIT_ACCESS_TOKEN_TTL_MS","TOKEN_PREFIX","signPayload","payloadB64","update","digest","mintEditAccessToken","hostId","uid","nowMs","Date","now","Error","exp","claims","payload","Buffer","from","JSON","stringify","toString","token","expiresAtMs","verifyEditAccessToken","length","parts","split","sig","expected","parse","Number","isFinite"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,kBAAkB,QAAQ,qBA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KC,WAAW,OAAO;IACtC,IAAId;IACJ,IAAI;QACFA,SAASI,KAAKW,KAAK,CAACb,OAAOC,IAAI,CAACF,SAAS,aAAaK,QAAQ,CAAC;IACjE,EAAE,eAAM;QACN,OAAO;IACT;IACA,MAAMP,MAAMiB,OAAOhB,0BAAAA,OAAQD,GAAG;IAC9B,IAAI,CAACiB,OAAOC,QAAQ,CAAClB,QAAQA,OAAOJ,OAAO,OAAO;IAClD,IAAI,OAAOK,OAAOP,MAAM,KAAK,YAAY,CAACO,OAAOP,MAAM,EAAE,OAAO;IAChE,IAAI,OAAOO,OAAON,GAAG,KAAK,YAAY,CAACM,OAAON,GAAG,EAAE,OAAO;IAC1D,OAAO;QAAED,QAAQO,OAAOP,MAAM;QAAEC,KAAKM,OAAON,GAAG;QAAEK;IAAI;AACvD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-access-token.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac } from 'crypto'\nimport { safeEqual } from './safe-equal'\nimport { tokenSigningSecret } from './media-signing'\n\n/**\n * Edit-access tokens for the tenant admin bar (admin edit bar, AGL-1302\n * follow-on).\n *\n * The console session lives first-party on app.aglyn.com; published sites\n * live on aglyn.app subdomains and customer domains, and with third-party\n * cookies gone an embedded console frame cannot see its own session. So the\n * console VERIFIES edit access server-side (the same host-scoped gate the\n * presence broker applies for co-editing: a role on this host that may write\n * content, or an org-wide role above viewer) and bakes the verdict into a\n * short-lived token the tenant can check without asking anyone:\n * `{hostId, uid, exp}` HMAC-signed with the shared, fail-closed\n * `TOKEN_SIGNING_SECRET` (docs/COMMERCE_TOKEN_SIGNING.md) — already\n * provisioned on both the console and tenant projects, which is the whole\n * reason to reuse it rather than mint a second secret to keep in step.\n *\n * Deliberately NOT an auth system: the token grants nothing but the admin\n * bar's convenience UI, a read of routing facts the page HTML already\n * carries, and the site's page-view counts for today, which are not public —\n * the reason the mint must scope to the host. It is scoped to ONE host,\n * expires in {@link EDIT_ACCESS_TOKEN_TTL_MS}, and revocation is the\n * `release_edit_bar` flag — flipping it off makes every outstanding token\n * useless at the verify site.\n * The `edit-bar:` context string domain-separates the signature so a token\n * minted here can never replay as a media or commerce signature (they share\n * the secret, so the namespace is the isolation).\n */\n\n/** 30 minutes — well under the ≤1h ceiling; reconnecting is one click. */\nexport const EDIT_ACCESS_TOKEN_TTL_MS = 30 * 60 * 1000\n\n/**\n * Version tag on the wire so a future claim change can reject old tokens by\n * shape instead of by signature failure (clearer to debug).\n */\nconst TOKEN_PREFIX = 'aglyn-edit-bar-v1'\n\nexport interface EditAccessClaims {\n /** The ONE host the console proved the caller may edit. */\n hostId: string\n uid: string\n /** Expiry, epoch ms. */\n exp: number\n /**\n * The console browser behind this token (its `aglyn_device` id) and when\n * that browser's console session was last proven live, epoch ms. Set when\n * the minter knows them; the tenant's `/api/edit-context` then refuses the\n * token once that browser has signed out of the console since `since`\n * (`edit-hint-end.ts`), instead of honouring it for the rest of its 30\n * minutes.\n */\n did?: string\n since?: number\n /**\n * The auth pool the uid lives in: a GCIP tenant id, or `''` for the\n * project pool (AGL-2005). Lets `/api/edit-context` ask the RIGHT pool\n * whether the account signed out everywhere since `since`, without a\n * cross-pool search on every page view. Only ever present beside `did` and\n * `since`; a token without it skips that check and keeps its short life.\n */\n pool?: string\n}\n\n/** The browser binding a mint may carry; see {@link EditAccessClaims}. */\nexport interface EditAccessBinding {\n did: string\n since: number\n /** See {@link EditAccessClaims.pool}. */\n pool?: string\n}\n\nfunction signPayload(payloadB64: string): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`edit-bar:${payloadB64}`)\n .digest('base64url')\n}\n\nexport interface MintedEditAccessToken {\n token: string\n expiresAtMs: number\n}\n\n/**\n * Mints a token asserting \"this uid may edit this host, until exp\". Two\n * routes call this, each only AFTER proving who the caller is and passing the\n * shared `editAccessMintRefusal` gate: the console's `/api/edit-access/token`\n * (a verified Firebase ID token) and the tenant's `/api/edit-access/exchange`\n * (a verified signed hint, AGL-1842). The mint itself checks nothing, which is\n * why it must never be reachable from unverified input.\n */\nexport function mintEditAccessToken(\n hostId: string,\n uid: string,\n nowMs: number = Date.now(),\n binding?: EditAccessBinding,\n): MintedEditAccessToken {\n if (!hostId || !uid) throw new Error('hostId and uid are required')\n const exp = nowMs + EDIT_ACCESS_TOKEN_TTL_MS\n const claims: EditAccessClaims = binding\n ? {\n hostId,\n uid,\n exp,\n did: binding.did,\n since: binding.since,\n ...(typeof binding.pool === 'string' ? { pool: binding.pool } : {}),\n }\n : { hostId, uid, exp }\n const payload = Buffer.from(JSON.stringify(claims), 'utf8').toString(\n 'base64url',\n )\n // The signature covers the ENCODED payload, so there is exactly one byte\n // string being signed and verified — no re-serialization ambiguity.\n return {\n token: `${TOKEN_PREFIX}.${payload}.${signPayload(payload)}`,\n expiresAtMs: exp,\n }\n}\n\n/**\n * Verifies a presented token and returns its claims, or `null` for anything\n * else — expired, tampered, malformed, wrong version, or a deploy with no\n * signing secret (fail closed, like the media signatures). Callers must still\n * check `claims.hostId` against the host actually being served.\n */\nexport function verifyEditAccessToken(\n token: unknown,\n nowMs: number = Date.now(),\n): EditAccessClaims | null {\n if (typeof token !== 'string' || token.length === 0 || token.length > 4096) {\n return null\n }\n const parts = token.split('.')\n if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null\n const [, payload, sig] = parts\n let expected: string\n try {\n expected = signPayload(payload)\n } catch {\n // Secret missing — refuse rather than trusting anything.\n return null\n }\n // `safeEqual` length-checks before `timingSafeEqual`, which THROWS on\n // mismatched lengths an attacker controls — a 500 where a 401 belongs. One\n // implementation since AGL-1902; this was one of six hand-written copies.\n if (!safeEqual(sig, expected)) return null\n let claims: EditAccessClaims\n try {\n claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n } catch {\n return null\n }\n const exp = Number(claims?.exp)\n if (!Number.isFinite(exp) || exp <= nowMs) return null\n if (typeof claims.hostId !== 'string' || !claims.hostId) return null\n if (typeof claims.uid !== 'string' || !claims.uid) return null\n const since = Number(claims.since)\n if (\n typeof claims.did === 'string' &&\n claims.did &&\n Number.isFinite(since) &&\n since > 0\n ) {\n return {\n hostId: claims.hostId,\n uid: claims.uid,\n exp,\n did: claims.did,\n since,\n ...(typeof claims.pool === 'string' && claims.pool.length <= 128\n ? { pool: claims.pool }\n : {}),\n }\n }\n return { hostId: claims.hostId, uid: claims.uid, exp }\n}\n"],"names":["createHmac","safeEqual","tokenSigningSecret","EDIT_ACCESS_TOKEN_TTL_MS","TOKEN_PREFIX","signPayload","payloadB64","update","digest","mintEditAccessToken","hostId","uid","nowMs","Date","now","binding","Error","exp","claims","did","since","pool","payload","Buffer","from","JSON","stringify","toString","token","expiresAtMs","verifyEditAccessToken","length","parts","split","sig","expected","parse","Number","isFinite"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,SAAS,QAAQ,kBAAc;AACxC,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,wEAAwE,GACxE,OAAO,MAAMC,2BAA2B,KAAK,KAAK,KAAI;AAEtD;;;CAGC,GACD,MAAMC,eAAe;AAoCrB,SAASC,YAAYC,UAAkB;IACrC,OAAON,WAAW,UAAUE,sBACzBK,MAAM,CAAC,CAAC,SAAS,EAAED,YAAY,EAC/BE,MAAM,CAAC;AACZ;AAOA;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,GAAW,EACXC,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ACN,OAAO;IACT;IACA,MAAMV,MAAMoB,OAAOnB,0BAAAA,OAAQD,GAAG;IAC9B,IAAI,CAACoB,OAAOC,QAAQ,CAACrB,QAAQA,OAAOL,OAAO,OAAO;IAClD,IAAI,OAAOM,OAAOR,MAAM,KAAK,YAAY,CAACQ,OAAOR,MAAM,EAAE,OAAO;IAChE,IAAI,OAAOQ,OAAOP,GAAG,KAAK,YAAY,CAACO,OAAOP,GAAG,EAAE,OAAO;IAC1D,MAAMS,QAAQiB,OAAOnB,OAAOE,KAAK;IACjC,IACE,OAAOF,OAAOC,GAAG,KAAK,YACtBD,OAAOC,GAAG,IACVkB,OAAOC,QAAQ,CAAClB,UAChBA,QAAQ,GACR;QACA,OAAO;YACLV,QAAQQ,OAAOR,MAAM;YACrBC,KAAKO,OAAOP,GAAG;YACfM;YACAE,KAAKD,OAAOC,GAAG;YACfC;WACI,OAAOF,OAAOG,IAAI,KAAK,YAAYH,OAAOG,IAAI,CAACU,MAAM,IAAI,MACzD;YAAEV,MAAMH,OAAOG,IAAI;QAAC,IACpB,CAAC;IAET;IACA,OAAO;QAAEX,QAAQQ,OAAOR,MAAM;QAAEC,KAAKO,OAAOP,GAAG;QAAEM;IAAI;AACvD"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { Firestore } from 'firebase-admin/firestore';
|
|
18
|
+
/**
|
|
19
|
+
* Console sign-out ends the site edit bar in THAT browser (AGL-1842
|
|
20
|
+
* follow-on).
|
|
21
|
+
*
|
|
22
|
+
* The `.aglyn.app` hint cookies live on a registrable domain the console
|
|
23
|
+
* cannot write, so clearing them at sign-out is best-effort at most: a tab
|
|
24
|
+
* closed mid-sign-out never gets there. The ending therefore happens on the
|
|
25
|
+
* server. Sign-out writes one document per browser,
|
|
26
|
+
* `users/{uid}/editHintEnds/{did}` with `endedAt`, where `did` is the
|
|
27
|
+
* console's `aglyn_device` id for that browser. Every hint and every
|
|
28
|
+
* edit-access token minted from that browser carries the same `did` and the
|
|
29
|
+
* time its console session was last proven live; the exchange and
|
|
30
|
+
* `/api/edit-context` refuse anything dated before `endedAt`.
|
|
31
|
+
*
|
|
32
|
+
* Per browser, by construction: another browser has another `did`, so the
|
|
33
|
+
* same person signed in elsewhere keeps their bar. Signing back in here mints
|
|
34
|
+
* a newer hint and the bar returns, with nothing to undo. One document per
|
|
35
|
+
* browser the person has signed out of, overwritten each time, so it needs no
|
|
36
|
+
* expiry; `eraseUser`'s `recursiveDelete(users/{uid})` takes it with the
|
|
37
|
+
* account.
|
|
38
|
+
*
|
|
39
|
+
* Admin SDK only. The collection has no rules match, so clients can neither
|
|
40
|
+
* read nor write it.
|
|
41
|
+
*
|
|
42
|
+
* Two other endings reach the bar without writing anything new (AGL-1842,
|
|
43
|
+
* "sign out everywhere" and removing a device): a device signed out from the
|
|
44
|
+
* device list ends that browser through its own `devices/{did}.revokedAt`
|
|
45
|
+
* stamp, read beside this record, and an account-wide sign-out ends every
|
|
46
|
+
* browser through the account's `tokensValidAfterTime`
|
|
47
|
+
* ({@link accountEndRefuses}).
|
|
48
|
+
*/
|
|
49
|
+
export declare const EDIT_HINT_ENDS_COLLECTION = "editHintEnds";
|
|
50
|
+
type FirestoreLike = Pick<Firestore, 'collection'>;
|
|
51
|
+
/** Records that `uid` signed out of the console in browser `did`. */
|
|
52
|
+
export declare function recordEditHintEnded(firestore: FirestoreLike, uid: string, did: string, nowMs?: number): Promise<boolean>;
|
|
53
|
+
/**
|
|
54
|
+
* `users/{uid}/devices/{did}`, the console's sign-in history row for the same
|
|
55
|
+
* browser (`device-registry.ts` in the console names it `DEVICES_COLLECTION`).
|
|
56
|
+
* Its `revokedAt` is stamped when that one device is signed out from the
|
|
57
|
+
* Recent sign-ins list or by staff. Read here, never written: the ending it
|
|
58
|
+
* records is reused as it stands, with no second write at revoke time.
|
|
59
|
+
*/
|
|
60
|
+
export declare const EDIT_HINT_DEVICES_COLLECTION = "devices";
|
|
61
|
+
/**
|
|
62
|
+
* When browser `did` was last ended for `uid`; 0 if never. The later of two
|
|
63
|
+
* records, read side by side:
|
|
64
|
+
*
|
|
65
|
+
* - its console sign-out (`editHintEnds/{did}.endedAt`, written by
|
|
66
|
+
* `DELETE /api/auth/session`);
|
|
67
|
+
* - that device being signed out from the device list
|
|
68
|
+
* (`devices/{did}.revokedAt`). The hint's `did` IS the device row's id: both
|
|
69
|
+
* are the browser's `aglyn_device` cookie. So removing a device ends that
|
|
70
|
+
* device's bar, and no other device's, through this record alone.
|
|
71
|
+
*
|
|
72
|
+
* Signing out EVERYWHERE is account-wide and lives on the account instead
|
|
73
|
+
* (`tokensValidAfterTime`); see {@link accountEndRefuses}.
|
|
74
|
+
*/
|
|
75
|
+
export declare function readEditHintEndedAt(firestore: FirestoreLike, uid: string, did: string): Promise<number>;
|
|
76
|
+
/**
|
|
77
|
+
* Does a sign-out at `endedAtMs` end a credential whose session was proven
|
|
78
|
+
* live at `provenAtMs`? An undateable credential cannot be shown to postdate
|
|
79
|
+
* the sign-out, so it is refused, the same safe direction as device
|
|
80
|
+
* revocation.
|
|
81
|
+
*/
|
|
82
|
+
export declare function editHintEndRefuses(endedAtMs: number, provenAtMs: number | null | undefined): boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Does the account's own revocation epoch end a credential proven live at
|
|
85
|
+
* `provenAtMs`?
|
|
86
|
+
*
|
|
87
|
+
* "Sign out everywhere", a password reset, a lock, a disable or a demotion
|
|
88
|
+
* all end every session through `revokeRefreshTokens`, which moves the
|
|
89
|
+
* account's `tokensValidAfterTime`. Every browser's hint and edit token
|
|
90
|
+
* proven live before that moment is refused, on every browser at once, and
|
|
91
|
+
* nothing extra is written: the epoch is the record. A hint minted after it
|
|
92
|
+
* came from a session that passed the same revocation check, so signing back
|
|
93
|
+
* in restores the bar with nothing to undo.
|
|
94
|
+
*
|
|
95
|
+
* Whole seconds on both sides, the same comparison `revocationRefuses` makes
|
|
96
|
+
* for ID tokens: `tokensValidAfterTime` has second granularity, so comparing
|
|
97
|
+
* milliseconds would refuse a hint minted in the same second on one process
|
|
98
|
+
* and admit it on the next.
|
|
99
|
+
*
|
|
100
|
+
* @param validAfter - `tokensValidAfterTime` as the Admin SDK returns it (an
|
|
101
|
+
* RFC-1123 string) or as epoch ms; absent when never revoked
|
|
102
|
+
*/
|
|
103
|
+
export declare function accountEndRefuses(validAfter: string | number | null | undefined, provenAtMs: number | null | undefined): boolean;
|
|
104
|
+
export {};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { isEditHintDeviceId } from "./edit-hint-token.js";
|
|
17
|
+
/**
|
|
18
|
+
* Console sign-out ends the site edit bar in THAT browser (AGL-1842
|
|
19
|
+
* follow-on).
|
|
20
|
+
*
|
|
21
|
+
* The `.aglyn.app` hint cookies live on a registrable domain the console
|
|
22
|
+
* cannot write, so clearing them at sign-out is best-effort at most: a tab
|
|
23
|
+
* closed mid-sign-out never gets there. The ending therefore happens on the
|
|
24
|
+
* server. Sign-out writes one document per browser,
|
|
25
|
+
* `users/{uid}/editHintEnds/{did}` with `endedAt`, where `did` is the
|
|
26
|
+
* console's `aglyn_device` id for that browser. Every hint and every
|
|
27
|
+
* edit-access token minted from that browser carries the same `did` and the
|
|
28
|
+
* time its console session was last proven live; the exchange and
|
|
29
|
+
* `/api/edit-context` refuse anything dated before `endedAt`.
|
|
30
|
+
*
|
|
31
|
+
* Per browser, by construction: another browser has another `did`, so the
|
|
32
|
+
* same person signed in elsewhere keeps their bar. Signing back in here mints
|
|
33
|
+
* a newer hint and the bar returns, with nothing to undo. One document per
|
|
34
|
+
* browser the person has signed out of, overwritten each time, so it needs no
|
|
35
|
+
* expiry; `eraseUser`'s `recursiveDelete(users/{uid})` takes it with the
|
|
36
|
+
* account.
|
|
37
|
+
*
|
|
38
|
+
* Admin SDK only. The collection has no rules match, so clients can neither
|
|
39
|
+
* read nor write it.
|
|
40
|
+
*
|
|
41
|
+
* Two other endings reach the bar without writing anything new (AGL-1842,
|
|
42
|
+
* "sign out everywhere" and removing a device): a device signed out from the
|
|
43
|
+
* device list ends that browser through its own `devices/{did}.revokedAt`
|
|
44
|
+
* stamp, read beside this record, and an account-wide sign-out ends every
|
|
45
|
+
* browser through the account's `tokensValidAfterTime`
|
|
46
|
+
* ({@link accountEndRefuses}).
|
|
47
|
+
*/ export const EDIT_HINT_ENDS_COLLECTION = 'editHintEnds';
|
|
48
|
+
function endDoc(firestore, uid, did) {
|
|
49
|
+
return firestore.collection('users').doc(uid).collection(EDIT_HINT_ENDS_COLLECTION).doc(did);
|
|
50
|
+
}
|
|
51
|
+
/** Records that `uid` signed out of the console in browser `did`. */ export async function recordEditHintEnded(firestore, uid, did, nowMs = Date.now()) {
|
|
52
|
+
if (!uid || !isEditHintDeviceId(did)) return false;
|
|
53
|
+
await endDoc(firestore, uid, did).set({
|
|
54
|
+
endedAt: nowMs
|
|
55
|
+
});
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `users/{uid}/devices/{did}`, the console's sign-in history row for the same
|
|
60
|
+
* browser (`device-registry.ts` in the console names it `DEVICES_COLLECTION`).
|
|
61
|
+
* Its `revokedAt` is stamped when that one device is signed out from the
|
|
62
|
+
* Recent sign-ins list or by staff. Read here, never written: the ending it
|
|
63
|
+
* records is reused as it stands, with no second write at revoke time.
|
|
64
|
+
*/ export const EDIT_HINT_DEVICES_COLLECTION = 'devices';
|
|
65
|
+
function epochField(snapshot, field) {
|
|
66
|
+
var _snapshot_get;
|
|
67
|
+
if (!snapshot.exists) return 0;
|
|
68
|
+
const value = Number((_snapshot_get = snapshot.get(field)) != null ? _snapshot_get : 0);
|
|
69
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* When browser `did` was last ended for `uid`; 0 if never. The later of two
|
|
73
|
+
* records, read side by side:
|
|
74
|
+
*
|
|
75
|
+
* - its console sign-out (`editHintEnds/{did}.endedAt`, written by
|
|
76
|
+
* `DELETE /api/auth/session`);
|
|
77
|
+
* - that device being signed out from the device list
|
|
78
|
+
* (`devices/{did}.revokedAt`). The hint's `did` IS the device row's id: both
|
|
79
|
+
* are the browser's `aglyn_device` cookie. So removing a device ends that
|
|
80
|
+
* device's bar, and no other device's, through this record alone.
|
|
81
|
+
*
|
|
82
|
+
* Signing out EVERYWHERE is account-wide and lives on the account instead
|
|
83
|
+
* (`tokensValidAfterTime`); see {@link accountEndRefuses}.
|
|
84
|
+
*/ export async function readEditHintEndedAt(firestore, uid, did) {
|
|
85
|
+
if (!uid || !isEditHintDeviceId(did)) return 0;
|
|
86
|
+
const [ended, device] = await Promise.all([
|
|
87
|
+
endDoc(firestore, uid, did).get(),
|
|
88
|
+
firestore.collection('users').doc(uid).collection(EDIT_HINT_DEVICES_COLLECTION).doc(did).get()
|
|
89
|
+
]);
|
|
90
|
+
return Math.max(epochField(ended, 'endedAt'), epochField(device, 'revokedAt'));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Does a sign-out at `endedAtMs` end a credential whose session was proven
|
|
94
|
+
* live at `provenAtMs`? An undateable credential cannot be shown to postdate
|
|
95
|
+
* the sign-out, so it is refused, the same safe direction as device
|
|
96
|
+
* revocation.
|
|
97
|
+
*/ export function editHintEndRefuses(endedAtMs, provenAtMs) {
|
|
98
|
+
if (!endedAtMs) return false;
|
|
99
|
+
const proven = Number(provenAtMs != null ? provenAtMs : 0);
|
|
100
|
+
if (!Number.isFinite(proven) || proven <= 0) return true;
|
|
101
|
+
return proven <= endedAtMs;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Does the account's own revocation epoch end a credential proven live at
|
|
105
|
+
* `provenAtMs`?
|
|
106
|
+
*
|
|
107
|
+
* "Sign out everywhere", a password reset, a lock, a disable or a demotion
|
|
108
|
+
* all end every session through `revokeRefreshTokens`, which moves the
|
|
109
|
+
* account's `tokensValidAfterTime`. Every browser's hint and edit token
|
|
110
|
+
* proven live before that moment is refused, on every browser at once, and
|
|
111
|
+
* nothing extra is written: the epoch is the record. A hint minted after it
|
|
112
|
+
* came from a session that passed the same revocation check, so signing back
|
|
113
|
+
* in restores the bar with nothing to undo.
|
|
114
|
+
*
|
|
115
|
+
* Whole seconds on both sides, the same comparison `revocationRefuses` makes
|
|
116
|
+
* for ID tokens: `tokensValidAfterTime` has second granularity, so comparing
|
|
117
|
+
* milliseconds would refuse a hint minted in the same second on one process
|
|
118
|
+
* and admit it on the next.
|
|
119
|
+
*
|
|
120
|
+
* @param validAfter - `tokensValidAfterTime` as the Admin SDK returns it (an
|
|
121
|
+
* RFC-1123 string) or as epoch ms; absent when never revoked
|
|
122
|
+
*/ export function accountEndRefuses(validAfter, provenAtMs) {
|
|
123
|
+
const validAfterMs = typeof validAfter === 'string' ? Date.parse(validAfter) : Number(validAfter != null ? validAfter : 0);
|
|
124
|
+
if (!Number.isFinite(validAfterMs) || validAfterMs <= 0) return false;
|
|
125
|
+
const proven = Number(provenAtMs != null ? provenAtMs : 0);
|
|
126
|
+
if (!Number.isFinite(proven) || proven <= 0) return true;
|
|
127
|
+
return Math.floor(proven / 1000) < Math.floor(validAfterMs / 1000);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
//# sourceMappingURL=edit-hint-end.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-hint-end.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Firestore } from 'firebase-admin/firestore'\nimport { isEditHintDeviceId } from './edit-hint-token'\n\n/**\n * Console sign-out ends the site edit bar in THAT browser (AGL-1842\n * follow-on).\n *\n * The `.aglyn.app` hint cookies live on a registrable domain the console\n * cannot write, so clearing them at sign-out is best-effort at most: a tab\n * closed mid-sign-out never gets there. The ending therefore happens on the\n * server. Sign-out writes one document per browser,\n * `users/{uid}/editHintEnds/{did}` with `endedAt`, where `did` is the\n * console's `aglyn_device` id for that browser. Every hint and every\n * edit-access token minted from that browser carries the same `did` and the\n * time its console session was last proven live; the exchange and\n * `/api/edit-context` refuse anything dated before `endedAt`.\n *\n * Per browser, by construction: another browser has another `did`, so the\n * same person signed in elsewhere keeps their bar. Signing back in here mints\n * a newer hint and the bar returns, with nothing to undo. One document per\n * browser the person has signed out of, overwritten each time, so it needs no\n * expiry; `eraseUser`'s `recursiveDelete(users/{uid})` takes it with the\n * account.\n *\n * Admin SDK only. The collection has no rules match, so clients can neither\n * read nor write it.\n *\n * Two other endings reach the bar without writing anything new (AGL-1842,\n * \"sign out everywhere\" and removing a device): a device signed out from the\n * device list ends that browser through its own `devices/{did}.revokedAt`\n * stamp, read beside this record, and an account-wide sign-out ends every\n * browser through the account's `tokensValidAfterTime`\n * ({@link accountEndRefuses}).\n */\nexport const EDIT_HINT_ENDS_COLLECTION = 'editHintEnds'\n\ntype FirestoreLike = Pick<Firestore, 'collection'>\n\nfunction endDoc(firestore: FirestoreLike, uid: string, did: string) {\n return firestore\n .collection('users')\n .doc(uid)\n .collection(EDIT_HINT_ENDS_COLLECTION)\n .doc(did)\n}\n\n/** Records that `uid` signed out of the console in browser `did`. */\nexport async function recordEditHintEnded(\n firestore: FirestoreLike,\n uid: string,\n did: string,\n nowMs: number = Date.now(),\n): Promise<boolean> {\n if (!uid || !isEditHintDeviceId(did)) return false\n await endDoc(firestore, uid, did).set({ endedAt: nowMs })\n return true\n}\n\n/**\n * `users/{uid}/devices/{did}`, the console's sign-in history row for the same\n * browser (`device-registry.ts` in the console names it `DEVICES_COLLECTION`).\n * Its `revokedAt` is stamped when that one device is signed out from the\n * Recent sign-ins list or by staff. Read here, never written: the ending it\n * records is reused as it stands, with no second write at revoke time.\n */\nexport const EDIT_HINT_DEVICES_COLLECTION = 'devices'\n\nfunction epochField(snapshot: { exists: boolean; get: (field: string) => unknown }, field: string): number {\n if (!snapshot.exists) return 0\n const value = Number(snapshot.get(field) ?? 0)\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * When browser `did` was last ended for `uid`; 0 if never. The later of two\n * records, read side by side:\n *\n * - its console sign-out (`editHintEnds/{did}.endedAt`, written by\n * `DELETE /api/auth/session`);\n * - that device being signed out from the device list\n * (`devices/{did}.revokedAt`). The hint's `did` IS the device row's id: both\n * are the browser's `aglyn_device` cookie. So removing a device ends that\n * device's bar, and no other device's, through this record alone.\n *\n * Signing out EVERYWHERE is account-wide and lives on the account instead\n * (`tokensValidAfterTime`); see {@link accountEndRefuses}.\n */\nexport async function readEditHintEndedAt(\n firestore: FirestoreLike,\n uid: string,\n did: string,\n): Promise<number> {\n if (!uid || !isEditHintDeviceId(did)) return 0\n const [ended, device] = await Promise.all([\n endDoc(firestore, uid, did).get(),\n firestore\n .collection('users')\n .doc(uid)\n .collection(EDIT_HINT_DEVICES_COLLECTION)\n .doc(did)\n .get(),\n ])\n return Math.max(epochField(ended, 'endedAt'), epochField(device, 'revokedAt'))\n}\n\n/**\n * Does a sign-out at `endedAtMs` end a credential whose session was proven\n * live at `provenAtMs`? An undateable credential cannot be shown to postdate\n * the sign-out, so it is refused, the same safe direction as device\n * revocation.\n */\nexport function editHintEndRefuses(\n endedAtMs: number,\n provenAtMs: number | null | undefined,\n): boolean {\n if (!endedAtMs) return false\n const proven = Number(provenAtMs ?? 0)\n if (!Number.isFinite(proven) || proven <= 0) return true\n return proven <= endedAtMs\n}\n\n/**\n * Does the account's own revocation epoch end a credential proven live at\n * `provenAtMs`?\n *\n * \"Sign out everywhere\", a password reset, a lock, a disable or a demotion\n * all end every session through `revokeRefreshTokens`, which moves the\n * account's `tokensValidAfterTime`. Every browser's hint and edit token\n * proven live before that moment is refused, on every browser at once, and\n * nothing extra is written: the epoch is the record. A hint minted after it\n * came from a session that passed the same revocation check, so signing back\n * in restores the bar with nothing to undo.\n *\n * Whole seconds on both sides, the same comparison `revocationRefuses` makes\n * for ID tokens: `tokensValidAfterTime` has second granularity, so comparing\n * milliseconds would refuse a hint minted in the same second on one process\n * and admit it on the next.\n *\n * @param validAfter - `tokensValidAfterTime` as the Admin SDK returns it (an\n * RFC-1123 string) or as epoch ms; absent when never revoked\n */\nexport function accountEndRefuses(\n validAfter: string | number | null | undefined,\n provenAtMs: number | null | undefined,\n): boolean {\n const validAfterMs =\n typeof validAfter === 'string' ? Date.parse(validAfter) : Number(validAfter ?? 0)\n if (!Number.isFinite(validAfterMs) || validAfterMs <= 0) return false\n const proven = Number(provenAtMs ?? 0)\n if (!Number.isFinite(proven) || proven <= 0) return true\n return Math.floor(proven / 1000) < Math.floor(validAfterMs / 1000)\n}\n"],"names":["isEditHintDeviceId","EDIT_HINT_ENDS_COLLECTION","endDoc","firestore","uid","did","collection","doc","recordEditHintEnded","nowMs","Date","now","set","endedAt","EDIT_HINT_DEVICES_COLLECTION","epochField","snapshot","field","exists","value","Number","get","isFinite","readEditHintEndedAt","ended","device","Promise","all","Math","max","editHintEndRefuses","endedAtMs","provenAtMs","proven","accountEndRefuses","validAfter","validAfterMs","parse","floor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,kBAAkB,QAAQ,uBAAmB;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GACD,OAAO,MAAMC,4BAA4B,eAAc;AAIvD,SAASC,OAAOC,SAAwB,EAAEC,GAAW,EAAEC,GAAW;IAChE,OAAOF,UACJG,UAAU,CAAC,SACXC,GAAG,CAACH,KACJE,UAAU,CAACL,2BACXM,GAAG,CAACF;AACT;AAEA,mEAAmE,GACnE,OAAO,eAAeG,oBACpBL,SAAwB,EACxBC,GAAW,EACXC,GAAW,EACXI,QAAgBC,KAAKC,GAAG,EAAE;IAE1B,IAAI,CAACP,OAAO,CAACJ,mBAAmBK,MAAM,OAAO;IAC7C,MAAMH,OAAOC,WAAWC,KAAKC,KAAKO,GAAG,CAAC;QAAEC,SAASJ;IAAM;IACvD,OAAO;AACT;AAEA;;;;;;CAMC,GACD,OAAO,MAAMK,+BAA+B,UAAS;AAErD,SAASC,WAAWC,QAA8D,EAAEC,KAAa;QAE1ED;IADrB,IAAI,CAACA,SAASE,MAAM,EAAE,OAAO;IAC7B,MAAMC,QAAQC,QAAOJ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efix domain-separates both from the `edit-bar:`/`media:`/commerce
|
|
42
42
|
* signatures sharing `TOKEN_SIGNING_SECRET`.
|
|
43
43
|
*
|
|
44
|
+
* Each hint also names the BROWSER it was planted in and when the console
|
|
45
|
+
* proved the session (AGL-1842 follow-on, sign-out ends the bar): `did` is
|
|
46
|
+
* the console's own `aglyn_device` id for that browser, and `iat` is when the
|
|
47
|
+
* bounce was minted from a live console session. Console sign-out records
|
|
48
|
+
* `users/{uid}/editHintEnds/{did}` (see `edit-hint-end.ts`), and the exchange
|
|
49
|
+
* refuses any hint for that browser minted before it — so a sign-out ends the
|
|
50
|
+
* bar in that browser alone, even when the tab closed before any cookie could
|
|
51
|
+
* be cleared, while the same person's other browsers keep theirs.
|
|
52
|
+
*
|
|
44
53
|
* A hint is NOT edit access: it names a uid and nothing else. Everything
|
|
45
54
|
* real happens server-side at the tenant's `/api/edit-access/exchange`,
|
|
46
55
|
* which re-authorizes that uid against the specific host being viewed with
|
|
@@ -63,7 +72,30 @@ export interface EditHintClaims {
|
|
|
63
72
|
uid: string;
|
|
64
73
|
/** Expiry, epoch ms. */
|
|
65
74
|
exp: number;
|
|
75
|
+
/**
|
|
76
|
+
* The console browser the hint was planted from — its `aglyn_device` id.
|
|
77
|
+
* Absent only on hints minted before sign-out could end them, which the
|
|
78
|
+
* exchange refuses.
|
|
79
|
+
*/
|
|
80
|
+
did?: string;
|
|
81
|
+
/**
|
|
82
|
+
* When the console last proved this session live, epoch ms: the BOUNCE
|
|
83
|
+
* mint, carried unchanged into the cookie so a bounce that lands after a
|
|
84
|
+
* sign-out is still dated before it.
|
|
85
|
+
*/
|
|
86
|
+
iat?: number;
|
|
87
|
+
}
|
|
88
|
+
/** What a mint may bind the hint to; see {@link EditHintClaims}. */
|
|
89
|
+
export interface EditHintBinding {
|
|
90
|
+
did: string;
|
|
91
|
+
iat: number;
|
|
66
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* The shape a `did` must have to be used as a Firestore document id: the
|
|
95
|
+
* console mints `aglyn_device` as a UUID, and anything else is refused rather
|
|
96
|
+
* than written into a path.
|
|
97
|
+
*/
|
|
98
|
+
export declare function isEditHintDeviceId(value: unknown): value is string;
|
|
67
99
|
export interface MintedEditHintToken {
|
|
68
100
|
token: string;
|
|
69
101
|
expiresAtMs: number;
|
|
@@ -73,7 +105,7 @@ export interface MintedEditHintToken {
|
|
|
73
105
|
* (the console route verifies a Firebase ID token; the bounce endpoint
|
|
74
106
|
* verifies a `bounce` hint). The mint itself checks nothing.
|
|
75
107
|
*/
|
|
76
|
-
export declare function mintEditHintToken(kind: EditHintKind, uid: string, nowMs?: number): MintedEditHintToken;
|
|
108
|
+
export declare function mintEditHintToken(kind: EditHintKind, uid: string, nowMs?: number, binding?: EditHintBinding): MintedEditHintToken;
|
|
77
109
|
/**
|
|
78
110
|
* Verifies a presented hint AS the stated kind and returns its claims, or
|
|
79
111
|
* `null` for anything else — expired, tampered, malformed, wrong version,
|
|
@@ -42,6 +42,15 @@ import { tokenSigningSecret } from "./media-signing.js";
|
|
|
42
42
|
* prefix domain-separates both from the `edit-bar:`/`media:`/commerce
|
|
43
43
|
* signatures sharing `TOKEN_SIGNING_SECRET`.
|
|
44
44
|
*
|
|
45
|
+
* Each hint also names the BROWSER it was planted in and when the console
|
|
46
|
+
* proved the session (AGL-1842 follow-on, sign-out ends the bar): `did` is
|
|
47
|
+
* the console's own `aglyn_device` id for that browser, and `iat` is when the
|
|
48
|
+
* bounce was minted from a live console session. Console sign-out records
|
|
49
|
+
* `users/{uid}/editHintEnds/{did}` (see `edit-hint-end.ts`), and the exchange
|
|
50
|
+
* refuses any hint for that browser minted before it — so a sign-out ends the
|
|
51
|
+
* bar in that browser alone, even when the tab closed before any cookie could
|
|
52
|
+
* be cleared, while the same person's other browsers keep theirs.
|
|
53
|
+
*
|
|
45
54
|
* A hint is NOT edit access: it names a uid and nothing else. Everything
|
|
46
55
|
* real happens server-side at the tenant's `/api/edit-access/exchange`,
|
|
47
56
|
* which re-authorizes that uid against the specific host being viewed with
|
|
@@ -56,6 +65,13 @@ import { tokenSigningSecret } from "./media-signing.js";
|
|
|
56
65
|
* tenant's own exchange route, where it is verified server-side.
|
|
57
66
|
*/ export const EDIT_HINT_COOKIE = 'aglyn_edit_hint';
|
|
58
67
|
/** Version tag, mirroring the edit-access token's debuggability rationale. */ const TOKEN_PREFIX = 'aglyn-edit-hint-v1';
|
|
68
|
+
/**
|
|
69
|
+
* The shape a `did` must have to be used as a Firestore document id: the
|
|
70
|
+
* console mints `aglyn_device` as a UUID, and anything else is refused rather
|
|
71
|
+
* than written into a path.
|
|
72
|
+
*/ export function isEditHintDeviceId(value) {
|
|
73
|
+
return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value);
|
|
74
|
+
}
|
|
59
75
|
function signPayload(kind, payloadB64) {
|
|
60
76
|
return createHmac('sha256', tokenSigningSecret()).update(`edit-hint:${kind}:${payloadB64}`).digest('base64url');
|
|
61
77
|
}
|
|
@@ -63,10 +79,15 @@ function signPayload(kind, payloadB64) {
|
|
|
63
79
|
* Mints a hint of the given kind for a uid the caller has ALREADY verified
|
|
64
80
|
* (the console route verifies a Firebase ID token; the bounce endpoint
|
|
65
81
|
* verifies a `bounce` hint). The mint itself checks nothing.
|
|
66
|
-
*/ export function mintEditHintToken(kind, uid, nowMs = Date.now()) {
|
|
82
|
+
*/ export function mintEditHintToken(kind, uid, nowMs = Date.now(), binding) {
|
|
67
83
|
if (!uid) throw new Error('uid is required');
|
|
68
84
|
const exp = nowMs + (kind === 'bounce' ? EDIT_HINT_BOUNCE_TTL_MS : EDIT_HINT_COOKIE_TTL_MS);
|
|
69
|
-
const claims = {
|
|
85
|
+
const claims = binding ? {
|
|
86
|
+
uid,
|
|
87
|
+
exp,
|
|
88
|
+
did: binding.did,
|
|
89
|
+
iat: binding.iat
|
|
90
|
+
} : {
|
|
70
91
|
uid,
|
|
71
92
|
exp
|
|
72
93
|
};
|
|
@@ -110,6 +131,15 @@ function signPayload(kind, payloadB64) {
|
|
|
110
131
|
const exp = Number(claims == null ? void 0 : claims.exp);
|
|
111
132
|
if (!Number.isFinite(exp) || exp <= nowMs) return null;
|
|
112
133
|
if (typeof claims.uid !== 'string' || !claims.uid) return null;
|
|
134
|
+
const iat = Number(claims.iat);
|
|
135
|
+
if (isEditHintDeviceId(claims.did) && Number.isFinite(iat) && iat > 0) {
|
|
136
|
+
return {
|
|
137
|
+
uid: claims.uid,
|
|
138
|
+
exp,
|
|
139
|
+
did: claims.did,
|
|
140
|
+
iat
|
|
141
|
+
};
|
|
142
|
+
}
|
|
113
143
|
return {
|
|
114
144
|
uid: claims.uid,
|
|
115
145
|
exp
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-hint-token.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport { tokenSigningSecret } from './media-signing'\n\n/**\n * Editor-presence HINT tokens for the tenant admin bar on `*.aglyn.app`\n * (AGL-1842, the cross-site half AGL-1829 could not reach).\n *\n * The console session lives on `app.aglyn.com`; `*.aglyn.app` is a different\n * registrable domain, so neither the AGL-1829 hint cookie nor the silent\n * iframe probe can cross over — storage partitioning keeps the two worlds\n * apart, correctly. What CAN cross is a top-level navigation: at console\n * sign-in the browser is bounced once through\n * `https://console.aglyn.app/api/edit-hint/set?sig=<bounce token>` and back,\n * and in that first-party moment the tenant app plants a signed hint cookie\n * on `Domain=.aglyn.app` that every tenant subdomain can present to its own\n * server afterwards.\n *\n * Two kinds, deliberately non-interchangeable:\n *\n * - `bounce` — rides the redirect URL once. URLs are logged and shareable,\n * so its TTL is seconds ({@link EDIT_HINT_BOUNCE_TTL_MS}).\n * - `cookie` — the planted `aglyn_edit_hint` value, HttpOnly, living the\n * {@link EDIT_HINT_COOKIE_TTL_MS} window between console visits.\n *\n * The kind is INSIDE the signed context string, so a leaked 60-second bounce\n * URL can never be replayed as a week-long cookie, and a stolen cookie value\n * can never be planted elsewhere through the bounce endpoint. The `edit-hint:`\n * prefix domain-separates both from the `edit-bar:`/`media:`/commerce\n * signatures sharing `TOKEN_SIGNING_SECRET`.\n *\n * A hint is NOT edit access: it names a uid and nothing else. Everything\n * real happens server-side at the tenant's `/api/edit-access/exchange`,\n * which re-authorizes that uid against the specific host being viewed with\n * the same membership gate the console's token mint applies. A forged,\n * expired, or stale hint costs one refused POST.\n */\n\n/** Seconds, not minutes: the bounce URL is single-use inside one redirect. */\nexport const EDIT_HINT_BOUNCE_TTL_MS = 60 * 1000\n\n/** 7 days — matches the AGL-1829 marker cookie's refresh cadence. */\nexport const EDIT_HINT_COOKIE_TTL_MS = 7 * 24 * 60 * 60 * 1000\n\n/**\n * The HttpOnly signed hint cookie on `Domain=.aglyn.app`. Sibling of the\n * JS-visible `aglyn_editor=1` marker (`EDITOR_HINT_COOKIE`), which the\n * admin-bar stub reads to arm; this one only ever travels back to the\n * tenant's own exchange route, where it is verified server-side.\n */\nexport const EDIT_HINT_COOKIE = 'aglyn_edit_hint'\n\n/** Version tag, mirroring the edit-access token's debuggability rationale. */\nconst TOKEN_PREFIX = 'aglyn-edit-hint-v1'\n\nexport type EditHintKind = 'bounce' | 'cookie'\n\nexport interface EditHintClaims {\n uid: string\n /** Expiry, epoch ms. */\n exp: number\n}\n\nfunction signPayload(kind: EditHintKind, payloadB64: string): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`edit-hint:${kind}:${payloadB64}`)\n .digest('base64url')\n}\n\nexport interface MintedEditHintToken {\n token: string\n expiresAtMs: number\n}\n\n/**\n * Mints a hint of the given kind for a uid the caller has ALREADY verified\n * (the console route verifies a Firebase ID token; the bounce endpoint\n * verifies a `bounce` hint). The mint itself checks nothing.\n */\nexport function mintEditHintToken(\n kind: EditHintKind,\n uid: string,\n nowMs: number = Date.now(),\n): MintedEditHintToken {\n if (!uid) throw new Error('uid is required')\n const exp =\n nowMs +\n (kind === 'bounce' ? EDIT_HINT_BOUNCE_TTL_MS : EDIT_HINT_COOKIE_TTL_MS)\n const claims: EditHintClaims = { uid, exp }\n const payload = Buffer.from(JSON.stringify(claims), 'utf8').toString(\n 'base64url',\n )\n return {\n token: `${TOKEN_PREFIX}.${payload}.${signPayload(kind, payload)}`,\n expiresAtMs: exp,\n }\n}\n\n/**\n * Verifies a presented hint AS the stated kind and returns its claims, or\n * `null` for anything else — expired, tampered, malformed, wrong version,\n * wrong KIND (the replay wall), or a deploy with no signing secret (fail\n * closed, like every signature in this family).\n */\nexport function verifyEditHintToken(\n kind: EditHintKind,\n token: unknown,\n nowMs: number = Date.now(),\n): EditHintClaims | null {\n if (typeof token !== 'string' || token.length === 0 || token.length > 4096) {\n return null\n }\n const parts = token.split('.')\n if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null\n const [, payload, sig] = parts\n let expected: string\n try {\n expected = signPayload(kind, payload)\n } catch {\n // Secret missing — refuse rather than trusting anything.\n return null\n }\n // Length-checked before timingSafeEqual, which THROWS on attacker-length\n // input — a 500 where a refusal belongs (same note as edit-access-token).\n if (sig.length !== expected.length) return null\n if (\n !timingSafeEqual(\n new Uint8Array(Buffer.from(sig)),\n new Uint8Array(Buffer.from(expected)),\n )\n ) {\n return null\n }\n let claims: EditHintClaims\n try {\n claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n } catch {\n return null\n }\n const exp = Number(claims?.exp)\n if (!Number.isFinite(exp) || exp <= nowMs) return null\n if (typeof claims.uid !== 'string' || !claims.uid) return null\n return { uid: claims.uid, exp }\n}\n"],"names":["createHmac","timingSafeEqual","tokenSigningSecret","EDIT_HINT_BOUNCE_TTL_MS","EDIT_HINT_COOKIE_TTL_MS","EDIT_HINT_COOKIE","TOKEN_PREFIX","signPayload","kind","payloadB64","update","digest","mintEditHintToken","uid","nowMs","Date","now","Error","exp","claims","payload","Buffer","from","JSON","stringify","toString","token","expiresAtMs","verifyEditHintToken","length","parts","split","sig","expected","Uint8Array","parse","Number","isFinite"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GAED,4EAA4E,GAC5E,OAAO,MAAMC,0BAA0B,KAAK,KAAI;AAEhD,mEAAmE,GACnE,OAAO,MAAMC,0BAA0B,IAAI,KAAK,KAAK,KAAK,KAAI;AAE9D;;;;;CAKC,GACD,OAAO,MAAMC,mBAAmB,kBAAiB;AAEjD,4EAA4E,GAC5E,MAAMC,eAAe;AAUrB,SAASC,YAAYC,IAAkB,EAAEC,UAAkB;IACzD,OAAOT,WAAW,UAAUE,sBACzBQ,MAAM,CAAC,CAAC,UAAU,EAAEF,KAAK,CAAC,EAAEC,YAAY,EACxCE,MAAM,CAAC;AACZ;AAOA;;;;CAIC,GACD,OAAO,SAASC,kBACdJ,IAAkB,EAClBK,GAAW,EACXC,QAAgBC,KAAKC,GAAG,EAAE;IAE1B,IAAI,CAACH,KAAK,MAAM,IAAII,MAAM;IAC1B,MAAMC,MACJJ,QACCN,CAAAA,SAAS,WAAWL,0BAA0BC,uBAAsB;IACvE,MAAMe,SAAyB;QAAEN;QAAKK;IAAI;IAC1C,MAAME,UAAUC,OAAOC,IAAI,CAACC,KAAKC,SAAS,CAACL,SAAS,QAAQM,QAAQ,CAClE;IAEF,OAAO;QACLC,OAAO,GAAGpB,aAAa,CAAC,EAAEc,QAAQ,CAAC,EAAEb,YAAYC,MAAMY,UAAU;QACjEO,aAAaT;IACf;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASU,oBACdpB,IAAkB,EAClBkB,KAAc,EACdZ,QAAgBC,KAAKC,GAAG,EAAE;IAE1B,IAAI,OAAOU,UAAU,YAAYA,MAAMG,MAAM,KAAK,KAAKH,MAAMG,MAAM,GAAG,MAAM;QAC1E,OAAO;IACT;IACA,MAAMC,QAAQJ,MAAMK,KAAK,CAAC;IAC1B,IAAID,MAAMD,MAAM,KAAK,KAAKC,KAAK,CAAC,EAAE,KAAKxB,cAAc,OAAO;IAC5D,MAAM,GAAGc,SAASY,IAAI,GAAGF;IACzB,IAAIG;IACJ,IAAI;QACFA,WAAW1B,YAAYC,MAAMY;IAC/B,EAAE,eAAM;QACN,yDAAyD;QACzD,OAAO;IACT;IACA,yEAAyE;IACzE,0EAA0E;IAC1E,IAAIY,IAAIH,MAAM,KAAKI,SAASJ,MAAM,EAAE,OAAO;IAC3C,IACE,CAAC5B,gBACC,IAAIiC,WAAWb,OAAOC,IAAI,CAACU,OAC3B,IAAIE,WAAWb,OAAOC,IAAI,CAACW,aAE7B;QACA,OAAO;IACT;IACA,IAAId;IACJ,IAAI;QACFA,SAASI,KAAKY,KAAK,CAACd,OAAOC,IAAI,CAACF,SAAS,aAAaK,QAAQ,CAAC;IACjE,EAAE,eAAM;QACN,OAAO;IACT;IACA,MAAMP,MAAMkB,OAAOjB,0BAAAA,OAAQD,GAAG;IAC9B,IAAI,CAACkB,OAAOC,QAAQ,CAACnB,QAAQA,OAAOJ,OAAO,OAAO;IAClD,IAAI,OAAOK,OAAON,GAAG,KAAK,YAAY,CAACM,OAAON,GAAG,EAAE,OAAO;IAC1D,OAAO;QAAEA,KAAKM,OAAON,GAAG;QAAEK;IAAI;AAChC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/edit-hint-token.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport { tokenSigningSecret } from './media-signing'\n\n/**\n * Editor-presence HINT tokens for the tenant admin bar on `*.aglyn.app`\n * (AGL-1842, the cross-site half AGL-1829 could not reach).\n *\n * The console session lives on `app.aglyn.com`; `*.aglyn.app` is a different\n * registrable domain, so neither the AGL-1829 hint cookie nor the silent\n * iframe probe can cross over — storage partitioning keeps the two worlds\n * apart, correctly. What CAN cross is a top-level navigation: at console\n * sign-in the browser is bounced once through\n * `https://console.aglyn.app/api/edit-hint/set?sig=<bounce token>` and back,\n * and in that first-party moment the tenant app plants a signed hint cookie\n * on `Domain=.aglyn.app` that every tenant subdomain can present to its own\n * server afterwards.\n *\n * Two kinds, deliberately non-interchangeable:\n *\n * - `bounce` — rides the redirect URL once. URLs are logged and shareable,\n * so its TTL is seconds ({@link EDIT_HINT_BOUNCE_TTL_MS}).\n * - `cookie` — the planted `aglyn_edit_hint` value, HttpOnly, living the\n * {@link EDIT_HINT_COOKIE_TTL_MS} window between console visits.\n *\n * The kind is INSIDE the signed context string, so a leaked 60-second bounce\n * URL can never be replayed as a week-long cookie, and a stolen cookie value\n * can never be planted elsewhere through the bounce endpoint. The `edit-hint:`\n * prefix domain-separates both from the `edit-bar:`/`media:`/commerce\n * signatures sharing `TOKEN_SIGNING_SECRET`.\n *\n * Each hint also names the BROWSER it was planted in and when the console\n * proved the session (AGL-1842 follow-on, sign-out ends the bar): `did` is\n * the console's own `aglyn_device` id for that browser, and `iat` is when the\n * bounce was minted from a live console session. Console sign-out records\n * `users/{uid}/editHintEnds/{did}` (see `edit-hint-end.ts`), and the exchange\n * refuses any hint for that browser minted before it — so a sign-out ends the\n * bar in that browser alone, even when the tab closed before any cookie could\n * be cleared, while the same person's other browsers keep theirs.\n *\n * A hint is NOT edit access: it names a uid and nothing else. Everything\n * real happens server-side at the tenant's `/api/edit-access/exchange`,\n * which re-authorizes that uid against the specific host being viewed with\n * the same membership gate the console's token mint applies. A forged,\n * expired, or stale hint costs one refused POST.\n */\n\n/** Seconds, not minutes: the bounce URL is single-use inside one redirect. */\nexport const EDIT_HINT_BOUNCE_TTL_MS = 60 * 1000\n\n/** 7 days — matches the AGL-1829 marker cookie's refresh cadence. */\nexport const EDIT_HINT_COOKIE_TTL_MS = 7 * 24 * 60 * 60 * 1000\n\n/**\n * The HttpOnly signed hint cookie on `Domain=.aglyn.app`. Sibling of the\n * JS-visible `aglyn_editor=1` marker (`EDITOR_HINT_COOKIE`), which the\n * admin-bar stub reads to arm; this one only ever travels back to the\n * tenant's own exchange route, where it is verified server-side.\n */\nexport const EDIT_HINT_COOKIE = 'aglyn_edit_hint'\n\n/** Version tag, mirroring the edit-access token's debuggability rationale. */\nconst TOKEN_PREFIX = 'aglyn-edit-hint-v1'\n\nexport type EditHintKind = 'bounce' | 'cookie'\n\nexport interface EditHintClaims {\n uid: string\n /** Expiry, epoch ms. */\n exp: number\n /**\n * The console browser the hint was planted from — its `aglyn_device` id.\n * Absent only on hints minted before sign-out could end them, which the\n * exchange refuses.\n */\n did?: string\n /**\n * When the console last proved this session live, epoch ms: the BOUNCE\n * mint, carried unchanged into the cookie so a bounce that lands after a\n * sign-out is still dated before it.\n */\n iat?: number\n}\n\n/** What a mint may bind the hint to; see {@link EditHintClaims}. */\nexport interface EditHintBinding {\n did: string\n iat: number\n}\n\n/**\n * The shape a `did` must have to be used as a Firestore document id: the\n * console mints `aglyn_device` as a UUID, and anything else is refused rather\n * than written into a path.\n */\nexport function isEditHintDeviceId(value: unknown): value is string {\n return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value)\n}\n\nfunction signPayload(kind: EditHintKind, payloadB64: string): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`edit-hint:${kind}:${payloadB64}`)\n .digest('base64url')\n}\n\nexport interface MintedEditHintToken {\n token: string\n expiresAtMs: number\n}\n\n/**\n * Mints a hint of the given kind for a uid the caller has ALREADY verified\n * (the console route verifies a Firebase ID token; the bounce endpoint\n * verifies a `bounce` hint). The mint itself checks nothing.\n */\nexport function mintEditHintToken(\n kind: EditHintKind,\n uid: string,\n nowMs: number = Date.now(),\n binding?: EditHintBinding,\n): MintedEditHintToken {\n if (!uid) throw new Error('uid is required')\n const exp =\n nowMs +\n (kind === 'bounce' ? EDIT_HINT_BOUNCE_TTL_MS : EDIT_HINT_COOKIE_TTL_MS)\n const claims: EditHintClaims = binding\n ? { uid, exp, did: binding.did, iat: binding.iat }\n : { uid, exp }\n const payload = Buffer.from(JSON.stringify(claims), 'utf8').toString(\n 'base64url',\n )\n return {\n token: `${TOKEN_PREFIX}.${payload}.${signPayload(kind, payload)}`,\n expiresAtMs: exp,\n }\n}\n\n/**\n * Verifies a presented hint AS the stated kind and returns its claims, or\n * `null` for anything else — expired, tampered, malformed, wrong version,\n * wrong KIND (the replay wall), or a deploy with no signing secret (fail\n * closed, like every signature in this family).\n */\nexport function verifyEditHintToken(\n kind: EditHintKind,\n token: unknown,\n nowMs: number = Date.now(),\n): EditHintClaims | null {\n if (typeof token !== 'string' || token.length === 0 || token.length > 4096) {\n return null\n }\n const parts = token.split('.')\n if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null\n const [, payload, sig] = parts\n let expected: string\n try {\n expected = signPayload(kind, payload)\n } catch {\n // Secret missing — refuse rather than trusting anything.\n return null\n }\n // Length-checked before timingSafeEqual, which THROWS on attacker-length\n // input — a 500 where a refusal belongs (same note as edit-access-token).\n if (sig.length !== expected.length) return null\n if (\n !timingSafeEqual(\n new Uint8Array(Buffer.from(sig)),\n new Uint8Array(Buffer.from(expected)),\n )\n ) {\n return null\n }\n let claims: EditHintClaims\n try {\n claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n } catch {\n return null\n }\n const exp = Number(claims?.exp)\n if (!Number.isFinite(exp) || exp <= nowMs) return null\n if (typeof claims.uid !== 'string' || !claims.uid) return null\n const iat = Number(claims.iat)\n if (isEditHintDeviceId(claims.did) && Number.isFinite(iat) && iat > 0) {\n return { uid: claims.uid, exp, did: claims.did, iat }\n }\n return { uid: claims.uid, exp }\n}\n"],"names":["createHmac","timingSafeEqual","tokenSigningSecret","EDIT_HINT_BOUNCE_TTL_MS","EDIT_HINT_COOKIE_TTL_MS","EDIT_HINT_COOKIE","TOKEN_PREFIX","isEditHintDeviceId","value","test","signPayload","kind","payloadB64","update","digest","mintEditHintToken","uid","nowMs","Date","now","binding","Error","exp","claims","did","iat","payload","Buffer","from","JSON","stringify","toString","token","expiresAtMs","verifyEditHintToken","length","parts","split","sig","expected","Uint8Array","parse","Number","isFinite"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,4EAA4E,GAC5E,OAAO,MAAMC,0BAA0B,KAAK,KAAI;AAEhD,mEAAmE,GACnE,OAAO,MAAMC,0BAA0B,IAAI,KAAK,KAAK,KAAK,KAAI;AAE9D;;;;;CAKC,GACD,OAAO,MAAMC,mBAAmB,kBAAiB;AAEjD,4EAA4E,GAC5E,MAAMC,eAAe;AA4BrB;;;;CAIC,GACD,OAAO,SAASC,mBAAmBC,KAAc;IAC/C,OAAO,OAAOA,UAAU,YAAY,wBAAwBC,IAAI,CAACD;AACnE;AAEA,SAASE,YAAYC,IAAkB,EAAEC,UAAkB;IACzD,OAAOZ,WAAW,UAAUE,sBACzBW,MAAM,CAAC,CAAC,UAAU,EAAEF,KAAK,CAAC,EAAEC,YAAY,EACxCE,MA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7B;QACA,OAAO;IACT;IACA,IAAIhB;IACJ,IAAI;QACFA,SAASM,KAAKY,KAAK,CAACd,OAAOC,IAAI,CAACF,SAAS,aAAaK,QAAQ,CAAC;IACjE,EAAE,eAAM;QACN,OAAO;IACT;IACA,MAAMT,MAAMoB,OAAOnB,0BAAAA,OAAQD,GAAG;IAC9B,IAAI,CAACoB,OAAOC,QAAQ,CAACrB,QAAQA,OAAOL,OAAO,OAAO;IAClD,IAAI,OAAOM,OAAOP,GAAG,KAAK,YAAY,CAACO,OAAOP,GAAG,EAAE,OAAO;IAC1D,MAAMS,MAAMiB,OAAOnB,OAAOE,GAAG;IAC7B,IAAIlB,mBAAmBgB,OAAOC,GAAG,KAAKkB,OAAOC,QAAQ,CAAClB,QAAQA,MAAM,GAAG;QACrE,OAAO;YAAET,KAAKO,OAAOP,GAAG;YAAEM;YAAKE,KAAKD,OAAOC,GAAG;YAAEC;QAAI;IACtD;IACA,OAAO;QAAET,KAAKO,OAAOP,GAAG;QAAEM;IAAI;AAChC"}
|
|
@@ -104,6 +104,14 @@ export declare class UserDisabledError extends Error {
|
|
|
104
104
|
readonly code = "auth/user-disabled";
|
|
105
105
|
constructor(message?: string);
|
|
106
106
|
}
|
|
107
|
+
/** What the check needs off the account record, and nothing else. */
|
|
108
|
+
export interface AccountRevocationState {
|
|
109
|
+
/** `true` when the record could not be found at all. */
|
|
110
|
+
missing: boolean;
|
|
111
|
+
disabled: boolean;
|
|
112
|
+
/** `tokensValidAfterTime` as epoch ms; null when never revoked. */
|
|
113
|
+
validAfterMs: number | null;
|
|
114
|
+
}
|
|
107
115
|
/**
|
|
108
116
|
* Drop one account's cached verdict — called by every path that revokes, so
|
|
109
117
|
* the process that took the action refuses on its very next request instead
|
|
@@ -126,6 +134,16 @@ export declare function resetTokenRevocationCache(): void;
|
|
|
126
134
|
* revoked
|
|
127
135
|
*/
|
|
128
136
|
export declare function revocationRefuses(decoded: DecodedIdToken, validAfterMs: number | null | undefined): boolean;
|
|
137
|
+
/**
|
|
138
|
+
* The cached account state behind a uid, for a credential that is not an ID
|
|
139
|
+
* token: the site edit bar's own token (AGL-1842), which names the uid and
|
|
140
|
+
* the pool it was minted for but carries no `auth_time`. Same cache, same
|
|
141
|
+
* 15-second bound and same pool rule as {@link assertIdTokenNotRevoked}.
|
|
142
|
+
* `null` means the service could not be asked; the caller fails open.
|
|
143
|
+
*
|
|
144
|
+
* @param pool - the auth handle of the pool the uid lives in (AGL-2005)
|
|
145
|
+
*/
|
|
146
|
+
export declare function readAccountRevocationState(pool: Pick<BaseAuth, 'getUser'>, uid: string, tenantId: string | null): Promise<Readonly<AccountRevocationState> | null>;
|
|
129
147
|
/**
|
|
130
148
|
* Throw if this verified ID token belongs to an account that has since been
|
|
131
149
|
* revoked, disabled or deleted. Resolves silently otherwise, including when
|
|
@@ -222,6 +222,18 @@ const pending = new Map();
|
|
|
222
222
|
}
|
|
223
223
|
return inFlight;
|
|
224
224
|
}
|
|
225
|
+
/**
|
|
226
|
+
* The cached account state behind a uid, for a credential that is not an ID
|
|
227
|
+
* token: the site edit bar's own token (AGL-1842), which names the uid and
|
|
228
|
+
* the pool it was minted for but carries no `auth_time`. Same cache, same
|
|
229
|
+
* 15-second bound and same pool rule as {@link assertIdTokenNotRevoked}.
|
|
230
|
+
* `null` means the service could not be asked; the caller fails open.
|
|
231
|
+
*
|
|
232
|
+
* @param pool - the auth handle of the pool the uid lives in (AGL-2005)
|
|
233
|
+
*/ export async function readAccountRevocationState(pool, uid, tenantId) {
|
|
234
|
+
if (!uid) return null;
|
|
235
|
+
return readAccountState(pool, uid, cacheKey(uid, tenantId));
|
|
236
|
+
}
|
|
225
237
|
/**
|
|
226
238
|
* Throw if this verified ID token belongs to an account that has since been
|
|
227
239
|
* revoked, disabled or deleted. Resolves silently otherwise, including when
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/token-revocation.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * ID-token revocation on every server door (AGL-1881).\n *\n * ## The gap this closes\n *\n * `verifyIdToken(token)` checks a signature and an expiry. It does not ask\n * whether the account was locked, disabled, deleted, de-staffed or signed out\n * five seconds ago — that costs a round trip, so the SDK makes it opt-in via\n * `checkRevoked`. The pre-launch audit found the flag set on 3 of 175 call\n * sites: the session MINT, the session EXCHANGE and the device-revoke route.\n * Everything else — 117 console API routes, plus the marketplace, commerce and\n * bookings plugin servers — took a bare `verifyIdToken`.\n *\n * So `revokeRefreshTokens(uid)` stopped the browser getting a NEW token and\n * did nothing about the one it already held. After a panic user-lock, a staff\n * password reset, an SSO offboard, an org-wide lockdown or a \"sign out\n * everywhere\", the revoked token kept opening every one of those doors for the\n * remainder of its hour. `device-revocation.ts` meanwhile promised the effect\n * was \"immediate for everything that goes through our server\", which was the\n * defect worth fixing: the sentence was shipped and it was not true.\n *\n * ## Why it is a cached epoch and not just `checkRevoked: true`\n *\n * `checkRevoked` costs one `accounts:lookup` per verification. Measured\n * against production `aglyn-main` (n=40): p50 95.5ms, p95 144ms — statistically\n * indistinguishable from the p50 85.8ms single Firestore `doc().get()` that\n * every one of these routes already performs, on the same connection from the\n * same machine. So the round trip is not expensive; it is just paid too often.\n * Turned on unconditionally it would multiply Identity Toolkit calls by the\n * whole console request volume, against a project quota, to re-answer a\n * question whose answer changes maybe twice a year per account.\n *\n * The answer is therefore CACHED, on exactly the terms AGL-1522 already set\n * for the panic path: `PLATFORM_TTL_MS`, 15 seconds, LRU-bounded, with the\n * acting process invalidating the uid after its own write. Steady state costs\n * nothing; a cold entry costs one Firestore-read-equivalent; the honest window\n * goes from ~3600s to ≤15s, and to zero on the process that did the revoking.\n * A revocation control whose staleness bound matches the lockdown control it\n * sits beside is one bound to explain, not two.\n *\n * ## What is checked, and in which pool\n *\n * Three refusals, mirroring firebase-admin's own `checkRevoked` so the error\n * codes route handlers already catch keep working unchanged:\n *\n * - `tokensValidAfterTime` after the token's `auth_time` → `id-token-revoked`\n * - `disabled` → `user-disabled` (a user-scope panic lock sets this, and it\n * is the half that does not depend on clock agreement)\n * - the record is GONE → `id-token-revoked` (a deleted account is not a\n * signed-in one; the SDK's own check treats this as revoked too)\n *\n * The lookup is asked of the auth instance the token was verified with, which\n * is the AGL-2005 rule made structural rather than remembered: a tenant-aware\n * auth asks the tenant pool, and a project-pool lookup for an SSO uid — which\n * would answer \"never revoked\" about a forged twin — cannot be spelled.\n *\n * ## Failure direction\n *\n * An unreachable Identity Toolkit is an outage, not a revocation, and refusing\n * every request in the console during one would be a self-inflicted lockdown.\n * So a transport failure fails OPEN — and is NOT cached, or a single blip\n * would blind the check for a full TTL. `user-not-found` is not a transport\n * failure and fails closed. This is the opposite direction from\n * `deviceRevocationRefuses`, which refuses an undateable credential, and the\n * split is deliberate: \"we could not reach the service\" and \"the service told\n * us this account is gone\" are different answers.\n */\n\nimport type { BaseAuth, DecodedIdToken } from 'firebase-admin/auth'\n\n/**\n * Matches `PLATFORM_TTL_MS` in `lockdown.ts`, and deliberately so — see the\n * module note. One number for how stale a panic action may read.\n */\nexport const TOKEN_REVOCATION_TTL_MS = 15_000\n\n/**\n * Bounded so a scan of uids cannot balloon a warm serverless process. Past\n * this many entries the least-recently-USED is evicted; a cache hit refreshes\n * recency, so an active session is not what a scan pushes out. Same bound and\n * same reasoning as `USER_LOCKDOWN_CACHE_MAX`.\n */\nexport const TOKEN_REVOCATION_CACHE_MAX = 5000\n\n/** Thrown for a token the account has invalidated. Code matches the SDK's. */\nexport class IdTokenRevokedError extends Error {\n readonly code = 'auth/id-token-revoked'\n constructor(message = 'The ID token has been revoked.') {\n super(message)\n this.name = 'IdTokenRevokedError'\n }\n}\n\n/** Thrown for a token whose account is disabled. Code matches the SDK's. */\nexport class UserDisabledError extends Error {\n readonly code = 'auth/user-disabled'\n constructor(message = 'The user record is disabled.') {\n super(message)\n this.name = 'UserDisabledError'\n }\n}\n\n/** What the check needs off the account record, and nothing else. */\ninterface AccountState {\n /** `true` when the record could not be found at all. */\n missing: boolean\n disabled: boolean\n /** `tokensValidAfterTime` as epoch ms; null when never revoked. */\n validAfterMs: number | null\n}\n\nconst cache = new Map<string, { at: number; state: AccountState }>()\nconst pending = new Map<string, Promise<AccountState | null>>()\n\n/**\n * A uid is only unique WITHIN a pool (AGL-2005), so the pool is part of the\n * key. The separator is a NUL because a tenant id cannot contain one.\n */\nfunction cacheKey(uid: string, tenantId: string | null | undefined): string {\n return `${tenantId ?? ''}\\u0000${uid}`\n}\n\n/**\n * Drop one account's cached verdict — called by every path that revokes, so\n * the process that took the action refuses on its very next request instead\n * of waiting out its own TTL. Called bare, clears everything.\n */\nexport function invalidateTokenRevocationCache(\n uid?: string,\n tenantId?: string | null,\n): void {\n if (uid === undefined) {\n cache.clear()\n pending.clear()\n return\n }\n // A revoke reaches the account, not one pool's view of it: clear the\n // project-pool key and the named tenant's, so a caller that does not know\n // which pool answered still gets a fresh read.\n for (const key of [cacheKey(uid, null), cacheKey(uid, tenantId)]) {\n cache.delete(key)\n pending.delete(key)\n }\n}\n\n/** Full reset, for specs. Production code wants the per-uid form above. */\nexport function resetTokenRevocationCache(): void {\n cache.clear()\n pending.clear()\n}\n\n/**\n * Does this account's revocation epoch refuse this token?\n *\n * Both sides are floored to whole seconds before comparing.\n * `tokensValidAfterTime` is an RFC-1123 string with second granularity and\n * `auth_time` is a whole second, so comparing in milliseconds would let a\n * token minted in the same second as the revoke read as refused on one\n * process and admitted on the next.\n *\n * @param decoded - the verified ID token\n * @param validAfterMs - epoch ms from `tokensValidAfterTime`, null when never\n * revoked\n */\nexport function revocationRefuses(\n decoded: DecodedIdToken,\n validAfterMs: number | null | undefined,\n): boolean {\n const validAfter = Number(validAfterMs ?? 0)\n if (!Number.isFinite(validAfter) || validAfter <= 0) return false\n // `auth_time` moves only on a real authentication, which is what makes it\n // the right clock: an attacker holding a stolen cookie and refresh token\n // cannot produce a newer one. `iat` is the fallback for the handful of\n // custom-token sign-ins that carry no `auth_time`.\n const issuedSeconds = Number(decoded?.auth_time ?? decoded?.iat ?? 0)\n // An undateable token cannot be shown to postdate the revocation, and the\n // safe direction for a security control is to refuse it.\n if (!Number.isFinite(issuedSeconds) || issuedSeconds <= 0) return true\n return Math.floor(issuedSeconds) < Math.floor(validAfter / 1000)\n}\n\n/**\n * Read (and cache) the account state behind a uid.\n *\n * `null` means \"could not ask\" — an outage, distinct from every answer the\n * service can give, and never cached.\n */\nasync function readAccountState(\n pool: Pick<BaseAuth, 'getUser'>,\n uid: string,\n key: string,\n): Promise<AccountState | null> {\n const cached = cache.get(key)\n if (cached && Date.now() - cached.at < TOKEN_REVOCATION_TTL_MS) {\n // Re-insert to refresh recency: eviction is least-recently-used, and an\n // ACTIVE session must not be what a uid scan evicts.\n cache.delete(key)\n cache.set(key, cached)\n return cached.state\n }\n let inFlight = pending.get(key)\n if (!inFlight) {\n inFlight = (async () => {\n // No initializer: every path below either assigns `state` or returns,\n // so seeding it with `null` would be a value nothing ever reads.\n let state: AccountState\n try {\n const record = await pool.getUser(uid)\n const validAfterRaw = record?.tokensValidAfterTime\n const parsed = validAfterRaw ? Date.parse(validAfterRaw) : NaN\n state = {\n missing: false,\n disabled: record?.disabled === true,\n validAfterMs: Number.isFinite(parsed) ? parsed : null,\n }\n } catch (error) {\n const code = (error as { code?: string })?.code ?? ''\n if (code === 'auth/user-not-found') {\n state = { missing: true, disabled: false, validAfterMs: null }\n } else {\n // Outage. Fail open, and do NOT cache — one blip must not blind\n // the check for a whole TTL.\n return null\n }\n }\n cache.delete(key)\n cache.set(key, { at: Date.now(), state })\n while (cache.size > TOKEN_REVOCATION_CACHE_MAX) {\n const oldest = cache.keys().next().value\n if (oldest === undefined) break\n cache.delete(oldest)\n }\n return state\n })().finally(() => {\n pending.delete(key)\n })\n pending.set(key, inFlight)\n }\n return inFlight\n}\n\n/**\n * Throw if this verified ID token belongs to an account that has since been\n * revoked, disabled or deleted. Resolves silently otherwise, including when\n * the account could not be reached.\n *\n * @param pool - the auth handle the token was verified against; the lookup\n * MUST go to the same one (AGL-2005), and the parameter is named `pool`\n * rather than `auth` because that is the contract — `no-project-level-auth-\n * lookup.spec.ts` reads the receiver name and is right to\n * @param decoded - the token firebase-admin just verified\n */\nexport async function assertIdTokenNotRevoked(\n pool: Pick<BaseAuth, 'getUser'>,\n decoded: DecodedIdToken,\n): Promise<void> {\n const uid = decoded?.uid\n if (!uid) return\n const tenantId = decoded?.firebase?.tenant ?? null\n const state = await readAccountState(pool, uid, cacheKey(uid, tenantId))\n // `=== null`, not `!state`: strictNullChecks is off repo-wide, so the falsy\n // test would not narrow and would also swallow a real state object one\n // refactor from now.\n if (state === null) return\n if (state.missing) {\n throw new IdTokenRevokedError('The user record no longer exists.')\n }\n if (state.disabled) throw new UserDisabledError()\n if (revocationRefuses(decoded, state.validAfterMs)) {\n throw new IdTokenRevokedError()\n }\n}\n"],"names":["TOKEN_REVOCATION_TTL_MS","TOKEN_REVOCATION_CACHE_MAX","IdTokenRevokedError","Error","message","code","name","UserDisabledError","cache","Map","pending","cacheKey","uid","tenantId","invalidateTokenRevocationCache","undefined","clear","key","delete","resetTokenRevocationCache","revocationRefuses","decoded","validAfterMs","validAfter","Number","isFinite","issuedSeconds","auth_time","iat","Math","floor","readAccountState","pool","cached","get","Date","now","at","set","state","inFlight","record","getUser","validAfterRaw","tokensValidAfterTime","parsed","parse","NaN","missing","disabled","error","size","oldest","keys","next","value","finally","assertIdTokenNotRevoked","firebase","tenant"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAc;oBAAK;gBAC/D,OAAO;oBACL,gEAAgE;oBAChE,6BAA6B;oBAC7B,OAAO;gBACT;YACF;YACAd,MAAMU,MAAM,CAACD;YACbT,MAAM8B,GAAG,CAACrB,KAAK;gBAAEoB,IAAIF,KAAKC,GAAG;gBAAIG;YAAM;YACvC,MAAO/B,MAAM2C,IAAI,GAAGlD,2BAA4B;gBAC9C,MAAMmD,SAAS5C,MAAM6C,IAAI,GAAGC,IAAI,GAAGC,KAAK;gBACxC,IAAIH,WAAWrC,WAAW;gBAC1BP,MAAMU,MAAM,CAACkC;YACf;YACA,OAAOb;QACT,CAAA,IAAKiB,OAAO,CAAC;YACX9C,QAAQQ,MAAM,CAACD;QACjB;QACAP,QAAQ4B,GAAG,CAACrB,KAAKuB;IACnB;IACA,OAAOA;AACT;AAEA;;;;;;;;;;CAUC,GACD,OAAO,eAAeiB,wBACpBzB,IAA+B,EAC/BX,OAAuB;;QAINA;IAFjB,MAAMT,MAAMS,2BAAAA,QAAST,GAAG;IACxB,IAAI,CAACA,KAAK;IACV,MAAMC,mBAAWQ,4BAAAA,oBAAAA,QAASqC,QAAQ,qBAAjBrC,kBAAmBsC,MAAM,mBAAI;IAC9C,MAAMpB,QAAQ,MAAMR,iBAAiBC,MAAMpB,KAAKD,SAASC,KAAKC;IAC9D,4EAA4E;IAC5E,uEAAuE;IACvE,qBAAqB;IACrB,IAAI0B,UAAU,MAAM;IACpB,IAAIA,MAAMS,OAAO,EAAE;QACjB,MAAM,IAAI9C,oBAAoB;IAChC;IACA,IAAIqC,MAAMU,QAAQ,EAAE,MAAM,IAAI1C;IAC9B,IAAIa,kBAAkBC,SAASkB,MAAMjB,YAAY,GAAG;QAClD,MAAM,IAAIpB;IACZ;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/token-revocation.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * ID-token revocation on every server door (AGL-1881).\n *\n * ## The gap this closes\n *\n * `verifyIdToken(token)` checks a signature and an expiry. It does not ask\n * whether the account was locked, disabled, deleted, de-staffed or signed out\n * five seconds ago — that costs a round trip, so the SDK makes it opt-in via\n * `checkRevoked`. The pre-launch audit found the flag set on 3 of 175 call\n * sites: the session MINT, the session EXCHANGE and the device-revoke route.\n * Everything else — 117 console API routes, plus the marketplace, commerce and\n * bookings plugin servers — took a bare `verifyIdToken`.\n *\n * So `revokeRefreshTokens(uid)` stopped the browser getting a NEW token and\n * did nothing about the one it already held. After a panic user-lock, a staff\n * password reset, an SSO offboard, an org-wide lockdown or a \"sign out\n * everywhere\", the revoked token kept opening every one of those doors for the\n * remainder of its hour. `device-revocation.ts` meanwhile promised the effect\n * was \"immediate for everything that goes through our server\", which was the\n * defect worth fixing: the sentence was shipped and it was not true.\n *\n * ## Why it is a cached epoch and not just `checkRevoked: true`\n *\n * `checkRevoked` costs one `accounts:lookup` per verification. Measured\n * against production `aglyn-main` (n=40): p50 95.5ms, p95 144ms — statistically\n * indistinguishable from the p50 85.8ms single Firestore `doc().get()` that\n * every one of these routes already performs, on the same connection from the\n * same machine. So the round trip is not expensive; it is just paid too often.\n * Turned on unconditionally it would multiply Identity Toolkit calls by the\n * whole console request volume, against a project quota, to re-answer a\n * question whose answer changes maybe twice a year per account.\n *\n * The answer is therefore CACHED, on exactly the terms AGL-1522 already set\n * for the panic path: `PLATFORM_TTL_MS`, 15 seconds, LRU-bounded, with the\n * acting process invalidating the uid after its own write. Steady state costs\n * nothing; a cold entry costs one Firestore-read-equivalent; the honest window\n * goes from ~3600s to ≤15s, and to zero on the process that did the revoking.\n * A revocation control whose staleness bound matches the lockdown control it\n * sits beside is one bound to explain, not two.\n *\n * ## What is checked, and in which pool\n *\n * Three refusals, mirroring firebase-admin's own `checkRevoked` so the error\n * codes route handlers already catch keep working unchanged:\n *\n * - `tokensValidAfterTime` after the token's `auth_time` → `id-token-revoked`\n * - `disabled` → `user-disabled` (a user-scope panic lock sets this, and it\n * is the half that does not depend on clock agreement)\n * - the record is GONE → `id-token-revoked` (a deleted account is not a\n * signed-in one; the SDK's own check treats this as revoked too)\n *\n * The lookup is asked of the auth instance the token was verified with, which\n * is the AGL-2005 rule made structural rather than remembered: a tenant-aware\n * auth asks the tenant pool, and a project-pool lookup for an SSO uid — which\n * would answer \"never revoked\" about a forged twin — cannot be spelled.\n *\n * ## Failure direction\n *\n * An unreachable Identity Toolkit is an outage, not a revocation, and refusing\n * every request in the console during one would be a self-inflicted lockdown.\n * So a transport failure fails OPEN — and is NOT cached, or a single blip\n * would blind the check for a full TTL. `user-not-found` is not a transport\n * failure and fails closed. This is the opposite direction from\n * `deviceRevocationRefuses`, which refuses an undateable credential, and the\n * split is deliberate: \"we could not reach the service\" and \"the service told\n * us this account is gone\" are different answers.\n */\n\nimport type { BaseAuth, DecodedIdToken } from 'firebase-admin/auth'\n\n/**\n * Matches `PLATFORM_TTL_MS` in `lockdown.ts`, and deliberately so — see the\n * module note. One number for how stale a panic action may read.\n */\nexport const TOKEN_REVOCATION_TTL_MS = 15_000\n\n/**\n * Bounded so a scan of uids cannot balloon a warm serverless process. Past\n * this many entries the least-recently-USED is evicted; a cache hit refreshes\n * recency, so an active session is not what a scan pushes out. Same bound and\n * same reasoning as `USER_LOCKDOWN_CACHE_MAX`.\n */\nexport const TOKEN_REVOCATION_CACHE_MAX = 5000\n\n/** Thrown for a token the account has invalidated. Code matches the SDK's. */\nexport class IdTokenRevokedError extends Error {\n readonly code = 'auth/id-token-revoked'\n constructor(message = 'The ID token has been revoked.') {\n super(message)\n this.name = 'IdTokenRevokedError'\n }\n}\n\n/** Thrown for a token whose account is disabled. Code matches the SDK's. */\nexport class UserDisabledError extends Error {\n readonly code = 'auth/user-disabled'\n constructor(message = 'The user record is disabled.') {\n super(message)\n this.name = 'UserDisabledError'\n }\n}\n\n/** What the check needs off the account record, and nothing else. */\nexport interface AccountRevocationState {\n /** `true` when the record could not be found at all. */\n missing: boolean\n disabled: boolean\n /** `tokensValidAfterTime` as epoch ms; null when never revoked. */\n validAfterMs: number | null\n}\n\nconst cache = new Map<string, { at: number; state: AccountRevocationState }>()\nconst pending = new Map<string, Promise<AccountRevocationState | null>>()\n\n/**\n * A uid is only unique WITHIN a pool (AGL-2005), so the pool is part of the\n * key. The separator is a NUL because a tenant id cannot contain one.\n */\nfunction cacheKey(uid: string, tenantId: string | null | undefined): string {\n return `${tenantId ?? ''}\\u0000${uid}`\n}\n\n/**\n * Drop one account's cached verdict — called by every path that revokes, so\n * the process that took the action refuses on its very next request instead\n * of waiting out its own TTL. Called bare, clears everything.\n */\nexport function invalidateTokenRevocationCache(\n uid?: string,\n tenantId?: string | null,\n): void {\n if (uid === undefined) {\n cache.clear()\n pending.clear()\n return\n }\n // A revoke reaches the account, not one pool's view of it: clear the\n // project-pool key and the named tenant's, so a caller that does not know\n // which pool answered still gets a fresh read.\n for (const key of [cacheKey(uid, null), cacheKey(uid, tenantId)]) {\n cache.delete(key)\n pending.delete(key)\n }\n}\n\n/** Full reset, for specs. Production code wants the per-uid form above. */\nexport function resetTokenRevocationCache(): void {\n cache.clear()\n pending.clear()\n}\n\n/**\n * Does this account's revocation epoch refuse this token?\n *\n * Both sides are floored to whole seconds before comparing.\n * `tokensValidAfterTime` is an RFC-1123 string with second granularity and\n * `auth_time` is a whole second, so comparing in milliseconds would let a\n * token minted in the same second as the revoke read as refused on one\n * process and admitted on the next.\n *\n * @param decoded - the verified ID token\n * @param validAfterMs - epoch ms from `tokensValidAfterTime`, null when never\n * revoked\n */\nexport function revocationRefuses(\n decoded: DecodedIdToken,\n validAfterMs: number | null | undefined,\n): boolean {\n const validAfter = Number(validAfterMs ?? 0)\n if (!Number.isFinite(validAfter) || validAfter <= 0) return false\n // `auth_time` moves only on a real authentication, which is what makes it\n // the right clock: an attacker holding a stolen cookie and refresh token\n // cannot produce a newer one. `iat` is the fallback for the handful of\n // custom-token sign-ins that carry no `auth_time`.\n const issuedSeconds = Number(decoded?.auth_time ?? decoded?.iat ?? 0)\n // An undateable token cannot be shown to postdate the revocation, and the\n // safe direction for a security control is to refuse it.\n if (!Number.isFinite(issuedSeconds) || issuedSeconds <= 0) return true\n return Math.floor(issuedSeconds) < Math.floor(validAfter / 1000)\n}\n\n/**\n * Read (and cache) the account state behind a uid.\n *\n * `null` means \"could not ask\" — an outage, distinct from every answer the\n * service can give, and never cached.\n */\nasync function readAccountState(\n pool: Pick<BaseAuth, 'getUser'>,\n uid: string,\n key: string,\n): Promise<AccountRevocationState | null> {\n const cached = cache.get(key)\n if (cached && Date.now() - cached.at < TOKEN_REVOCATION_TTL_MS) {\n // Re-insert to refresh recency: eviction is least-recently-used, and an\n // ACTIVE session must not be what a uid scan evicts.\n cache.delete(key)\n cache.set(key, cached)\n return cached.state\n }\n let inFlight = pending.get(key)\n if (!inFlight) {\n inFlight = (async () => {\n // No initializer: every path below either assigns `state` or returns,\n // so seeding it with `null` would be a value nothing ever reads.\n let state: AccountRevocationState\n try {\n const record = await pool.getUser(uid)\n const validAfterRaw = record?.tokensValidAfterTime\n const parsed = validAfterRaw ? Date.parse(validAfterRaw) : NaN\n state = {\n missing: false,\n disabled: record?.disabled === true,\n validAfterMs: Number.isFinite(parsed) ? parsed : null,\n }\n } catch (error) {\n const code = (error as { code?: string })?.code ?? ''\n if (code === 'auth/user-not-found') {\n state = { missing: true, disabled: false, validAfterMs: null }\n } else {\n // Outage. Fail open, and do NOT cache — one blip must not blind\n // the check for a whole TTL.\n return null\n }\n }\n cache.delete(key)\n cache.set(key, { at: Date.now(), state })\n while (cache.size > TOKEN_REVOCATION_CACHE_MAX) {\n const oldest = cache.keys().next().value\n if (oldest === undefined) break\n cache.delete(oldest)\n }\n return state\n })().finally(() => {\n pending.delete(key)\n })\n pending.set(key, inFlight)\n }\n return inFlight\n}\n\n/**\n * The cached account state behind a uid, for a credential that is not an ID\n * token: the site edit bar's own token (AGL-1842), which names the uid and\n * the pool it was minted for but carries no `auth_time`. Same cache, same\n * 15-second bound and same pool rule as {@link assertIdTokenNotRevoked}.\n * `null` means the service could not be asked; the caller fails open.\n *\n * @param pool - the auth handle of the pool the uid lives in (AGL-2005)\n */\nexport async function readAccountRevocationState(\n pool: Pick<BaseAuth, 'getUser'>,\n uid: string,\n tenantId: string | null,\n): Promise<Readonly<AccountRevocationState> | null> {\n if (!uid) return null\n return readAccountState(pool, uid, cacheKey(uid, tenantId))\n}\n\n/**\n * Throw if this verified ID token belongs to an account that has since been\n * revoked, disabled or deleted. Resolves silently otherwise, including when\n * the account could not be reached.\n *\n * @param pool - the auth handle the token was verified against; the lookup\n * MUST go to the same one (AGL-2005), and the parameter is named `pool`\n * rather than `auth` because that is the contract — `no-project-level-auth-\n * lookup.spec.ts` reads the receiver name and is right to\n * @param decoded - the token firebase-admin just verified\n */\nexport async function assertIdTokenNotRevoked(\n pool: Pick<BaseAuth, 'getUser'>,\n decoded: DecodedIdToken,\n): Promise<void> {\n const uid = decoded?.uid\n if (!uid) return\n const tenantId = decoded?.firebase?.tenant ?? null\n const state = await readAccountState(pool, uid, cacheKey(uid, tenantId))\n // `=== null`, not `!state`: strictNullChecks is off repo-wide, so the falsy\n // test would not narrow and would also swallow a real state object one\n // refactor from now.\n if (state === null) return\n if (state.missing) {\n throw new IdTokenRevokedError('The user record no longer exists.')\n }\n if (state.disabled) throw new UserDisabledError()\n if (revocationRefuses(decoded, state.validAfterMs)) {\n throw new IdTokenRevokedError()\n }\n}\n"],"names":["TOKEN_REVOCATION_TTL_MS","TOKEN_REVOCATION_CACHE_MAX","IdTokenRevokedError","Error","message","code","name","UserDisabledError","cache","Map","pending","cacheKey","uid","tenantId","invalidateTokenRevocationCache","undefined","clear","key","delete","resetTokenRevocationCache","revocationRefuses","decoded","validAfterMs","validAfter","Number","isFinite","issuedSeconds","auth_time","iat","Math","floor","readAccountState","pool","cached","get","Date","now","at","set","state","inFlight","record","getUser","validAfterRaw","tokensValidAfterTime","parsed","parse","NaN","missing","disabled","error","size","oldest","keys","next","value","finally","readAccountRevocationState","assertIdTokenNotRevoked","firebase","tenant"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkEC,GAID;;;CAGC,GACD,OAAO,MAAMA,0BAA0B,MAAM;AAE7C;;;;;CAKC,GACD,OAAO,MAAMC,6BAA6B,KAAI;AAE9C,4EAA4E,GAC5E,OAAO,MAAMC,4BAA4BC;IAEvC,YAAYC,UAAU,gCAAgC,CAAE;QACtD,KAAK,CAACA,eAFCC,OAAO;QAGd,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,0EAA0E,GAC1E,OAAO,MAAMC,0BAA0BJ;IAErC,YAAYC,UAAU,8BAA8B,CAAE;QACpD,KAAK,CAACA,eAFCC,OAAO;QAGd,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAWA,MAAME,QAAQ,IAAIC;AAClB,MAAMC,UAAU,IAAID;AAEpB;;;CAGC,GACD,SAASE,SAASC,GAAW,EAAEC,QAAmC;IAChE,OAAO,GAAGA,mBAAAA,WAAY,GAAG,MAAM,EAAED,KAAK;AACxC;AAEA;;;;CAIC,GACD,OAAO,SAASE,+BACdF,GAAY,EACZC,QAAwB;IAExB,IAAID,QAAQG,WAAW;QACrBP,MAAMQ,KAAK;QACXN,QAAQM,KAAK;QACb;IACF;IACA,qEAAqE;IACrE,0EAA0E;IAC1E,+CAA+C;IAC/C,KAAK,MAAMC,OAAO;QAACN,SAASC,KAAK;QAAOD,SAASC,KAAKC;KAAU,CAAE;QAChEL,MAAMU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AAmBuC,MAAM,mBAAI;IAC9C,MAAMrB,QAAQ,MAAMR,iBAAiBC,MAAMpB,KAAKD,SAASC,KAAKC;IAC9D,4EAA4E;IAC5E,uEAAuE;IACvE,qBAAqB;IACrB,IAAI0B,UAAU,MAAM;IACpB,IAAIA,MAAMS,OAAO,EAAE;QACjB,MAAM,IAAI9C,oBAAoB;IAChC;IACA,IAAIqC,MAAMU,QAAQ,EAAE,MAAM,IAAI1C;IAC9B,IAAIa,kBAAkBC,SAASkB,MAAMjB,YAAY,GAAG;QAClD,MAAM,IAAIpB;IACZ;AACF"}
|
package/src/tenancy.d.ts
CHANGED
|
@@ -52,6 +52,7 @@ export * from './lib/server/collection-preview-token';
|
|
|
52
52
|
export * from './lib/server/edit-access-authz';
|
|
53
53
|
export * from './lib/server/edit-access-token';
|
|
54
54
|
export * from './lib/server/edit-hint-token';
|
|
55
|
+
export * from './lib/server/edit-hint-end';
|
|
55
56
|
export * from './lib/server/email-metering';
|
|
56
57
|
export * from './lib/server/email-send-rate';
|
|
57
58
|
export * from './lib/server/email-transactional-ceiling';
|
package/src/tenancy.js
CHANGED
|
@@ -70,6 +70,7 @@ export * from "./lib/server/collection-preview-token.js";
|
|
|
70
70
|
export * from "./lib/server/edit-access-authz.js";
|
|
71
71
|
export * from "./lib/server/edit-access-token.js";
|
|
72
72
|
export * from "./lib/server/edit-hint-token.js";
|
|
73
|
+
export * from "./lib/server/edit-hint-end.js";
|
|
73
74
|
export * from "./lib/server/email-metering.js";
|
|
74
75
|
// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the
|
|
75
76
|
// platform send-rate governor on `sendEmail`. Every server surface already
|
package/src/tenancy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/data/admin/src/tenancy.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './lib/server/analytics-retention'\nexport * from './lib/server/api-http'\nexport * from './lib/server/api-keys'\nexport * from './lib/server/account-emails'\nexport * from './lib/server/auth-pools'\nexport * from './lib/server/client-error-report'\n// The merchant's payment account, as a contract. Its adapter is not exported:\n// a plugin asks the contract, and the doors that only need the readiness rule\n// import `@aglyn/tenant-data-admin/server/payment-provider` directly, which\n// loads no Firebase.\nexport {\n accountChargeModel,\n connectedAccountHeader,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n directChargeParams,\n merchantAccountInOtherMode,\n merchantAccountIsReady,\n merchantAccountReadiness,\n merchantAccountReplacement,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n saleChargeModel,\n} from './lib/server/payment-provider'\nexport type {\n SaleChargeModel,\n MerchantAccountReadiness,\n MerchantAccountReadinessInput,\n PaymentMode,\n PaymentProvider,\n PaymentProviderEvent,\n} from './lib/server/payment-provider'\nexport * from './lib/server/auth-handoff'\nexport * from './lib/server/console-domains'\nexport * from './lib/server/dns-probe'\n// Whether a name points at the tenant edge, for the verify route and the\n// domains plugin's one-click DNS (AGL-3963).\nexport * from './lib/server/tenant-dns-check'\nexport * from './lib/server/sending-domains'\nexport * from './lib/server/sender-readiness'\nexport * from './lib/server/host-sending-domain'\nexport * from './lib/server/sending-domain-debt'\nexport * from './lib/server/sending-domain-recheck'\n// The hosting seam itself, so a door can ask whether this deployment is able\n// to register a name at all before it promises the caller one.\n// `workspace-domains` re-exports the pieces its own callers share with it; the\n// provider behind it is not among them.\nexport { domainProvider } from './lib/server/domain-provider'\nexport type {\n DomainProvider,\n DomainProviderId,\n DomainScope,\n} from './lib/server/domain-provider'\nexport * from './lib/server/platform-domain-names'\nexport * from './lib/server/consume-once'\nexport * from './lib/server/csp-aggregate'\nexport * from './lib/server/data-storage-gate'\nexport * from './lib/server/contact-suppression'\nexport * from './lib/server/email-suppression'\n// The double opt-in quarantine, after the module whose keying it shares and\n// whose `filterTopicSendable` is the reader that makes it a quarantine rather\n// than a stored fact.\nexport * from './lib/server/topic-subscriptions'\nexport * from './lib/server/email-unsubscribe-link'\nexport * from './lib/server/email-flow-gate'\n// Side-effecting on purpose, for the reason `email-send-rate` below is:\n// evaluating this module INSTALLS the marketing gate on `sendEmail`, so the\n// unsubscribe header, the suppression check and the frequency ceiling reach\n// every bulk sender without a call at each server entrypoint.\nexport * from './lib/server/email-marketing-gate'\n// A consent group change (AGL-3320): the carries of the three stores above,\n// and the executor that runs a change around them.\nexport * from './lib/server/consent-group-carry'\nexport * from './lib/server/consent-group-change'\n// A person's refusal kept after the record it was written on is deleted\n// (AGL-3338): the delete's write, the list gate's read, and the change's carry.\nexport * from './lib/server/retained-refusals'\nexport * from './lib/server/sms-keywords'\nexport * from './lib/server/document-id'\nexport * from './lib/server/collection-preview-token'\nexport * from './lib/server/edit-access-authz'\nexport * from './lib/server/edit-access-token'\nexport * from './lib/server/edit-hint-token'\nexport * from './lib/server/email-metering'\n// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the\n// platform send-rate governor on `sendEmail`. Every server surface already\n// imports this barrel, so nothing has to remember to call an installer.\nexport * from './lib/server/email-send-rate'\n// Side-effecting on purpose, for the same reason (AGL-4145): evaluating this\n// module INSTALLS the daily transactional ceiling on `sendEmail`, so a site's\n// non-campaign mail is counted per organization per UTC day on every send\n// path at once.\nexport * from './lib/server/email-transactional-ceiling'\n// Side-effecting on purpose, for the same reason (AGL-3328): evaluating this\n// module INSTALLS the deliverability preflight on `sendEmail`, so a recipient\n// whose domain takes no mail is refused, and bulk mail behind a gateway that\n// refused its sending domain twice is held, on every send path at once.\nexport * from './lib/server/email-deliverability'\nexport * from './lib/server/email-sender-reputation'\nexport * from './lib/server/erase'\nexport * from './lib/server/erase-person'\nexport * from './lib/server/dynamic-list-materialize'\nexport * from './lib/server/firebase-admin'\nexport * from './lib/server/free-workspace-cap'\nexport * from './lib/server/ga4-measurement-protocol'\nexport * from './lib/server/host-memberships'\n// Connecting a name to a site, for the attach route and for plugins that\n// bought the name (AGL-3961).\nexport * from './lib/server/host-custom-domain'\nexport * from './lib/server/custom-domain-redirects'\nexport * from './lib/server/host-visitor-records'\nexport * from './lib/server/list-members'\nexport * from './lib/server/lockdown'\nexport * from './lib/server/token-revocation'\nexport * from './lib/server/tenant-write-lockdown'\nexport * from './lib/server/outbound-send-review'\n// The same review for a published page, read where it is composed (AGL-3356).\nexport * from './lib/server/hosted-page-review'\n// Every hold, flag, lock and pause tells owners and staff through one seam (AGL-3368).\nexport * from './lib/server/risk-notice'\nexport * from './lib/server/host-email-tokens'\nexport * from './lib/server/notifications'\n// Every operator alert raises through one entry point, and every health check\n// remembers its state (AGL-3377).\nexport * from './lib/server/operator-alerts'\nexport * from './lib/server/operator-health'\nexport * from './lib/server/org-billing'\nexport * from './lib/server/organizations'\n// Per-member permission overrides, org-wide and per site (AGL-4047).\nexport * from './lib/server/member-permission-overrides'\n// Platform staff take no customer seat, and a workspace is asked to upgrade\n// as a separate step after it is handed over (AGL-3466).\nexport * from './lib/server/staff-seat'\nexport * from './lib/server/upgrade-proposal'\nexport * from './lib/server/duplicate-activity'\nexport * from './lib/server/duplicate-resource'\nexport * from './lib/server/workspace-domains'\nexport * from './lib/server/membership-recover-throttle'\nexport * from './lib/server/password-reset-throttle'\nexport * from './lib/server/rate-limit-store'\nexport * from './lib/server/verify-email-cooldown'\nexport * from './lib/server/vercel-drain-signature'\nexport * from './lib/server/vercel-log-drain'\nexport * from './lib/server/visitor-write-rate-limit'\nexport * from './lib/server/card-payment-velocity'\nexport * from './lib/server/console-api-rate-limit'\nexport * from './lib/server/realm-plugins'\nexport * from './lib/server/release-flags'\nexport * from './lib/server/resolve-people'\nexport * from './lib/server/member-photo'\nexport * from './lib/server/personal-data-export'\nexport * from './lib/server/media-delivery'\nexport * from './lib/server/media-download-tokens'\nexport * from './lib/server/media-quarantine'\nexport * from './lib/server/media-signing'\nexport * from './lib/server/media-storage-path'\nexport * from './lib/server/safe-equal'\nexport * from './lib/server/media-strong-digest'\nexport * from './lib/server/media-tombstone'\nexport * from './lib/server/media-delivery-regeneration'\nexport * from './lib/server/media-variants'\nexport * from './lib/server/media-photo-links'\n// The one-screen build for a client (AGL-3958): staff hold its record.\nexport * from './lib/server/client-build'\nexport * from './lib/server/serve-media-cdn'\nexport * from './lib/server/serve-plugin-fetch'\nexport * from './lib/server/configured-url-fetch'\nexport * from './lib/server/sso-break-glass-owners'\nexport * from './lib/server/sso-domain-policy'\nexport * from './lib/server/sso-enforcement'\nexport * from './lib/server/sso-provisioning'\nexport * from './lib/server/update-existing'\nexport * from './lib/server/contact-company-link'\nexport * from './lib/server/contact-email-index'\nexport * from './lib/server/upsert-contact'\nexport * from './lib/server/crm-records'\n// The `nextTaskAtMs` a contact, a company and a deal carry, recomputed from\n// their open tasks by every server-side task writer (AGL-2661).\n// Where a one-to-one email's activity row lives and how the delivery\n// webhook advances it (AGL-2615).\n// A member's own addresses in a workspace, and the signed link that\n// confirms one (AGL-2975).\nexport * from './lib/server/member-email-aliases'\nexport * from './lib/server/user-profiles'\n// One answer to an account's name and photo, and the SSO sign-in fill of a\n// blank Auth record (AGL-3721).\nexport * from './lib/server/account-identity'\n// The one \"New account\" staff notice per account, keyed on the auth\n// record's creation (AGL-3225).\nexport * from './lib/server/new-account-announcement'\nexport * from './lib/server/legal-acceptance'\n// The person's decision about the platform's own product email, on their\n// document and on the operator's marketing contact (AGL-3185).\nexport * from './lib/server/platform-marketing-consent'\n"],"names":["accountChargeModel","connectedAccountHeader","DIRECT_CHARGE_ACCOUNT_PARAMS","directChargeParams","merchantAccountInOtherMode","merchantAccountIsReady","merchantAccountReadiness","merchantAccountReplacement","paymentProvider","PREVIOU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Ac,mCAA+B;AAC7C,cAAc,2CAAuC;AACrD,cAAc,wCAAoC;AAClD,cAAc,yCAAqC;AACnD,cAAc,gCAA4B;AAC1C,cAAc,gCAA4B;AAC1C,cAAc,iCAA6B;AAC3C,cAAc,+BAA2B;AACzC,cAAc,uCAAmC;AACjD,cAAc,iCAA6B;AAC3C,cAAc,wCAAoC;AAClD,cAAc,mCAA+B;AAC7C,cAAc,gCAA4B;AAC1C,cAAc,qCAAiC;AAC/C,cAAc,6BAAyB;AACvC,cAAc,sCAAkC;AAChD,cAAc,kCAA8B;AAC5C,cAAc,8CAA0C;AACxD,cAAc,iCAA6B;AAC3C,cAAc,oCAAgC;AAC9C,uEAAuE;AACvE,cAAc,+BAA2B;AACzC,cAAc,kCAA8B;AAC5C,cAAc,qCAAiC;AAC/C,cAAc,uCAAmC;AACjD,cAAc,yCAAqC;AACnD,cAAc,oCAAgC;AAC9C,cAAc,kCAA8B;AAC5C,cAAc,mCAA+B;AAC7C,cAAc,kCAA8B;AAC5C,cAAc,uCAAmC;AACjD,cAAc,sCAAkC;AAChD,cAAc,iCAA6B;AAC3C,cAAc,8BAA0B;AACxC,4EAA4E;AAC5E,gEAAgE;AAChE,qEAAqE;AACrE,kCAAkC;AAClC,oEAAoE;AACpE,2BAA2B;AAC3B,cAAc,uCAAmC;AACjD,cAAc,gCAA4B;AAC1C,2EAA2E;AAC3E,gCAAgC;AAChC,cAAc,mCAA+B;AAC7C,oEAAoE;AACpE,gCAAgC;AAChC,cAAc,2CAAuC;AACrD,cAAc,mCAA+B;AAC7C,yEAAyE;AACzE,+DAA+D;AAC/D,cAAc,6CAAyC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/data/admin/src/tenancy.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './lib/server/analytics-retention'\nexport * from './lib/server/api-http'\nexport * from './lib/server/api-keys'\nexport * from './lib/server/account-emails'\nexport * from './lib/server/auth-pools'\nexport * from './lib/server/client-error-report'\n// The merchant's payment account, as a contract. Its adapter is not exported:\n// a plugin asks the contract, and the doors that only need the readiness rule\n// import `@aglyn/tenant-data-admin/server/payment-provider` directly, which\n// loads no Firebase.\nexport {\n accountChargeModel,\n connectedAccountHeader,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n directChargeParams,\n merchantAccountInOtherMode,\n merchantAccountIsReady,\n merchantAccountReadiness,\n merchantAccountReplacement,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n saleChargeModel,\n} from './lib/server/payment-provider'\nexport type {\n SaleChargeModel,\n MerchantAccountReadiness,\n MerchantAccountReadinessInput,\n PaymentMode,\n PaymentProvider,\n PaymentProviderEvent,\n} from './lib/server/payment-provider'\nexport * from './lib/server/auth-handoff'\nexport * from './lib/server/console-domains'\nexport * from './lib/server/dns-probe'\n// Whether a name points at the tenant edge, for the verify route and the\n// domains plugin's one-click DNS (AGL-3963).\nexport * from './lib/server/tenant-dns-check'\nexport * from './lib/server/sending-domains'\nexport * from './lib/server/sender-readiness'\nexport * from './lib/server/host-sending-domain'\nexport * from './lib/server/sending-domain-debt'\nexport * from './lib/server/sending-domain-recheck'\n// The hosting seam itself, so a door can ask whether this deployment is able\n// to register a name at all before it promises the caller one.\n// `workspace-domains` re-exports the pieces its own callers share with it; the\n// provider behind it is not among them.\nexport { domainProvider } from './lib/server/domain-provider'\nexport type {\n DomainProvider,\n DomainProviderId,\n DomainScope,\n} from './lib/server/domain-provider'\nexport * from './lib/server/platform-domain-names'\nexport * from './lib/server/consume-once'\nexport * from './lib/server/csp-aggregate'\nexport * from './lib/server/data-storage-gate'\nexport * from './lib/server/contact-suppression'\nexport * from './lib/server/email-suppression'\n// The double opt-in quarantine, after the module whose keying it shares and\n// whose `filterTopicSendable` is the reader that makes it a quarantine rather\n// than a stored fact.\nexport * from './lib/server/topic-subscriptions'\nexport * from './lib/server/email-unsubscribe-link'\nexport * from './lib/server/email-flow-gate'\n// Side-effecting on purpose, for the reason `email-send-rate` below is:\n// evaluating this module INSTALLS the marketing gate on `sendEmail`, so the\n// unsubscribe header, the suppression check and the frequency ceiling reach\n// every bulk sender without a call at each server entrypoint.\nexport * from './lib/server/email-marketing-gate'\n// A consent group change (AGL-3320): the carries of the three stores above,\n// and the executor that runs a change around them.\nexport * from './lib/server/consent-group-carry'\nexport * from './lib/server/consent-group-change'\n// A person's refusal kept after the record it was written on is deleted\n// (AGL-3338): the delete's write, the list gate's read, and the change's carry.\nexport * from './lib/server/retained-refusals'\nexport * from './lib/server/sms-keywords'\nexport * from './lib/server/document-id'\nexport * from './lib/server/collection-preview-token'\nexport * from './lib/server/edit-access-authz'\nexport * from './lib/server/edit-access-token'\nexport * from './lib/server/edit-hint-token'\nexport * from './lib/server/edit-hint-end'\nexport * from './lib/server/email-metering'\n// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the\n// platform send-rate governor on `sendEmail`. Every server surface already\n// imports this barrel, so nothing has to remember to call an installer.\nexport * from './lib/server/email-send-rate'\n// Side-effecting on purpose, for the same reason (AGL-4145): evaluating this\n// module INSTALLS the daily transactional ceiling on `sendEmail`, so a site's\n// non-campaign mail is counted per organization per UTC day on every send\n// path at once.\nexport * from './lib/server/email-transactional-ceiling'\n// Side-effecting on purpose, for the same reason (AGL-3328): evaluating this\n// module INSTALLS the deliverability preflight on `sendEmail`, so a recipient\n// whose domain takes no mail is refused, and bulk mail behind a gateway that\n// refused its sending domain twice is held, on every send path at once.\nexport * from './lib/server/email-deliverability'\nexport * from './lib/server/email-sender-reputation'\nexport * from './lib/server/erase'\nexport * from './lib/server/erase-person'\nexport * from './lib/server/dynamic-list-materialize'\nexport * from './lib/server/firebase-admin'\nexport * from './lib/server/free-workspace-cap'\nexport * from './lib/server/ga4-measurement-protocol'\nexport * from './lib/server/host-memberships'\n// Connecting a name to a site, for the attach route and for plugins that\n// bought the name (AGL-3961).\nexport * from './lib/server/host-custom-domain'\nexport * from './lib/server/custom-domain-redirects'\nexport * from './lib/server/host-visitor-records'\nexport * from './lib/server/list-members'\nexport * from './lib/server/lockdown'\nexport * from './lib/server/token-revocation'\nexport * from './lib/server/tenant-write-lockdown'\nexport * from './lib/server/outbound-send-review'\n// The same review for a published page, read where it is composed (AGL-3356).\nexport * from './lib/server/hosted-page-review'\n// Every hold, flag, lock and pause tells owners and staff through one seam (AGL-3368).\nexport * from './lib/server/risk-notice'\nexport * from './lib/server/host-email-tokens'\nexport * from './lib/server/notifications'\n// Every operator alert raises through one entry point, and every health check\n// remembers its state (AGL-3377).\nexport * from './lib/server/operator-alerts'\nexport * from './lib/server/operator-health'\nexport * from './lib/server/org-billing'\nexport * from './lib/server/organizations'\n// Per-member permission overrides, org-wide and per site (AGL-4047).\nexport * from './lib/server/member-permission-overrides'\n// Platform staff take no customer seat, and a workspace is asked to upgrade\n// as a separate step after it is handed over (AGL-3466).\nexport * from './lib/server/staff-seat'\nexport * from './lib/server/upgrade-proposal'\nexport * from './lib/server/duplicate-activity'\nexport * from './lib/server/duplicate-resource'\nexport * from './lib/server/workspace-domains'\nexport * from './lib/server/membership-recover-throttle'\nexport * from './lib/server/password-reset-throttle'\nexport * from './lib/server/rate-limit-store'\nexport * from './lib/server/verify-email-cooldown'\nexport * from './lib/server/vercel-drain-signature'\nexport * from './lib/server/vercel-log-drain'\nexport * from './lib/server/visitor-write-rate-limit'\nexport * from './lib/server/card-payment-velocity'\nexport * from './lib/server/console-api-rate-limit'\nexport * from './lib/server/realm-plugins'\nexport * from './lib/server/release-flags'\nexport * from './lib/server/resolve-people'\nexport * from './lib/server/member-photo'\nexport * from './lib/server/personal-data-export'\nexport * from './lib/server/media-delivery'\nexport * from './lib/server/media-download-tokens'\nexport * from './lib/server/media-quarantine'\nexport * from './lib/server/media-signing'\nexport * from './lib/server/media-storage-path'\nexport * from './lib/server/safe-equal'\nexport * from './lib/server/media-strong-digest'\nexport * from './lib/server/media-tombstone'\nexport * from './lib/server/media-delivery-regeneration'\nexport * from './lib/server/media-variants'\nexport * from './lib/server/media-photo-links'\n// The one-screen build for a client (AGL-3958): staff hold its record.\nexport * from './lib/server/client-build'\nexport * from './lib/server/serve-media-cdn'\nexport * from './lib/server/serve-plugin-fetch'\nexport * from './lib/server/configured-url-fetch'\nexport * from './lib/server/sso-break-glass-owners'\nexport * from './lib/server/sso-domain-policy'\nexport * from './lib/server/sso-enforcement'\nexport * from './lib/server/sso-provisioning'\nexport * from './lib/server/update-existing'\nexport * from './lib/server/contact-company-link'\nexport * from './lib/server/contact-email-index'\nexport * from './lib/server/upsert-contact'\nexport * from './lib/server/crm-records'\n// The `nextTaskAtMs` a contact, a company and a deal carry, recomputed from\n// their open tasks by every server-side task writer (AGL-2661).\n// Where a one-to-one email's activity row lives and how the delivery\n// webhook advances it (AGL-2615).\n// A member's own addresses in a workspace, and the signed link that\n// confirms one (AGL-2975).\nexport * from './lib/server/member-email-aliases'\nexport * from './lib/server/user-profiles'\n// One answer to an account's name and photo, and the SSO sign-in fill of a\n// blank Auth record (AGL-3721).\nexport * from './lib/server/account-identity'\n// The one \"New account\" staff notice per account, keyed on the auth\n// record's creation (AGL-3225).\nexport * from './lib/server/new-account-announcement'\nexport * from './lib/server/legal-acceptance'\n// The person's decision about the platform's own product email, on their\n// document and on the operator's marketing contact (AGL-3185).\nexport * from './lib/server/platform-marketing-consent'\n"],"names":["accountChargeModel","connectedAccountHeader","DIRECT_CHARGE_ACCOUNT_PARAMS","directChargeParams","merchantAccountInOtherMode","merchantAccountIsReady","merchantAccountReadiness","merchantAccountReplacement","paymentProvider","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","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