@aglyn/tenant-data-admin 1.0.0-beta.288 → 1.0.0-beta.290
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/account-acquisition.js +19 -3
- package/src/lib/server/account-acquisition.js.map +1 -1
- package/src/lib/server/platform-marketing-consent.d.ts +33 -0
- package/src/lib/server/platform-marketing-consent.js +58 -0
- package/src/lib/server/platform-marketing-consent.js.map +1 -1
- package/src/lib/server/platform-served-domain.d.ts +60 -0
- package/src/lib/server/platform-served-domain.js +146 -0
- package/src/lib/server/platform-served-domain.js.map +1 -0
- package/src/lib/server/site-preview-token.d.ts +42 -0
- package/src/lib/server/site-preview-token.js +123 -0
- package/src/lib/server/site-preview-token.js.map +1 -0
- package/src/lib/server/site-view-authz.d.ts +88 -0
- package/src/lib/server/site-view-authz.js +103 -0
- package/src/lib/server/site-view-authz.js.map +1 -0
- package/src/lib/server/visitor-upload.d.ts +167 -0
- package/src/lib/server/visitor-upload.js +364 -0
- package/src/lib/server/visitor-upload.js.map +1 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { liveCustomDomain, TENANT_APEX } from "@aglyn/aglyn/app-utils/host-naming";
|
|
18
|
+
import firebaseAdmin from "./firebase-admin.js";
|
|
19
|
+
import { PLATFORM_DOMAIN_PATTERN, MAX_DOMAIN_LENGTH } from "./platform-domain-names.js";
|
|
20
|
+
import { projectDomainStatus } from "./workspace-domains.js";
|
|
21
|
+
const HOST_DOMAIN_FIELDS = [
|
|
22
|
+
'subdomain',
|
|
23
|
+
'cname',
|
|
24
|
+
'cnameTwin',
|
|
25
|
+
'cnameAttachmentPending',
|
|
26
|
+
'cnameDetachmentPending',
|
|
27
|
+
'cnameTwinPending'
|
|
28
|
+
];
|
|
29
|
+
async function findHostsInFirestore(field, value) {
|
|
30
|
+
const snapshot = await firebaseAdmin.app().firestore().collection('hosts').where(field, '==', value).select(...HOST_DOMAIN_FIELDS).limit(2).get();
|
|
31
|
+
return snapshot.docs.map((doc)=>{
|
|
32
|
+
const data = doc.data();
|
|
33
|
+
return _extends({}, data, {
|
|
34
|
+
id: doc.id
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** A request's hostname, lowercased and without a trailing dot; null for anything else. */ export function normalizeServedHostname(input) {
|
|
39
|
+
const name = String(input != null ? input : '').trim().toLowerCase().replace(/\.+$/, '');
|
|
40
|
+
if (!name || name.length > MAX_DOMAIN_LENGTH) return null;
|
|
41
|
+
if (!PLATFORM_DOMAIN_PATTERN.test(name)) return null;
|
|
42
|
+
return name;
|
|
43
|
+
}
|
|
44
|
+
/** Whether a name serves on our deployment, and why not when it does not. Never throws. */ export async function platformServedDomain(hostname, deps = {}) {
|
|
45
|
+
var _deps_findHosts, _deps_domainStatus;
|
|
46
|
+
const name = normalizeServedHostname(hostname);
|
|
47
|
+
if (!name || name === TENANT_APEX) return {
|
|
48
|
+
served: false,
|
|
49
|
+
reason: 'not-a-hostname'
|
|
50
|
+
};
|
|
51
|
+
const findHosts = (_deps_findHosts = deps.findHosts) != null ? _deps_findHosts : findHostsInFirestore;
|
|
52
|
+
const domainStatus = (_deps_domainStatus = deps.domainStatus) != null ? _deps_domainStatus : (host)=>projectDomainStatus(host, {
|
|
53
|
+
scope: 'tenant'
|
|
54
|
+
});
|
|
55
|
+
try {
|
|
56
|
+
// A platform subdomain: one label under the apex, held by exactly one host.
|
|
57
|
+
if (name.endsWith(`.${TENANT_APEX}`)) {
|
|
58
|
+
const sub = name.slice(0, -(TENANT_APEX.length + 1));
|
|
59
|
+
if (!sub || sub.includes('.')) return {
|
|
60
|
+
served: false,
|
|
61
|
+
reason: 'no-host'
|
|
62
|
+
};
|
|
63
|
+
const hosts = (await findHosts('subdomain', sub)).filter((host)=>host.subdomain === sub);
|
|
64
|
+
if (hosts.length === 0) return {
|
|
65
|
+
served: false,
|
|
66
|
+
reason: 'no-host'
|
|
67
|
+
};
|
|
68
|
+
if (hosts.length > 1) return {
|
|
69
|
+
served: false,
|
|
70
|
+
reason: 'ambiguous'
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
served: true,
|
|
74
|
+
via: 'subdomain',
|
|
75
|
+
hostId: hosts[0].id
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
// A custom domain: the host's own name, else the twin that forwards to it.
|
|
79
|
+
let match = null;
|
|
80
|
+
const byCname = (await findHosts('cname', name)).filter((host)=>{
|
|
81
|
+
var _host_cname;
|
|
82
|
+
return String((_host_cname = host.cname) != null ? _host_cname : '').trim().toLowerCase() === name;
|
|
83
|
+
});
|
|
84
|
+
if (byCname.length > 1) return {
|
|
85
|
+
served: false,
|
|
86
|
+
reason: 'ambiguous'
|
|
87
|
+
};
|
|
88
|
+
if (byCname.length === 1) match = {
|
|
89
|
+
host: byCname[0],
|
|
90
|
+
via: 'cname'
|
|
91
|
+
};
|
|
92
|
+
if (!match) {
|
|
93
|
+
const byTwin = (await findHosts('cnameTwin', name)).filter((host)=>{
|
|
94
|
+
var _host_cnameTwin;
|
|
95
|
+
return String((_host_cnameTwin = host.cnameTwin) != null ? _host_cnameTwin : '').trim().toLowerCase() === name;
|
|
96
|
+
});
|
|
97
|
+
if (byTwin.length > 1) return {
|
|
98
|
+
served: false,
|
|
99
|
+
reason: 'ambiguous'
|
|
100
|
+
};
|
|
101
|
+
if (byTwin.length === 1) match = {
|
|
102
|
+
host: byTwin[0],
|
|
103
|
+
via: 'twin'
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
if (!match) return {
|
|
107
|
+
served: false,
|
|
108
|
+
reason: 'no-host'
|
|
109
|
+
};
|
|
110
|
+
const primary = liveCustomDomain(match.host);
|
|
111
|
+
if (!primary) return {
|
|
112
|
+
served: false,
|
|
113
|
+
reason: 'not-live'
|
|
114
|
+
};
|
|
115
|
+
if (match.via === 'cname' && primary !== name) return {
|
|
116
|
+
served: false,
|
|
117
|
+
reason: 'not-live'
|
|
118
|
+
};
|
|
119
|
+
if (match.via === 'twin' && match.host.cnameTwinPending === true) return {
|
|
120
|
+
served: false,
|
|
121
|
+
reason: 'not-live'
|
|
122
|
+
};
|
|
123
|
+
const status = await domainStatus(name);
|
|
124
|
+
const conflicts = Array.isArray(status == null ? void 0 : status.conflicts) ? status.conflicts : [];
|
|
125
|
+
if ((status == null ? void 0 : status.state) !== 'serving' || conflicts.length > 0) return {
|
|
126
|
+
served: false,
|
|
127
|
+
reason: 'not-serving'
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
served: true,
|
|
131
|
+
via: match.via,
|
|
132
|
+
hostId: match.host.id
|
|
133
|
+
};
|
|
134
|
+
} catch (error) {
|
|
135
|
+
console.error('[platform-served-domain] could not decide; answering no', name, error);
|
|
136
|
+
return {
|
|
137
|
+
served: false,
|
|
138
|
+
reason: 'error'
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** {@link platformServedDomain} as a yes or no. */ export async function isPlatformServedDomain(hostname, deps = {}) {
|
|
143
|
+
return (await platformServedDomain(hostname, deps)).served;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
//# sourceMappingURL=platform-served-domain.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/platform-served-domain.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 { liveCustomDomain, TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport type { ProjectDomainStatus } from './domain-provider'\nimport firebaseAdmin from './firebase-admin'\nimport { PLATFORM_DOMAIN_PATTERN, MAX_DOMAIN_LENGTH } from './platform-domain-names'\nimport { projectDomainStatus } from './workspace-domains'\n\n/*==========================================\n * WHETHER THIS PLATFORM SERVES A HOSTNAME (AGL-4085).\n *\n * The question a caller asks before it hands a request a secret that only\n * our own edge may see: the site-import crawler's edge secret\n * (`site-import-edge.ts` in the AI plugin), which lifts the tenant's bot\n * challenge for AglynBot. A wrong \"yes\" sends that\n * secret to a stranger, so this answers from our own records and from the\n * hosting platform's live view, never from the shape of the name:\n *\n * - `{sub}.{TENANT_APEX}` is ours only when exactly one host carries that\n * `subdomain`. The apex's DNS is ours, so no one else can answer for it.\n * - Any other name is ours only when exactly one host carries it as its\n * `cname` (and `liveCustomDomain` says it serves: no attach or detach left\n * pending), or as its `cnameTwin` with the twin's redirect landed. That is\n * what the tenant's own `get-host.ts` resolves a request by.\n * - AND the hosting platform says, right now, that the name is attached to\n * the tenant deployment, verified, pointed at it with no foreign record\n * answering beside ours, and holding a certificate (`state: 'serving'`,\n * no `conflicts`). A customer's DNS was checked once, when they connected\n * the name; a name re-pointed since at a server of their own still reads\n * as live in Firestore, and only this read sees it.\n *\n * Every doubt is a \"no\": a query that fails, two hosts claiming one name, a\n * status the platform could not answer (`unknown`), a deployment with no\n * domain provider (`skipped`). A \"no\" costs only the challenge the crawler\n * met before this existed.\n *\n * What it cannot see: DNS that changes between this read and the request a\n * moment later. The secret that window could expose lifts the bot challenge\n * and nothing else (no sign-in, no lockdown, no rate limit), and the edge\n * rule asks for the AglynBot user agent as well.\n *=========================================*/\n\n/** The host fields a domain decision reads, and nothing else. */\nexport interface HostDomainRecord {\n id: string\n subdomain?: string | null\n cname?: string | null\n cnameTwin?: string | null\n cnameAttachmentPending?: boolean | null\n cnameDetachmentPending?: boolean | null\n cnameTwinPending?: boolean | null\n}\n\nexport type HostDomainField = 'subdomain' | 'cname' | 'cnameTwin'\n\nexport type PlatformServedVerdict =\n | { served: true; via: 'subdomain' | 'cname' | 'twin'; hostId: string }\n | {\n served: false\n reason:\n /** Not a hostname at all, or the tenant apex itself. */\n | 'not-a-hostname'\n /** No host carries the name. */\n | 'no-host'\n /** More than one host carries the name; connect-time uniqueness failed. */\n | 'ambiguous'\n /** A host carries it, but its attach, detach or twin never landed. */\n | 'not-live'\n /** The hosting platform does not say the name serves on our deployment now. */\n | 'not-serving'\n /** A read failed. */\n | 'error'\n }\n\nexport interface PlatformServedDeps {\n /** At most two hosts whose `field` equals `value`. */\n findHosts?: (field: HostDomainField, value: string) => Promise<HostDomainRecord[]>\n /** The hosting platform's live view of a name on the tenant deployment. */\n domainStatus?: (hostname: string) => Promise<ProjectDomainStatus>\n}\n\nconst HOST_DOMAIN_FIELDS = [\n 'subdomain',\n 'cname',\n 'cnameTwin',\n 'cnameAttachmentPending',\n 'cnameDetachmentPending',\n 'cnameTwinPending',\n] as const\n\nasync function findHostsInFirestore(field: HostDomainField, value: string): Promise<HostDomainRecord[]> {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .where(field, '==', value)\n .select(...HOST_DOMAIN_FIELDS)\n .limit(2)\n .get()\n return snapshot.docs.map((doc) => {\n const data = doc.data() as Omit<HostDomainRecord, 'id'>\n return { ...data, id: doc.id }\n })\n}\n\n/** A request's hostname, lowercased and without a trailing dot; null for anything else. */\nexport function normalizeServedHostname(input: string): string | null {\n const name = String(input ?? '').trim().toLowerCase().replace(/\\.+$/, '')\n if (!name || name.length > MAX_DOMAIN_LENGTH) return null\n if (!PLATFORM_DOMAIN_PATTERN.test(name)) return null\n return name\n}\n\n/** Whether a name serves on our deployment, and why not when it does not. Never throws. */\nexport async function platformServedDomain(\n hostname: string,\n deps: PlatformServedDeps = {},\n): Promise<PlatformServedVerdict> {\n const name = normalizeServedHostname(hostname)\n if (!name || name === TENANT_APEX) return { served: false, reason: 'not-a-hostname' }\n const findHosts = deps.findHosts ?? findHostsInFirestore\n const domainStatus = deps.domainStatus ?? ((host: string) => projectDomainStatus(host, { scope: 'tenant' }))\n\n try {\n // A platform subdomain: one label under the apex, held by exactly one host.\n if (name.endsWith(`.${TENANT_APEX}`)) {\n const sub = name.slice(0, -(TENANT_APEX.length + 1))\n if (!sub || sub.includes('.')) return { served: false, reason: 'no-host' }\n const hosts = (await findHosts('subdomain', sub)).filter((host) => host.subdomain === sub)\n if (hosts.length === 0) return { served: false, reason: 'no-host' }\n if (hosts.length > 1) return { served: false, reason: 'ambiguous' }\n return { served: true, via: 'subdomain', hostId: hosts[0].id }\n }\n\n // A custom domain: the host's own name, else the twin that forwards to it.\n let match: { host: HostDomainRecord; via: 'cname' | 'twin' } | null = null\n const byCname = (await findHosts('cname', name)).filter(\n (host) => String(host.cname ?? '').trim().toLowerCase() === name,\n )\n if (byCname.length > 1) return { served: false, reason: 'ambiguous' }\n if (byCname.length === 1) match = { host: byCname[0], via: 'cname' }\n if (!match) {\n const byTwin = (await findHosts('cnameTwin', name)).filter(\n (host) => String(host.cnameTwin ?? '').trim().toLowerCase() === name,\n )\n if (byTwin.length > 1) return { served: false, reason: 'ambiguous' }\n if (byTwin.length === 1) match = { host: byTwin[0], via: 'twin' }\n }\n if (!match) return { served: false, reason: 'no-host' }\n\n const primary = liveCustomDomain(match.host)\n if (!primary) return { served: false, reason: 'not-live' }\n if (match.via === 'cname' && primary !== name) return { served: false, reason: 'not-live' }\n if (match.via === 'twin' && match.host.cnameTwinPending === true) return { served: false, reason: 'not-live' }\n\n const status = await domainStatus(name)\n const conflicts = Array.isArray(status?.conflicts) ? status.conflicts : []\n if (status?.state !== 'serving' || conflicts.length > 0) return { served: false, reason: 'not-serving' }\n return { served: true, via: match.via, hostId: match.host.id }\n } catch (error) {\n console.error('[platform-served-domain] could not decide; answering no', name, error)\n return { served: false, reason: 'error' }\n }\n}\n\n/** {@link platformServedDomain} as a yes or no. */\nexport async function isPlatformServedDomain(hostname: string, deps: PlatformServedDeps = {}): Promise<boolean> {\n return (await platformServedDomain(hostname, deps)).served\n}\n"],"names":["liveCustomDomain","TENANT_APEX","firebaseAdmin","PLATFORM_DOMAIN_PATTERN","MAX_DOMAIN_LENGTH","projectDomainStatus","HOST_DOMAIN_FIELDS","findHostsInFirestore","field","value","snapshot","app","firestore","collection","where","select","limit","get","docs","map","doc","data","id","normalizeServedHostname","input","name","String","trim","toLowerCase","replace","length","test","platformServedDomain","hostname","deps","served","reason","findHosts","domainStatus","host","scope","endsWith","sub","slice","includes","hosts","filter","subdomain","via","hostId","match","byCname","cname","byTwin","cnameTwin","primary","cnameTwinPending","status","conflicts","Array","isArray","state","error","console","isPlatformServedDomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,WAAW,QAAQ,qCAAoC;AAElF,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,6BAAyB;AACpF,SAASC,mBAAmB,QAAQ,yBAAqB;AA2EzD,MAAMC,qBAAqB;IACzB;IACA;IACA;IACA;IACA;IACA;CACD;AAED,eAAeC,qBAAqBC,KAAsB,EAAEC,KAAa;IACvE,MAAMC,WAAW,MAAMR,cACpBS,GAAG,GACHC,SAAS,G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X,IAAI;QAC3C,IAAI,CAACgB,SAAS,OAAO;YAAEpB,QAAQ;YAAOC,QAAQ;QAAW;QACzD,IAAIc,MAAMF,GAAG,KAAK,WAAWO,YAAY9B,MAAM,OAAO;YAAEU,QAAQ;YAAOC,QAAQ;QAAW;QAC1F,IAAIc,MAAMF,GAAG,KAAK,UAAUE,MAAMX,IAAI,CAACiB,gBAAgB,KAAK,MAAM,OAAO;YAAErB,QAAQ;YAAOC,QAAQ;QAAW;QAE7G,MAAMqB,SAAS,MAAMnB,aAAab;QAClC,MAAMiC,YAAYC,MAAMC,OAAO,CAACH,0BAAAA,OAAQC,SAAS,IAAID,OAAOC,SAAS,GAAG,EAAE;QAC1E,IAAID,CAAAA,0BAAAA,OAAQI,KAAK,MAAK,aAAaH,UAAU5B,MAAM,GAAG,GAAG,OAAO;YAAEK,QAAQ;YAAOC,QAAQ;QAAc;QACvG,OAAO;YAAED,QAAQ;YAAMa,KAAKE,MAAMF,GAAG;YAAEC,QAAQC,MAAMX,IAAI,CAACjB,EAAE;QAAC;IAC/D,EAAE,OAAOwC,OAAO;QACdC,QAAQD,KAAK,CAAC,2DAA2DrC,MAAMqC;QAC/E,OAAO;YAAE3B,QAAQ;YAAOC,QAAQ;QAAQ;IAC1C;AACF;AAEA,iDAAiD,GACjD,OAAO,eAAe4B,uBAAuB/B,QAAgB,EAAEC,OAA2B,CAAC,CAAC;IAC1F,OAAO,AAAC,CAAA,MAAMF,qBAAqBC,UAAUC,KAAI,EAAGC,MAAM;AAC5D"}
|
|
@@ -0,0 +1,42 @@
|
|
|
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
|
+
export type SitePreviewTokenKind = 'enter' | 'cookie';
|
|
18
|
+
export interface SitePreviewClaims {
|
|
19
|
+
hostId: string;
|
|
20
|
+
/** Expiry, epoch ms. */
|
|
21
|
+
exp: number;
|
|
22
|
+
}
|
|
23
|
+
export interface MintedSitePreviewToken {
|
|
24
|
+
token: string;
|
|
25
|
+
expiresAtMs: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Mints a token of the given kind for a site the caller has ALREADY decided
|
|
29
|
+
* the person may see. The mint checks nothing.
|
|
30
|
+
*/
|
|
31
|
+
export declare function mintSitePreviewToken(kind: SitePreviewTokenKind, hostId: string, nowMs?: number): MintedSitePreviewToken;
|
|
32
|
+
/**
|
|
33
|
+
* Verifies a token AS the stated kind, FOR the stated site. `null` for
|
|
34
|
+
* anything else: expired, tampered, malformed, another version, another kind,
|
|
35
|
+
* another site, or a deploy with no signing secret (fail closed).
|
|
36
|
+
*
|
|
37
|
+
* An expiry further out than the kind allows is refused too, so a token
|
|
38
|
+
* minted under a longer TTL by an older build cannot outlive this one's.
|
|
39
|
+
*/
|
|
40
|
+
export declare function verifySitePreviewToken(kind: SitePreviewTokenKind, token: unknown, hostId: string, nowMs?: number): SitePreviewClaims | null;
|
|
41
|
+
/** The value of one cookie in a `Cookie` header, or `undefined`. */
|
|
42
|
+
export declare function readCookieValue(cookieHeader: string | null | undefined, name: string): string | undefined;
|
|
@@ -0,0 +1,123 @@
|
|
|
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 { createHmac } from "crypto";
|
|
17
|
+
import { SITE_PREVIEW_COOKIE_TTL_MS, SITE_PREVIEW_ENTER_TTL_MS } from "@aglyn/aglyn/app-utils/site-preview";
|
|
18
|
+
import { tokenSigningSecret } from "./media-signing.js";
|
|
19
|
+
import { safeEqual } from "./safe-equal.js";
|
|
20
|
+
/**
|
|
21
|
+
* A capability to see ONE site that is in preview (AGL-4086).
|
|
22
|
+
*
|
|
23
|
+
* On `*.aglyn.app` the site knows a console user by the `aglyn_edit_hint`
|
|
24
|
+
* cookie the sign-in bounce plants on the tenant apex. A CUSTOM domain is
|
|
25
|
+
* cross-site with every console cookie, so there the console mints an enter
|
|
26
|
+
* link instead: `https://{domain}/api/site-preview/enter?blob=…`. The tenant
|
|
27
|
+
* verifies the blob, plants an HttpOnly cookie on that host alone, and every
|
|
28
|
+
* request after that is verified again before the site renders.
|
|
29
|
+
*
|
|
30
|
+
* ## Two kinds, deliberately non-interchangeable
|
|
31
|
+
*
|
|
32
|
+
* - `enter` rides the URL once. URLs are logged and shared, so it lives
|
|
33
|
+
* {@link SITE_PREVIEW_ENTER_TTL_MS} — long enough for one click.
|
|
34
|
+
* - `cookie` is the planted value, living {@link SITE_PREVIEW_COOKIE_TTL_MS}.
|
|
35
|
+
*
|
|
36
|
+
* The kind is inside the signed context, so a leaked enter URL can never be
|
|
37
|
+
* replayed as a 12-hour cookie, and a stolen cookie value cannot be pasted
|
|
38
|
+
* into an enter link to plant itself on a second browser.
|
|
39
|
+
*
|
|
40
|
+
* ## What the signature is over
|
|
41
|
+
*
|
|
42
|
+
* `site-preview:{kind}:{payload}`, where the payload carries the `hostId` and
|
|
43
|
+
* `exp`. The tenant compares the `hostId` with the site the REQUEST resolved
|
|
44
|
+
* to, never with anything the URL says, so a token for one site opens no
|
|
45
|
+
* other. The `site-preview:` prefix separates it from the media, edit-hint
|
|
46
|
+
* and collection-preview signatures that share `TOKEN_SIGNING_SECRET`.
|
|
47
|
+
*
|
|
48
|
+
* ## What it is not
|
|
49
|
+
*
|
|
50
|
+
* It names a site and a time, not a person, and buys nothing but "render this
|
|
51
|
+
* site as its team sees it". The person was checked when the console minted
|
|
52
|
+
* the enter link (`siteViewRefusal`), and the 12 hours bound how long that
|
|
53
|
+
* check is trusted.
|
|
54
|
+
*/ /** Version tag, mirroring the edit-hint token's. */ const TOKEN_PREFIX = 'aglyn-site-preview-v1';
|
|
55
|
+
function signPayload(kind, payloadB64) {
|
|
56
|
+
return createHmac('sha256', tokenSigningSecret()).update(`site-preview:${kind}:${payloadB64}`).digest('base64url');
|
|
57
|
+
}
|
|
58
|
+
function ttlOf(kind) {
|
|
59
|
+
return kind === 'enter' ? SITE_PREVIEW_ENTER_TTL_MS : SITE_PREVIEW_COOKIE_TTL_MS;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Mints a token of the given kind for a site the caller has ALREADY decided
|
|
63
|
+
* the person may see. The mint checks nothing.
|
|
64
|
+
*/ export function mintSitePreviewToken(kind, hostId, nowMs = Date.now()) {
|
|
65
|
+
if (!hostId) throw new Error('hostId is required');
|
|
66
|
+
const exp = nowMs + ttlOf(kind);
|
|
67
|
+
const claims = {
|
|
68
|
+
hostId,
|
|
69
|
+
exp
|
|
70
|
+
};
|
|
71
|
+
const payload = Buffer.from(JSON.stringify(claims), 'utf8').toString('base64url');
|
|
72
|
+
return {
|
|
73
|
+
token: `${TOKEN_PREFIX}.${payload}.${signPayload(kind, payload)}`,
|
|
74
|
+
expiresAtMs: exp
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Verifies a token AS the stated kind, FOR the stated site. `null` for
|
|
79
|
+
* anything else: expired, tampered, malformed, another version, another kind,
|
|
80
|
+
* another site, or a deploy with no signing secret (fail closed).
|
|
81
|
+
*
|
|
82
|
+
* An expiry further out than the kind allows is refused too, so a token
|
|
83
|
+
* minted under a longer TTL by an older build cannot outlive this one's.
|
|
84
|
+
*/ export function verifySitePreviewToken(kind, token, hostId, nowMs = Date.now()) {
|
|
85
|
+
if (!hostId) return null;
|
|
86
|
+
if (typeof token !== 'string' || token.length === 0 || token.length > 2048) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const parts = token.split('.');
|
|
90
|
+
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null;
|
|
91
|
+
const [, payload, sig] = parts;
|
|
92
|
+
let expected;
|
|
93
|
+
try {
|
|
94
|
+
expected = signPayload(kind, payload);
|
|
95
|
+
} catch (unused) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
if (!safeEqual(sig, expected)) return null;
|
|
99
|
+
let claims;
|
|
100
|
+
try {
|
|
101
|
+
claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
|
102
|
+
} catch (unused) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
const exp = Number(claims == null ? void 0 : claims.exp);
|
|
106
|
+
if (!Number.isFinite(exp) || exp <= nowMs) return null;
|
|
107
|
+
if (exp - nowMs > ttlOf(kind)) return null;
|
|
108
|
+
if (typeof claims.hostId !== 'string' || claims.hostId !== hostId) return null;
|
|
109
|
+
return {
|
|
110
|
+
hostId: claims.hostId,
|
|
111
|
+
exp
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** The value of one cookie in a `Cookie` header, or `undefined`. */ export function readCookieValue(cookieHeader, name) {
|
|
115
|
+
if (!cookieHeader) return undefined;
|
|
116
|
+
for (const part of cookieHeader.split(';')){
|
|
117
|
+
const trimmed = part.trim();
|
|
118
|
+
if (trimmed.startsWith(`${name}=`)) return trimmed.slice(name.length + 1);
|
|
119
|
+
}
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
//# sourceMappingURL=site-preview-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-preview-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 {\n SITE_PREVIEW_COOKIE_TTL_MS,\n SITE_PREVIEW_ENTER_TTL_MS,\n} from '@aglyn/aglyn/app-utils/site-preview'\nimport { tokenSigningSecret } from './media-signing'\nimport { safeEqual } from './safe-equal'\n\n/**\n * A capability to see ONE site that is in preview (AGL-4086).\n *\n * On `*.aglyn.app` the site knows a console user by the `aglyn_edit_hint`\n * cookie the sign-in bounce plants on the tenant apex. A CUSTOM domain is\n * cross-site with every console cookie, so there the console mints an enter\n * link instead: `https://{domain}/api/site-preview/enter?blob=…`. The tenant\n * verifies the blob, plants an HttpOnly cookie on that host alone, and every\n * request after that is verified again before the site renders.\n *\n * ## Two kinds, deliberately non-interchangeable\n *\n * - `enter` rides the URL once. URLs are logged and shared, so it lives\n * {@link SITE_PREVIEW_ENTER_TTL_MS} — long enough for one click.\n * - `cookie` is the planted value, living {@link SITE_PREVIEW_COOKIE_TTL_MS}.\n *\n * The kind is inside the signed context, so a leaked enter URL can never be\n * replayed as a 12-hour cookie, and a stolen cookie value cannot be pasted\n * into an enter link to plant itself on a second browser.\n *\n * ## What the signature is over\n *\n * `site-preview:{kind}:{payload}`, where the payload carries the `hostId` and\n * `exp`. The tenant compares the `hostId` with the site the REQUEST resolved\n * to, never with anything the URL says, so a token for one site opens no\n * other. The `site-preview:` prefix separates it from the media, edit-hint\n * and collection-preview signatures that share `TOKEN_SIGNING_SECRET`.\n *\n * ## What it is not\n *\n * It names a site and a time, not a person, and buys nothing but \"render this\n * site as its team sees it\". The person was checked when the console minted\n * the enter link (`siteViewRefusal`), and the 12 hours bound how long that\n * check is trusted.\n */\n\n/** Version tag, mirroring the edit-hint token's. */\nconst TOKEN_PREFIX = 'aglyn-site-preview-v1'\n\nexport type SitePreviewTokenKind = 'enter' | 'cookie'\n\nexport interface SitePreviewClaims {\n hostId: string\n /** Expiry, epoch ms. */\n exp: number\n}\n\nexport interface MintedSitePreviewToken {\n token: string\n expiresAtMs: number\n}\n\nfunction signPayload(kind: SitePreviewTokenKind, payloadB64: string): string {\n return createHmac('sha256', tokenSigningSecret())\n .update(`site-preview:${kind}:${payloadB64}`)\n .digest('base64url')\n}\n\nfunction ttlOf(kind: SitePreviewTokenKind): number {\n return kind === 'enter' ? SITE_PREVIEW_ENTER_TTL_MS : SITE_PREVIEW_COOKIE_TTL_MS\n}\n\n/**\n * Mints a token of the given kind for a site the caller has ALREADY decided\n * the person may see. The mint checks nothing.\n */\nexport function mintSitePreviewToken(\n kind: SitePreviewTokenKind,\n hostId: string,\n nowMs: number = Date.now(),\n): MintedSitePreviewToken {\n if (!hostId) throw new Error('hostId is required')\n const exp = nowMs + ttlOf(kind)\n const claims: SitePreviewClaims = { hostId, 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 token AS the stated kind, FOR the stated site. `null` for\n * anything else: expired, tampered, malformed, another version, another kind,\n * another site, or a deploy with no signing secret (fail closed).\n *\n * An expiry further out than the kind allows is refused too, so a token\n * minted under a longer TTL by an older build cannot outlive this one's.\n */\nexport function verifySitePreviewToken(\n kind: SitePreviewTokenKind,\n token: unknown,\n hostId: string,\n nowMs: number = Date.now(),\n): SitePreviewClaims | null {\n if (!hostId) return null\n if (typeof token !== 'string' || token.length === 0 || token.length > 2048) {\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 return null\n }\n if (!safeEqual(sig, expected)) return null\n let claims: SitePreviewClaims\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 (exp - nowMs > ttlOf(kind)) return null\n if (typeof claims.hostId !== 'string' || claims.hostId !== hostId) return null\n return { hostId: claims.hostId, exp }\n}\n\n/** The value of one cookie in a `Cookie` header, or `undefined`. */\nexport function readCookieValue(\n cookieHeader: string | null | undefined,\n name: string,\n): string | undefined {\n if (!cookieHeader) return undefined\n for (const part of cookieHeader.split(';')) {\n const trimmed = part.trim()\n if (trimmed.startsWith(`${name}=`)) return trimmed.slice(name.length + 1)\n }\n return undefined\n}\n"],"names":["createHmac","SITE_PREVIEW_COOKIE_TTL_MS","SITE_PREVIEW_ENTER_TTL_MS","tokenSigningSecret","safeEqual","TOKEN_PREFIX","signPayload","kind","payloadB64","update","digest","ttlOf","mintSitePreviewToken","hostId","nowMs","Date","now","Error","exp","claims","payload","Buffer","from","JSON","stringify","toString","token","expiresAtMs","verifySitePreviewToken","length","parts","split","sig","expected","parse","Number","isFinite","readCookieValue","cookieHeader","name","undefined","part","trimmed","trim","startsWith","slice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SACEC,0BAA0B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I,GAAGF;IACzB,IAAIG;IACJ,IAAI;QACFA,WAAW3B,YAAYC,MAAMa;IAC/B,EAAE,eAAM;QACN,OAAO;IACT;IACA,IAAI,CAAChB,UAAU4B,KAAKC,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,IAAII,MAAMJ,QAAQH,MAAMJ,OAAO,OAAO;IACtC,IAAI,OAAOY,OAAON,MAAM,KAAK,YAAYM,OAAON,MAAM,KAAKA,QAAQ,OAAO;IAC1E,OAAO;QAAEA,QAAQM,OAAON,MAAM;QAAEK;IAAI;AACtC;AAEA,kEAAkE,GAClE,OAAO,SAASmB,gBACdC,YAAuC,EACvCC,IAAY;IAEZ,IAAI,CAACD,cAAc,OAAOE;IAC1B,KAAK,MAAMC,QAAQH,aAAaP,KAAK,CAAC,KAAM;QAC1C,MAAMW,UAAUD,KAAKE,IAAI;QACzB,IAAID,QAAQE,UAAU,CAAC,GAAGL,KAAK,CAAC,CAAC,GAAG,OAAOG,QAAQG,KAAK,CAACN,KAAKV,MAAM,GAAG;IACzE;IACA,OAAOW;AACT"}
|
|
@@ -0,0 +1,88 @@
|
|
|
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 { DocumentSnapshot, Firestore } from 'firebase-admin/firestore';
|
|
18
|
+
import { findUserByUidAcrossPools } from './auth-pools';
|
|
19
|
+
/**
|
|
20
|
+
* Who may see a site, or a page, that is in preview (AGL-4086).
|
|
21
|
+
*
|
|
22
|
+
* The site's TEAM: anyone the console lets open the site. That is the same
|
|
23
|
+
* question the host document's read rule answers — a role on this site in its
|
|
24
|
+
* `memberRoles` — widened by the roster for the two members that projection
|
|
25
|
+
* can miss: a workspace owner or admin, and a member who holds every site of
|
|
26
|
+
* the workspace. A collaborator scoped to OTHER sites of the workspace is not
|
|
27
|
+
* this site's team, and does not see it.
|
|
28
|
+
*
|
|
29
|
+
* And Aglyn STAFF, by the `staff` custom claim on the account. That claim is
|
|
30
|
+
* set only through the Admin SDK, so nothing a client can write reaches it.
|
|
31
|
+
*
|
|
32
|
+
* NOT the site's own member accounts — the visitors who signed up on the
|
|
33
|
+
* site. They are an audience, not the team, and they are in another account
|
|
34
|
+
* pool besides.
|
|
35
|
+
*
|
|
36
|
+
* Read intent, not write: seeing a site is not editing it, so a role that can
|
|
37
|
+
* only view the site in the console sees its preview too. Lockdown is not
|
|
38
|
+
* asked here because it outranks preview where it is enforced — the
|
|
39
|
+
* middleware's verdict and the loader's lockdown branch both run first, for
|
|
40
|
+
* the team as for everyone.
|
|
41
|
+
*/
|
|
42
|
+
export type SiteViewRefusal = 'not-team';
|
|
43
|
+
/**
|
|
44
|
+
* `null` when `uid` may see this site in preview, or why not. The caller has
|
|
45
|
+
* already proved WHO the uid is (a verified ID token at the console, a signed
|
|
46
|
+
* hint at the tenant) and whether the account is staff.
|
|
47
|
+
*/
|
|
48
|
+
export declare function siteViewRefusal(options: {
|
|
49
|
+
firestore: Firestore;
|
|
50
|
+
/** The `hosts/{hostId}` snapshot, already confirmed to exist. */
|
|
51
|
+
host: DocumentSnapshot;
|
|
52
|
+
uid: string;
|
|
53
|
+
/** From verified claims or the auth record; never from a request body. */
|
|
54
|
+
staff?: boolean;
|
|
55
|
+
}): Promise<SiteViewRefusal | null>;
|
|
56
|
+
/** How a team member was recognized on the site, or that they were not. */
|
|
57
|
+
export interface SitePreviewViewer {
|
|
58
|
+
admitted: boolean;
|
|
59
|
+
via: 'cookie' | 'hint' | null;
|
|
60
|
+
}
|
|
61
|
+
export interface SitePreviewViewerDeps {
|
|
62
|
+
findUser?: typeof findUserByUidAcrossPools;
|
|
63
|
+
nowMs?: number;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Is the person behind this request the site's team? (AGL-4086)
|
|
67
|
+
*
|
|
68
|
+
* The middleware routed the request here because one of two cookies was
|
|
69
|
+
* PRESENT; this is where either is believed or not.
|
|
70
|
+
*
|
|
71
|
+
* 1. `aglyn_site_preview` — planted by a console-minted enter link on this
|
|
72
|
+
* host alone. A signed token bound to the site; verified against the site
|
|
73
|
+
* the request resolved to.
|
|
74
|
+
* 2. `aglyn_edit_hint` — the console sign-in's hint on the tenant apex. It
|
|
75
|
+
* names a uid and nothing more, so the account is looked up (it must exist
|
|
76
|
+
* and be enabled, which is how a sign-out the cookie cannot hear about
|
|
77
|
+
* still ends it) and then asked {@link siteViewRefusal}, with the staff
|
|
78
|
+
* claim read off the account record.
|
|
79
|
+
*
|
|
80
|
+
* Anything else — no cookie, a forged or expired one, one for another site, a
|
|
81
|
+
* uid with no role here — is refused, and the caller renders what the public
|
|
82
|
+
* gets. Never throws: a lookup that fails is a refusal.
|
|
83
|
+
*/
|
|
84
|
+
export declare function verifySitePreviewViewer(options: {
|
|
85
|
+
firestore: Firestore;
|
|
86
|
+
hostId: string;
|
|
87
|
+
cookieHeader: string | null | undefined;
|
|
88
|
+
}, deps?: SitePreviewViewerDeps): Promise<SitePreviewViewer>;
|
|
@@ -0,0 +1,103 @@
|
|
|
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 { hostRoleFor, isOrgWideMember } from "@aglyn/aglyn/server";
|
|
17
|
+
import { SITE_PREVIEW_COOKIE, SITE_PREVIEW_EDIT_HINT_COOKIE } from "@aglyn/aglyn/app-utils/site-preview";
|
|
18
|
+
import { findUserByUidAcrossPools } from "./auth-pools.js";
|
|
19
|
+
import { verifyEditHintToken } from "./edit-hint-token.js";
|
|
20
|
+
import { readCookieValue, verifySitePreviewToken } from "./site-preview-token.js";
|
|
21
|
+
import { claimsHoldStaff } from "./staff-seat.js";
|
|
22
|
+
/**
|
|
23
|
+
* `null` when `uid` may see this site in preview, or why not. The caller has
|
|
24
|
+
* already proved WHO the uid is (a verified ID token at the console, a signed
|
|
25
|
+
* hint at the tenant) and whether the account is staff.
|
|
26
|
+
*/ export async function siteViewRefusal(options) {
|
|
27
|
+
var _host_get, _membership_data;
|
|
28
|
+
const { firestore, host, uid, staff = false } = options;
|
|
29
|
+
if (staff) return null;
|
|
30
|
+
if (!uid) return 'not-team';
|
|
31
|
+
const memberRoles = (_host_get = host.get('memberRoles')) != null ? _host_get : {};
|
|
32
|
+
if (memberRoles && memberRoles[uid] != null) return null;
|
|
33
|
+
const orgId = host.get('orgId');
|
|
34
|
+
if (!orgId) return 'not-team';
|
|
35
|
+
const membership = await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get();
|
|
36
|
+
if (!membership.exists) return 'not-team';
|
|
37
|
+
const member = (_membership_data = membership.data()) != null ? _membership_data : {};
|
|
38
|
+
if (isOrgWideMember(member) || hostRoleFor(member, host.id) !== null) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return 'not-team';
|
|
42
|
+
}
|
|
43
|
+
const REFUSED = {
|
|
44
|
+
admitted: false,
|
|
45
|
+
via: null
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Is the person behind this request the site's team? (AGL-4086)
|
|
49
|
+
*
|
|
50
|
+
* The middleware routed the request here because one of two cookies was
|
|
51
|
+
* PRESENT; this is where either is believed or not.
|
|
52
|
+
*
|
|
53
|
+
* 1. `aglyn_site_preview` — planted by a console-minted enter link on this
|
|
54
|
+
* host alone. A signed token bound to the site; verified against the site
|
|
55
|
+
* the request resolved to.
|
|
56
|
+
* 2. `aglyn_edit_hint` — the console sign-in's hint on the tenant apex. It
|
|
57
|
+
* names a uid and nothing more, so the account is looked up (it must exist
|
|
58
|
+
* and be enabled, which is how a sign-out the cookie cannot hear about
|
|
59
|
+
* still ends it) and then asked {@link siteViewRefusal}, with the staff
|
|
60
|
+
* claim read off the account record.
|
|
61
|
+
*
|
|
62
|
+
* Anything else — no cookie, a forged or expired one, one for another site, a
|
|
63
|
+
* uid with no role here — is refused, and the caller renders what the public
|
|
64
|
+
* gets. Never throws: a lookup that fails is a refusal.
|
|
65
|
+
*/ export async function verifySitePreviewViewer(options, deps = {}) {
|
|
66
|
+
var _deps_nowMs;
|
|
67
|
+
const { firestore, hostId, cookieHeader } = options;
|
|
68
|
+
if (!hostId) return REFUSED;
|
|
69
|
+
const nowMs = (_deps_nowMs = deps.nowMs) != null ? _deps_nowMs : Date.now();
|
|
70
|
+
const previewCookie = readCookieValue(cookieHeader, SITE_PREVIEW_COOKIE);
|
|
71
|
+
if (previewCookie && verifySitePreviewToken('cookie', previewCookie, hostId, nowMs)) {
|
|
72
|
+
return {
|
|
73
|
+
admitted: true,
|
|
74
|
+
via: 'cookie'
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const hint = readCookieValue(cookieHeader, SITE_PREVIEW_EDIT_HINT_COOKIE);
|
|
78
|
+
const claims = hint ? verifyEditHintToken('cookie', hint, nowMs) : null;
|
|
79
|
+
if (!claims) return REFUSED;
|
|
80
|
+
try {
|
|
81
|
+
var _deps_findUser;
|
|
82
|
+
const findUser = (_deps_findUser = deps.findUser) != null ? _deps_findUser : findUserByUidAcrossPools;
|
|
83
|
+
const found = await findUser(claims.uid);
|
|
84
|
+
if (!found || found.record.disabled) return REFUSED;
|
|
85
|
+
const host = await firestore.collection('hosts').doc(hostId).get();
|
|
86
|
+
if (!host.exists) return REFUSED;
|
|
87
|
+
const refusal = await siteViewRefusal({
|
|
88
|
+
firestore,
|
|
89
|
+
host,
|
|
90
|
+
uid: claims.uid,
|
|
91
|
+
staff: claimsHoldStaff(found.record)
|
|
92
|
+
});
|
|
93
|
+
return refusal ? REFUSED : {
|
|
94
|
+
admitted: true,
|
|
95
|
+
via: 'hint'
|
|
96
|
+
};
|
|
97
|
+
} catch (error) {
|
|
98
|
+
console.error('[site-preview] viewer check failed', error);
|
|
99
|
+
return REFUSED;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
//# sourceMappingURL=site-view-authz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-view-authz.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 {\n type AglynOrgMember,\n hostRoleFor,\n isOrgWideMember,\n} from '@aglyn/aglyn/server'\nimport {\n SITE_PREVIEW_COOKIE,\n SITE_PREVIEW_EDIT_HINT_COOKIE,\n} from '@aglyn/aglyn/app-utils/site-preview'\nimport type { DocumentSnapshot, Firestore } from 'firebase-admin/firestore'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { verifyEditHintToken } from './edit-hint-token'\nimport { readCookieValue, verifySitePreviewToken } from './site-preview-token'\nimport { claimsHoldStaff } from './staff-seat'\n\n/**\n * Who may see a site, or a page, that is in preview (AGL-4086).\n *\n * The site's TEAM: anyone the console lets open the site. That is the same\n * question the host document's read rule answers — a role on this site in its\n * `memberRoles` — widened by the roster for the two members that projection\n * can miss: a workspace owner or admin, and a member who holds every site of\n * the workspace. A collaborator scoped to OTHER sites of the workspace is not\n * this site's team, and does not see it.\n *\n * And Aglyn STAFF, by the `staff` custom claim on the account. That claim is\n * set only through the Admin SDK, so nothing a client can write reaches it.\n *\n * NOT the site's own member accounts — the visitors who signed up on the\n * site. They are an audience, not the team, and they are in another account\n * pool besides.\n *\n * Read intent, not write: seeing a site is not editing it, so a role that can\n * only view the site in the console sees its preview too. Lockdown is not\n * asked here because it outranks preview where it is enforced — the\n * middleware's verdict and the loader's lockdown branch both run first, for\n * the team as for everyone.\n */\n\nexport type SiteViewRefusal = 'not-team'\n\n/**\n * `null` when `uid` may see this site in preview, or why not. The caller has\n * already proved WHO the uid is (a verified ID token at the console, a signed\n * hint at the tenant) and whether the account is staff.\n */\nexport async function siteViewRefusal(options: {\n firestore: Firestore\n /** The `hosts/{hostId}` snapshot, already confirmed to exist. */\n host: DocumentSnapshot\n uid: string\n /** From verified claims or the auth record; never from a request body. */\n staff?: boolean\n}): Promise<SiteViewRefusal | null> {\n const { firestore, host, uid, staff = false } = options\n if (staff) return null\n if (!uid) return 'not-team'\n const memberRoles = (host.get('memberRoles') ?? {}) as Record<string, unknown>\n if (memberRoles && memberRoles[uid] != null) return null\n const orgId = host.get('orgId') as string | undefined\n if (!orgId) return 'not-team'\n const membership = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(uid)\n .get()\n if (!membership.exists) return 'not-team'\n const member = (membership.data() ?? {}) as Partial<AglynOrgMember>\n if (isOrgWideMember(member) || hostRoleFor(member, host.id) !== null) {\n return null\n }\n return 'not-team'\n}\n\n/** How a team member was recognized on the site, or that they were not. */\nexport interface SitePreviewViewer {\n admitted: boolean\n via: 'cookie' | 'hint' | null\n}\n\nexport interface SitePreviewViewerDeps {\n findUser?: typeof findUserByUidAcrossPools\n nowMs?: number\n}\n\nconst REFUSED: SitePreviewViewer = { admitted: false, via: null }\n\n/**\n * Is the person behind this request the site's team? (AGL-4086)\n *\n * The middleware routed the request here because one of two cookies was\n * PRESENT; this is where either is believed or not.\n *\n * 1. `aglyn_site_preview` — planted by a console-minted enter link on this\n * host alone. A signed token bound to the site; verified against the site\n * the request resolved to.\n * 2. `aglyn_edit_hint` — the console sign-in's hint on the tenant apex. It\n * names a uid and nothing more, so the account is looked up (it must exist\n * and be enabled, which is how a sign-out the cookie cannot hear about\n * still ends it) and then asked {@link siteViewRefusal}, with the staff\n * claim read off the account record.\n *\n * Anything else — no cookie, a forged or expired one, one for another site, a\n * uid with no role here — is refused, and the caller renders what the public\n * gets. Never throws: a lookup that fails is a refusal.\n */\nexport async function verifySitePreviewViewer(\n options: {\n firestore: Firestore\n hostId: string\n cookieHeader: string | null | undefined\n },\n deps: SitePreviewViewerDeps = {},\n): Promise<SitePreviewViewer> {\n const { firestore, hostId, cookieHeader } = options\n if (!hostId) return REFUSED\n const nowMs = deps.nowMs ?? Date.now()\n\n const previewCookie = readCookieValue(cookieHeader, SITE_PREVIEW_COOKIE)\n if (\n previewCookie &&\n verifySitePreviewToken('cookie', previewCookie, hostId, nowMs)\n ) {\n return { admitted: true, via: 'cookie' }\n }\n\n const hint = readCookieValue(cookieHeader, SITE_PREVIEW_EDIT_HINT_COOKIE)\n const claims = hint ? verifyEditHintToken('cookie', hint, nowMs) : null\n if (!claims) return REFUSED\n try {\n const findUser = deps.findUser ?? findUserByUidAcrossPools\n const found = await findUser(claims.uid)\n if (!found || found.record.disabled) return REFUSED\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return REFUSED\n const refusal = await siteViewRefusal({\n firestore,\n host,\n uid: claims.uid,\n staff: claimsHoldStaff(found.record),\n })\n return refusal ? REFUSED : { admitted: true, via: 'hint' }\n } catch (error) {\n console.error('[site-preview] viewer check failed', error)\n return REFUSED\n }\n}\n"],"names":["hostRoleFor","isOrgWideMember","SITE_PREVIEW_COOKIE","SITE_PREVIEW_EDIT_HINT_COOKIE","findUserByUidAcrossPools","verifyEditHintToken","readCookieValue","verifySitePreviewToken","claimsHoldStaff","siteViewRefusal","options","host","membership","firestore","uid","staff","memberRoles","get","orgId","collection","doc","exists","member","data","id","REFUSED","admitted","via","verifySitePreviewViewer","deps","hostId","cookieHeader","nowMs","Date","now","previewCookie","hint","claims","findUser","found","record","disabled","refusal","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,WAAW,EACXC,eAAe,QACV,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,6BAA6B,QACxB,sCAAqC;AAE5C,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SAASC,eAAe,EAAEC,sBAAsB,QAAQ,0BAAsB;AAC9E,SAASC,eAAe,QAAQ,kBAAc;AA4B9C;;;;CAIC,GACD,OAAO,eAAeC,gBAAgBC,OAOrC;QAIsBC,WAWLC;IAdhB,MAAM,EAAEC,SAAS,EAAEF,IAAI,EAAEG,GAAG,EAAEC,QAAQ,KAAK,EAAE,GAAGL;IAChD,IAAIK,OAAO,OAAO;IAClB,IAAI,CAACD,KAAK,OAAO;IACjB,MAAME,e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