@fabrika/auth-core 0.3.3 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/app-environment.ts +44 -0
- package/src/canonical-path.ts +66 -0
- package/src/contract-canonical.ts +189 -0
- package/src/contract.ts +504 -0
- package/src/endpoint-digest.ts +141 -0
- package/src/endpoints.ts +292 -0
- package/src/framework-variables.ts +114 -0
- package/src/index.ts +14 -1
- package/src/installation-endpoint.ts +61 -0
- package/src/locale.ts +35 -0
- package/src/mail.ts +198 -0
- package/src/membership.ts +384 -0
- package/src/oauth.ts +50 -0
- package/src/path-segment.ts +9 -0
- package/src/requirement.ts +58 -0
- package/src/rpc.ts +22 -8
- package/src/sha256.ts +125 -0
- package/src/token.ts +255 -9
- package/src/types.ts +123 -43
- package/src/wire.ts +48 -0
- package/src/gates.ts +0 -29
package/src/mail.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// An application's wording of IAM's e-mails: per message and language, a subject, a plain-text body and optionally an
|
|
2
|
+
// HTML body, with `{{name}}` placeholders from a closed set. IAM fills them, escapes every value and puts in the action
|
|
3
|
+
// link; without an HTML body it builds the HTML part itself. The HTML body is a closed subset (`mailHtmlTokens`): text
|
|
4
|
+
// structure only, and a link only to `{{actionUrl}}`, `{{appUrl}}` or a `mailto:` address. The contract build, the
|
|
5
|
+
// static reader, IAM's schema parser and IAM's renderer all apply `mailTemplateProblems`.
|
|
6
|
+
|
|
7
|
+
import type { Locale } from './locale'
|
|
8
|
+
|
|
9
|
+
export const MESSAGE_KINDS = ['invitation', 'enrollment', 'reset'] as const
|
|
10
|
+
|
|
11
|
+
export type MessageKind = (typeof MESSAGE_KINDS)[number]
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The placeholders each message fills. `companyLabel` and `message` are empty until an invitation carries them.
|
|
15
|
+
* `appUrl` is the application's address, its first registered return origin: IAM sends a template that names it only
|
|
16
|
+
* while one is registered, and its own wording otherwise.
|
|
17
|
+
*/
|
|
18
|
+
export const MAIL_PLACEHOLDERS = {
|
|
19
|
+
invitation: ['displayName', 'recipient', 'inviterLabel', 'companyLabel', 'message', 'actionUrl', 'appUrl', 'expiry'],
|
|
20
|
+
enrollment: ['displayName', 'recipient', 'actionUrl', 'appUrl', 'expiry'],
|
|
21
|
+
reset: ['displayName', 'recipient', 'actionUrl', 'appUrl', 'expiry'],
|
|
22
|
+
} as const satisfies { readonly [K in MessageKind]: readonly string[] }
|
|
23
|
+
|
|
24
|
+
export type MailPlaceholder<K extends MessageKind> = (typeof MAIL_PLACEHOLDERS)[K][number]
|
|
25
|
+
|
|
26
|
+
/** One message in one language: the subject line, the plain-text body and, optionally, the HTML body. */
|
|
27
|
+
export interface MailTemplate {
|
|
28
|
+
readonly subject: string
|
|
29
|
+
readonly text: string
|
|
30
|
+
/** A body in the closed HTML subset of `mailHtmlTokens`; absent, IAM builds the HTML part from `text`. */
|
|
31
|
+
readonly html?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The contract's `mail`: the templates it declares, by message and language. A missing one is IAM's default. */
|
|
35
|
+
export type MailTemplates = { readonly [K in MessageKind]?: { readonly [L in Locale]?: MailTemplate } }
|
|
36
|
+
|
|
37
|
+
export const MAX_MAIL_SUBJECT_LENGTH = 200
|
|
38
|
+
export const MAX_MAIL_TEXT_BYTES = 8 * 1024
|
|
39
|
+
export const MAX_MAIL_HTML_BYTES = 16 * 1024
|
|
40
|
+
|
|
41
|
+
const PLACEHOLDER = /\{\{([^{}]*)\}\}/g
|
|
42
|
+
|
|
43
|
+
export function isMessageKind(value: string): value is MessageKind {
|
|
44
|
+
return MESSAGE_KINDS.some((kind) => kind === value)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Why `template` cannot be the `kind` message, one line each; empty when it can. */
|
|
48
|
+
export function mailTemplateProblems(kind: MessageKind, template: MailTemplate): string[] {
|
|
49
|
+
const problems: string[] = []
|
|
50
|
+
const { subject, text } = template
|
|
51
|
+
if (subject.replaceAll(PLACEHOLDER, '').trim() === '') problems.push('the subject has no words of its own: a value may be empty')
|
|
52
|
+
if (Array.from(subject).length > MAX_MAIL_SUBJECT_LENGTH) problems.push(`the subject is longer than ${MAX_MAIL_SUBJECT_LENGTH} characters`)
|
|
53
|
+
if (/\p{Cc}/u.test(subject)) problems.push('the subject is not one line: it contains a line break or a control character')
|
|
54
|
+
if (new TextEncoder().encode(text).length > MAX_MAIL_TEXT_BYTES) problems.push(`the text is longer than ${MAX_MAIL_TEXT_BYTES} bytes`)
|
|
55
|
+
problems.push(...placeholderProblems(kind, 'the subject', subject), ...placeholderProblems(kind, 'the text', text))
|
|
56
|
+
if (subject.includes('{{actionUrl}}')) problems.push('the subject names {{actionUrl}}: the one-time link belongs in the text, never in a header')
|
|
57
|
+
if (!text.includes('{{actionUrl}}')) problems.push('the text has no {{actionUrl}}: IAM puts the one-time link there')
|
|
58
|
+
if (template.html !== undefined) problems.push(...htmlProblems(kind, template.html))
|
|
59
|
+
return problems
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function htmlProblems(kind: MessageKind, html: string): string[] {
|
|
63
|
+
if (new TextEncoder().encode(html).length > MAX_MAIL_HTML_BYTES) return [`the HTML is longer than ${MAX_MAIL_HTML_BYTES} bytes`]
|
|
64
|
+
const parsed = mailHtmlTokens(html)
|
|
65
|
+
const problems = [...placeholderProblems(kind, 'the HTML', html), ...(parsed.ok ? [] : parsed.problems)]
|
|
66
|
+
if (parsed.ok && !parsed.tokens.some((token) => token.kind === 'open' && token.href === ACTION_URL)) {
|
|
67
|
+
problems.push('the HTML has no <a href="{{actionUrl}}">: IAM puts the one-time link there')
|
|
68
|
+
}
|
|
69
|
+
return problems
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The elements an HTML body may use: text structure, a list, a quote and a link. Nothing loads, runs or submits. */
|
|
73
|
+
export const MAIL_HTML_ELEMENTS = [
|
|
74
|
+
'a',
|
|
75
|
+
'b',
|
|
76
|
+
'blockquote',
|
|
77
|
+
'br',
|
|
78
|
+
'div',
|
|
79
|
+
'em',
|
|
80
|
+
'h1',
|
|
81
|
+
'h2',
|
|
82
|
+
'h3',
|
|
83
|
+
'hr',
|
|
84
|
+
'i',
|
|
85
|
+
'li',
|
|
86
|
+
'ol',
|
|
87
|
+
'p',
|
|
88
|
+
'span',
|
|
89
|
+
'strong',
|
|
90
|
+
'u',
|
|
91
|
+
'ul',
|
|
92
|
+
] as const
|
|
93
|
+
|
|
94
|
+
const VOID_ELEMENTS: readonly string[] = ['br', 'hr']
|
|
95
|
+
const ACTION_URL = '{{actionUrl}}'
|
|
96
|
+
const APP_URL = '{{appUrl}}'
|
|
97
|
+
const MAILTO = /^mailto:[^\s"'<>{}&]+$/
|
|
98
|
+
const CHARACTER_REFERENCE = /^&(?:[A-Za-z][A-Za-z0-9]{1,31}|#[0-9]{1,7}|#x[0-9A-Fa-f]{1,6});/
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* One piece of an HTML body: literal text (placeholders included, character references as written), an element that
|
|
102
|
+
* opens (with a link's `href`, verbatim), or one that closes. IAM renders the body from these, never from its source.
|
|
103
|
+
*/
|
|
104
|
+
export type MailHtmlToken =
|
|
105
|
+
| { readonly kind: 'text'; readonly text: string }
|
|
106
|
+
| { readonly kind: 'open'; readonly name: string; readonly href: string | null }
|
|
107
|
+
| { readonly kind: 'close'; readonly name: string }
|
|
108
|
+
|
|
109
|
+
interface RefusedHtml {
|
|
110
|
+
readonly ok: false
|
|
111
|
+
readonly problems: string[]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* An HTML body read by a small tokenizer that admits only `MAIL_HTML_ELEMENTS`, in lower case, balanced, with no
|
|
116
|
+
* attribute but a link's double-quoted `href` to `{{actionUrl}}`, `{{appUrl}}` or a `mailto:` address, no comment and
|
|
117
|
+
* no `&` that starts no character reference. So no script, style, form, frame, event handler, image, remote resource
|
|
118
|
+
* or `javascript:`/`data:` URL can be written, and a value IAM inserts is text.
|
|
119
|
+
*/
|
|
120
|
+
export function mailHtmlTokens(html: string): { readonly ok: true; readonly tokens: MailHtmlToken[] } | RefusedHtml {
|
|
121
|
+
const tokens: MailHtmlToken[] = []
|
|
122
|
+
const open: string[] = []
|
|
123
|
+
const refuse = (problem: string): RefusedHtml => ({ ok: false, problems: [problem] })
|
|
124
|
+
let at = 0
|
|
125
|
+
while (at < html.length) {
|
|
126
|
+
const tag = html.indexOf('<', at)
|
|
127
|
+
const end = tag === -1 ? html.length : tag
|
|
128
|
+
if (end > at) {
|
|
129
|
+
const text = html.slice(at, end)
|
|
130
|
+
for (let amp = text.indexOf('&'); amp !== -1; amp = text.indexOf('&', amp + 1)) {
|
|
131
|
+
if (!CHARACTER_REFERENCE.test(text.slice(amp))) return refuse('the HTML has an & that starts no character reference: write &')
|
|
132
|
+
}
|
|
133
|
+
tokens.push({ kind: 'text', text })
|
|
134
|
+
}
|
|
135
|
+
if (tag === -1) break
|
|
136
|
+
if (html.startsWith('<!--', tag)) return refuse('the HTML has a comment: an e-mail body has none')
|
|
137
|
+
const close = html.indexOf('>', tag)
|
|
138
|
+
if (close === -1) return refuse('the HTML has a < that ends no element: write <')
|
|
139
|
+
const source = html.slice(tag + 1, close)
|
|
140
|
+
const closing = /^\/([a-z0-9]+)\s*$/.exec(source)
|
|
141
|
+
if (closing !== null) {
|
|
142
|
+
const name = closing[1] ?? ''
|
|
143
|
+
if (open.at(-1) !== name) return refuse(`the HTML closes </${name}> where ${open.length === 0 ? 'nothing' : `<${open.at(-1)}>`} is open`)
|
|
144
|
+
open.pop()
|
|
145
|
+
tokens.push({ kind: 'close', name })
|
|
146
|
+
at = close + 1
|
|
147
|
+
continue
|
|
148
|
+
}
|
|
149
|
+
const opening = /^([a-z0-9]+)((?:\s+[^\s=]+="[^"]*")*)\s*(\/?)$/.exec(source)
|
|
150
|
+
const name = opening?.[1]
|
|
151
|
+
if (opening === null || name === undefined) {
|
|
152
|
+
return refuse(`the HTML has <${source.slice(0, 40)}>, which is no element of the subset (attributes are double-quoted)`)
|
|
153
|
+
}
|
|
154
|
+
if (!MAIL_HTML_ELEMENTS.some((element) => element === name)) {
|
|
155
|
+
return refuse(
|
|
156
|
+
`the HTML has <${name}>, which an e-mail body may not use (allowed: ${MAIL_HTML_ELEMENTS.map((element) => `<${element}>`).join(', ')})`,
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
let href: string | null = null
|
|
160
|
+
for (const [, attribute = '', value = ''] of (opening[2] ?? '').matchAll(/([^\s=]+)="([^"]*)"/g)) {
|
|
161
|
+
if (name !== 'a' || attribute !== 'href' || href !== null) {
|
|
162
|
+
return refuse(`the HTML gives <${name}> the attribute ${attribute.slice(0, 40)}: only a link's href is allowed`)
|
|
163
|
+
}
|
|
164
|
+
if (value !== ACTION_URL && value !== APP_URL && !MAILTO.test(value)) {
|
|
165
|
+
return refuse('the HTML links somewhere else: a link goes only to {{actionUrl}}, {{appUrl}} or a mailto: address')
|
|
166
|
+
}
|
|
167
|
+
href = value
|
|
168
|
+
}
|
|
169
|
+
const isVoid = VOID_ELEMENTS.includes(name)
|
|
170
|
+
if (opening[3] === '/' && !isVoid) return refuse(`the HTML closes <${name}/> in its own tag: write <${name}></${name}>`)
|
|
171
|
+
if (name === 'a' && href === null) return refuse('the HTML has an <a> without href')
|
|
172
|
+
if (name === 'a' && open.includes('a')) return refuse('the HTML has a link inside a link')
|
|
173
|
+
if (!isVoid) open.push(name)
|
|
174
|
+
tokens.push({ kind: 'open', name, href })
|
|
175
|
+
at = close + 1
|
|
176
|
+
}
|
|
177
|
+
if (open.length > 0) return refuse(`the HTML leaves <${open.at(-1)}> open`)
|
|
178
|
+
return { ok: true, tokens }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function placeholderProblems(kind: MessageKind, part: string, value: string): string[] {
|
|
182
|
+
const allowed: readonly string[] = MAIL_PLACEHOLDERS[kind]
|
|
183
|
+
const problems: string[] = []
|
|
184
|
+
for (const [, name = ''] of value.matchAll(PLACEHOLDER)) {
|
|
185
|
+
if (!allowed.includes(name)) {
|
|
186
|
+
problems.push(
|
|
187
|
+
`${part} names {{${name.slice(0, 40)}}}, which the ${kind} message does not fill (allowed: ${allowed.map((key) => `{{${key}}}`).join(', ')})`,
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (value.replaceAll(PLACEHOLDER, '').includes('{{')) problems.push(`${part} has a {{ that opens no placeholder`)
|
|
192
|
+
return problems
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** `template` with each placeholder replaced by its value; a name without a value becomes empty. */
|
|
196
|
+
export function fillMailTemplate(template: string, values: Readonly<Record<string, string>>): string {
|
|
197
|
+
return template.replaceAll(PLACEHOLDER, (_, name: string) => values[name] ?? '')
|
|
198
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// The IAM operations a multi-tenant application requests on its caller's behalf (ADR-0012 §6): scope
|
|
2
|
+
// creation, membership and share links. IAM evaluates every request against the caller's LIVE permissions, generates every value and issues every key; the application supplies the
|
|
3
|
+
// caller's token as proof and nothing that names an actor.
|
|
4
|
+
//
|
|
5
|
+
// A SEPARATE interface from `IamRpc`, like `IamHandoffRpc`: an application's IAM entrypoint serves it,
|
|
6
|
+
// and a platform component that implements `IamRpc` does not have to.
|
|
7
|
+
|
|
8
|
+
import type { ContractArtifact, DimensionArtifact, EndpointRow } from './contract'
|
|
9
|
+
import type { PrincipalAffiliation, Scope } from './types'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What an endpoint may ask IAM about the members of its own target (`ctx.members`): `manage` where its action is the
|
|
13
|
+
* dimension's `members.manage`, `list` where it is the dimension's `members.list`, on or in that dimension. IAM checks
|
|
14
|
+
* the same action live, so the endpoint's own access already names what IAM requires.
|
|
15
|
+
*/
|
|
16
|
+
export function endpointMembers(artifact: Pick<ContractArtifact, 'dimensions'>, row: EndpointRow): 'manage' | 'list' | null {
|
|
17
|
+
if (row.requirement?.kind !== 'action') {
|
|
18
|
+
return null
|
|
19
|
+
}
|
|
20
|
+
const { action, access } = row.requirement
|
|
21
|
+
if (access.form !== 'on' && access.form !== 'in') {
|
|
22
|
+
return null
|
|
23
|
+
}
|
|
24
|
+
const members = Object.hasOwn(artifact.dimensions, access.dimension) ? artifact.dimensions[access.dimension]?.members : null
|
|
25
|
+
return members?.manage === action ? 'manage' : members?.list === action ? 'list' : null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The member directory an endpoint reads through `ctx.members` when it does not manage members: the nearest dimension,
|
|
30
|
+
* its own or one containing it, that declares members. Every such endpoint (access `on` or `in`) may look up one member
|
|
31
|
+
* it names; `lists` where its action is that dimension's `members.list`, which alone may list them. IAM checks either
|
|
32
|
+
* action live on the directory's value itself.
|
|
33
|
+
*/
|
|
34
|
+
export interface EndpointDirectory {
|
|
35
|
+
readonly dimension: string
|
|
36
|
+
readonly lists: boolean
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The directory reach an endpoint's access form gives it, from the dimensions alone: what `buildArtifact` records in
|
|
41
|
+
* `ContractArtifact.directories`. Nothing else derives it, so an approved artifact holds every reach the runtime grants.
|
|
42
|
+
*/
|
|
43
|
+
export function directoryReach(dimensions: ContractArtifact['dimensions'], row: EndpointRow): EndpointDirectory | null {
|
|
44
|
+
// Only a procedure of an RPC mount has a handler with `ctx.members`: a file endpoint and an export have none.
|
|
45
|
+
const procedure = (row.kind === 'query' || row.kind === 'mutation') && row.source.kind === 'mount'
|
|
46
|
+
if (!procedure || row.requirement?.kind !== 'action' || endpointMembers({ dimensions }, row) === 'manage') {
|
|
47
|
+
return null
|
|
48
|
+
}
|
|
49
|
+
const { action, access } = row.requirement
|
|
50
|
+
// A link procedure (`from: null`) acts for an anonymous key holder, which IAM never answers a membership question.
|
|
51
|
+
if ((access.form !== 'on' && access.form !== 'in') || access.from === null) {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
const seen = new Set<string>()
|
|
55
|
+
let dimension: string | null = access.dimension
|
|
56
|
+
while (dimension !== null && !seen.has(dimension) && Object.hasOwn(dimensions, dimension)) {
|
|
57
|
+
seen.add(dimension)
|
|
58
|
+
const definition: DimensionArtifact | undefined = dimensions[dimension]
|
|
59
|
+
if (definition === undefined) {
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
if (definition.members !== null) {
|
|
63
|
+
return { dimension, lists: definition.members.list === action }
|
|
64
|
+
}
|
|
65
|
+
dimension = definition.in
|
|
66
|
+
}
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The directory reach the artifact records for the endpoint; an artifact compiled before it recorded any grants none. */
|
|
71
|
+
export function endpointDirectory(artifact: Pick<ContractArtifact, 'directories'>, row: EndpointRow): EndpointDirectory | null {
|
|
72
|
+
const directories = artifact.directories
|
|
73
|
+
return directories !== undefined && Object.hasOwn(directories, row.id) ? (directories[row.id] ?? null) : null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The actions of the endpoints whose directory is `dimension`, sorted: what IAM's schema holds as the dimension's
|
|
78
|
+
* `lookups`, so IAM answers a lookup only for an action an approved endpoint below the dimension holds.
|
|
79
|
+
*/
|
|
80
|
+
export function directoryLookups(artifact: Pick<ContractArtifact, 'directories' | 'endpoints'>, dimension: string): string[] {
|
|
81
|
+
const actions = new Set<string>()
|
|
82
|
+
for (const row of artifact.endpoints) {
|
|
83
|
+
if (row.requirement?.kind === 'action' && endpointDirectory(artifact, row)?.dimension === dimension) {
|
|
84
|
+
actions.add(row.requirement.action)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return [...actions].sort()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Whether an endpoint reads the application's own directory (`ctx.members.list()` of `listAppMembers`): a procedure of
|
|
92
|
+
* an RPC mount whose access is `app` and whose action is the application's `members.list`, which IAM checks live.
|
|
93
|
+
*/
|
|
94
|
+
export function endpointAppDirectory(artifact: Pick<ContractArtifact, 'members'>, row: EndpointRow): boolean {
|
|
95
|
+
const procedure = (row.kind === 'query' || row.kind === 'mutation') && row.source.kind === 'mount'
|
|
96
|
+
return procedure && row.requirement?.kind === 'action' && row.requirement.access.form === 'app' && artifact.members !== undefined
|
|
97
|
+
&& row.requirement.action === artifact.members.list
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Every request carries the caller's own credential; `app` is superseded by the credential's verified app. */
|
|
101
|
+
export interface MembershipCaller {
|
|
102
|
+
app: string
|
|
103
|
+
/** The caller's verified access token, or a `px_` key bound to a user principal. */
|
|
104
|
+
credential: string | null
|
|
105
|
+
requestId: string
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Why IAM refused. `not_allowed` is a lack of authority; `invalid_delegation` a missing, spent or
|
|
110
|
+
* mismatched delegation grant; `invalid_request` a request the app's schema cannot express, with a
|
|
111
|
+
* message naming the problem.
|
|
112
|
+
*/
|
|
113
|
+
export type MembershipFailure =
|
|
114
|
+
| { ok: false; reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' | 'invalid_delegation' | 'not_found' }
|
|
115
|
+
/** Revoking would leave the value without a holder of its creator role. */
|
|
116
|
+
| { ok: false; reason: 'last_creator' }
|
|
117
|
+
/** The installation sends no email, so it cannot verify an invited address. */
|
|
118
|
+
| { ok: false; reason: 'invitations_disabled' | 'delivery_failed' }
|
|
119
|
+
/**
|
|
120
|
+
* An invitation to a role declared external for an address the organization names (a bootstrap admin, or one the
|
|
121
|
+
* OIDC allowlist names by address or domain): IAM never creates such a mailbox as an external person (ADR-0051).
|
|
122
|
+
*/
|
|
123
|
+
| { ok: false; reason: 'internal_mailbox' }
|
|
124
|
+
| { ok: false; reason: 'invalid_request'; message: string }
|
|
125
|
+
|
|
126
|
+
export type MembershipFailureReason = MembershipFailure['reason']
|
|
127
|
+
|
|
128
|
+
/** The longest scope type or value a membership operation takes; a lookup of a longer principal id finds no member. */
|
|
129
|
+
export const MAX_MEMBERSHIP_SCOPE_PART_LENGTH = 200
|
|
130
|
+
|
|
131
|
+
/** The most values a share link's chain names: its object and each value containing it. */
|
|
132
|
+
export const MAX_LINK_CHAIN_LENGTH = 8
|
|
133
|
+
|
|
134
|
+
/** The longest address IAM invites, after `normalizeEmailIdentity`. */
|
|
135
|
+
export const MAX_INVITATION_EMAIL_LENGTH = 254
|
|
136
|
+
|
|
137
|
+
/** Why IAM refuses `scope` as a membership operation's coordinate, or `null`. */
|
|
138
|
+
export function membershipScopeProblem(scope: Scope): string | null {
|
|
139
|
+
for (const part of [scope.type, scope.value]) {
|
|
140
|
+
if (part === '' || part.length > MAX_MEMBERSHIP_SCOPE_PART_LENGTH) {
|
|
141
|
+
return `a scope type and value are 1 to ${MAX_MEMBERSHIP_SCOPE_PART_LENGTH} characters`
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Normalize an email identity for case-insensitive exact-mailbox comparisons. */
|
|
148
|
+
export function normalizeEmailIdentity(value: string): string {
|
|
149
|
+
return value.normalize('NFC').trim().toLocaleLowerCase('en-US')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A mailbox as IAM stores it: a trimmed, lower-cased address. It never normalizes again: NFC before lower-casing is not
|
|
154
|
+
* idempotent (`J\u030C` stores as `j\u030C`, which NFC would compose to `\u01F0`), so a second pass would refuse a
|
|
155
|
+
* stored mailbox.
|
|
156
|
+
*/
|
|
157
|
+
export function isNormalizedMailbox(value: string): boolean {
|
|
158
|
+
return value === value.trim().toLocaleLowerCase('en-US') && /^[^\s@]+@[^\s@]+$/.test(value)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The normalized address IAM invites for `address`, or `null` for one it refuses as no address. */
|
|
162
|
+
export function invitedAddress(address: string): string | null {
|
|
163
|
+
const email = normalizeEmailIdentity(address)
|
|
164
|
+
return email.length > MAX_INVITATION_EMAIL_LENGTH || !/^[^\s@]+@[^\s@]+$/.test(email) ? null : email
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The longest company label an invitation carries: display text the inviting application names. */
|
|
168
|
+
export const MAX_INVITATION_LABEL_LENGTH = 200
|
|
169
|
+
|
|
170
|
+
/** The longest personal message an invitation carries. */
|
|
171
|
+
export const MAX_INVITATION_MESSAGE_LENGTH = 1000
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* What an invitation by address carries besides its role. `label` is the invited person's company as the application
|
|
175
|
+
* names it, `message` the inviter's personal note; both are plain text IAM escapes wherever it inserts them. `resend`
|
|
176
|
+
* rotates the open invitation's link, restarts its lifetime and sends it again; without it, repeating an invitation
|
|
177
|
+
* answers the open one and sends nothing.
|
|
178
|
+
*/
|
|
179
|
+
export interface InvitationOptions {
|
|
180
|
+
readonly label?: string
|
|
181
|
+
readonly message?: string
|
|
182
|
+
readonly resend?: boolean
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Why IAM refuses an invitation's label or message, or `null`. A message may break lines; nothing else is a control character. */
|
|
186
|
+
export function invitationOptionsProblem(options: InvitationOptions): string | null {
|
|
187
|
+
const { label, message } = options
|
|
188
|
+
if (label !== undefined && (label.length > MAX_INVITATION_LABEL_LENGTH || /\p{Cc}/u.test(label))) {
|
|
189
|
+
return `an invitation label is at most ${MAX_INVITATION_LABEL_LENGTH} characters on one line`
|
|
190
|
+
}
|
|
191
|
+
if (message !== undefined && (message.length > MAX_INVITATION_MESSAGE_LENGTH || /[^\P{Cc}\n\r\t]/u.test(message))) {
|
|
192
|
+
return `an invitation message is at most ${MAX_INVITATION_MESSAGE_LENGTH} characters of plain text`
|
|
193
|
+
}
|
|
194
|
+
return null
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** How long a delegation grant may be held before it is spent. One request, so seconds. */
|
|
198
|
+
export const DELEGATION_GRANT_TTL_SECONDS = 120
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Obtain a single-use delegation grant for ONE request to one endpoint. The endpoint must be one the
|
|
202
|
+
* app's schema lists under `delegations`, and the grant is spent by one membership operation of the same
|
|
203
|
+
* caller and request id.
|
|
204
|
+
*/
|
|
205
|
+
export interface RequestDelegationInput extends MembershipCaller {
|
|
206
|
+
endpoint: string
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export type RequestDelegationResult = { ok: true; grant: string; expiresAt: number } | MembershipFailure
|
|
210
|
+
|
|
211
|
+
/** Create a value of `dimension`: IAM generates it and grants the caller the dimension's creator role, atomically. */
|
|
212
|
+
export interface CreateScopeInput extends MembershipCaller {
|
|
213
|
+
/** A grant for an endpoint whose purpose is `creates` for this dimension. */
|
|
214
|
+
delegation: string
|
|
215
|
+
dimension: string
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export type CreateScopeResult = { ok: true; scope: Scope; role: string } | MembershipFailure
|
|
219
|
+
|
|
220
|
+
/** Who a membership operation is about: an existing principal, or an address IAM invites. */
|
|
221
|
+
export type MemberTarget = { principalId: string } | { email: string }
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Give `role` in `scope`. The caller holds the dimension's `members.manage` there, holds a role there
|
|
225
|
+
* that may assign `role`, and holds every action `role` grants there. An existing principal receives the
|
|
226
|
+
* grant; an address receives an invitation that only its verified owner can accept, and for a role declared
|
|
227
|
+
* external that IAM creates as an external principal at acceptance when no principal holds it. Repeating the
|
|
228
|
+
* call answers the same result.
|
|
229
|
+
*/
|
|
230
|
+
export interface AssignMemberInput extends MembershipCaller {
|
|
231
|
+
/** A grant for an endpoint whose purpose is `members` for `scope.type`. */
|
|
232
|
+
delegation: string
|
|
233
|
+
scope: Scope
|
|
234
|
+
role: string
|
|
235
|
+
member: MemberTarget
|
|
236
|
+
/** Only with an address: the invitation's label, message and resend (`InvitationOptions`). */
|
|
237
|
+
invitation?: InvitationOptions
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export type AssignMemberResult =
|
|
241
|
+
| { ok: true; assigned: { principalId: string; role: string } }
|
|
242
|
+
| { ok: true; invited: { invitationId: string; role: string; expiresAt: number } }
|
|
243
|
+
| MembershipFailure
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Remove a principal's membership roles in `scope` (only `role` when given), or cancel an invitation.
|
|
247
|
+
* Each removed role must be one the caller could assign; the last holder of the creator role stays.
|
|
248
|
+
* Repeating the call answers the same result.
|
|
249
|
+
*/
|
|
250
|
+
export interface RevokeMemberInput extends MembershipCaller {
|
|
251
|
+
delegation: string
|
|
252
|
+
scope: Scope
|
|
253
|
+
member: { principalId: string; role?: string | null } | { invitationId: string }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export type RevokeMemberResult = { ok: true } | MembershipFailure
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The members of `scope`, with their labels. Needs the dimension's `members.list` there; emails, last sign-ins and
|
|
260
|
+
* invitations only to `members.manage`.
|
|
261
|
+
*/
|
|
262
|
+
export interface ListMembersInput extends MembershipCaller {
|
|
263
|
+
scope: Scope
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export interface MemberItem {
|
|
267
|
+
principalId: string
|
|
268
|
+
/** The principal's display label (a user's spelling of its address); null from an IAM that shows it only to `members.manage`. */
|
|
269
|
+
label: string | null
|
|
270
|
+
/** Null unless the caller holds the dimension's `members.manage` in the scope. */
|
|
271
|
+
email: string | null
|
|
272
|
+
/**
|
|
273
|
+
* When the member last signed in to the application (unix seconds): null for one that never did, and unless the caller
|
|
274
|
+
* holds the dimension's `members.manage` in the scope, since it is personal data like the address.
|
|
275
|
+
*/
|
|
276
|
+
lastSignInAt: number | null
|
|
277
|
+
roles: string[]
|
|
278
|
+
disabled: boolean
|
|
279
|
+
/** An `external` member is a person from outside the organization (ADR-0051). */
|
|
280
|
+
affiliation: PrincipalAffiliation
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface InvitationItem {
|
|
284
|
+
id: string
|
|
285
|
+
email: string
|
|
286
|
+
role: string
|
|
287
|
+
expiresAt: number
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export type ListMembersResult = { ok: true; members: MemberItem[]; invitations: InvitationItem[] } | MembershipFailure
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Look up ONE principal in the members of `scope`, for an endpoint on, in or below its dimension. `action` is the
|
|
294
|
+
* endpoint's own: IAM answers only when the schema lists it among the dimension's `lookups` and the caller holds it on
|
|
295
|
+
* `scope` itself, so the application names no chain IAM would have to trust. Listing stays with `members.list`.
|
|
296
|
+
*/
|
|
297
|
+
export interface FindMemberInput extends MembershipCaller {
|
|
298
|
+
scope: Scope
|
|
299
|
+
principalId: string
|
|
300
|
+
action: string
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export interface FoundMember {
|
|
304
|
+
principalId: string
|
|
305
|
+
/** The principal's display label; null unless the dimension declares `directory: 'labels'` or the caller holds `members.manage` there. */
|
|
306
|
+
label: string | null
|
|
307
|
+
disabled: boolean
|
|
308
|
+
affiliation: PrincipalAffiliation
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** `member` is null for a principal that holds no membership role in `scope`, unknown ones included. */
|
|
312
|
+
export type FindMemberResult = { ok: true; member: FoundMember | null } | MembershipFailure
|
|
313
|
+
|
|
314
|
+
/** The most members one page of an application's directory answers. */
|
|
315
|
+
export const MAX_APP_MEMBERS_PAGE = 100
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* One page of the application's own people (`AppSchema.members`): every principal holding a role of the application,
|
|
319
|
+
* globally or in a value. Needs the application's `members.list` held globally; labels by the same rule as a value's
|
|
320
|
+
* directory, emails and last sign-ins only to its `members.manage` held globally. Pages run by principal id: `after`
|
|
321
|
+
* is the previous page's `next`.
|
|
322
|
+
*/
|
|
323
|
+
export interface ListAppMembersInput extends MembershipCaller {
|
|
324
|
+
after?: string
|
|
325
|
+
/** 1 to `MAX_APP_MEMBERS_PAGE`; absent, the most. */
|
|
326
|
+
limit?: number
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** One role a principal holds at the application: globally (`scope: null`), or in one value. */
|
|
330
|
+
export interface AppMemberRole {
|
|
331
|
+
role: string
|
|
332
|
+
scope: Scope | null
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export interface AppMemberItem {
|
|
336
|
+
principalId: string
|
|
337
|
+
/** The principal's display label; null unless the application declares `directory: 'labels'` or the caller manages its people. */
|
|
338
|
+
label: string | null
|
|
339
|
+
/** Null unless the caller holds the application's `members.manage` globally. */
|
|
340
|
+
email: string | null
|
|
341
|
+
/** As `MemberItem.lastSignInAt`, to a holder of the application's `members.manage` only. */
|
|
342
|
+
lastSignInAt: number | null
|
|
343
|
+
/** Sorted by role, then scope; a global grant first. */
|
|
344
|
+
roles: AppMemberRole[]
|
|
345
|
+
disabled: boolean
|
|
346
|
+
affiliation: PrincipalAffiliation
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** `next` is the `after` of the following page, null on the last one. */
|
|
350
|
+
export type ListAppMembersResult = { ok: true; members: AppMemberItem[]; next: string | null } | MembershipFailure
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Issue a share link of `mount` for the object `chain[0]`. `chain` names the object and every value
|
|
354
|
+
* containing it, outward, as the app resolved it from its database; the framework re-checks it on every
|
|
355
|
+
* link request, so a link whose object moved stops working. The caller holds the mount's `issuedBy` and
|
|
356
|
+
* every granted action on some link of the chain.
|
|
357
|
+
*/
|
|
358
|
+
export interface IssueLinkInput extends MembershipCaller {
|
|
359
|
+
mount: string
|
|
360
|
+
chain: Scope[]
|
|
361
|
+
/** Required, at most the mount's `maxDays`. */
|
|
362
|
+
days: number
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
export type IssueLinkResult = { ok: true; key: string; id: string; expiresAt: number } | MembershipFailure
|
|
366
|
+
|
|
367
|
+
/** Revoke a share link: its issuer, or a holder of `members.manage` on a value of its chain. Idempotent. */
|
|
368
|
+
export interface RevokeLinkInput extends MembershipCaller {
|
|
369
|
+
id: string
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export type RevokeLinkResult = { ok: true } | MembershipFailure
|
|
373
|
+
|
|
374
|
+
export interface IamMembershipRpc {
|
|
375
|
+
requestDelegation(input: RequestDelegationInput): Promise<RequestDelegationResult>
|
|
376
|
+
createScope(input: CreateScopeInput): Promise<CreateScopeResult>
|
|
377
|
+
assignMember(input: AssignMemberInput): Promise<AssignMemberResult>
|
|
378
|
+
revokeMember(input: RevokeMemberInput): Promise<RevokeMemberResult>
|
|
379
|
+
listMembers(input: ListMembersInput): Promise<ListMembersResult>
|
|
380
|
+
listAppMembers(input: ListAppMembersInput): Promise<ListAppMembersResult>
|
|
381
|
+
findMember(input: FindMemberInput): Promise<FindMemberResult>
|
|
382
|
+
issueLink(input: IssueLinkInput): Promise<IssueLinkResult>
|
|
383
|
+
revokeLink(input: RevokeLinkInput): Promise<RevokeLinkResult>
|
|
384
|
+
}
|
package/src/oauth.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** OAuth 2.1 primitives shared by IAM (issuer), the proxy (enforcement) and resource servers (verification). */
|
|
2
|
+
|
|
3
|
+
/** RFC 8707 resources are byte-exact; plain HTTP is reserved for loopback development. */
|
|
4
|
+
export function isOAuthResourceUri(value: unknown): value is string {
|
|
5
|
+
if (!isUriText(value)) return false
|
|
6
|
+
try {
|
|
7
|
+
const url = new URL(value)
|
|
8
|
+
const local = url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname === '127.0.0.1' || url.hostname === '[::1]'
|
|
9
|
+
return (url.protocol === 'https:' || (url.protocol === 'http:' && local)) && !uriAuthority(value).includes('@') && !value.includes('#')
|
|
10
|
+
} catch {
|
|
11
|
+
return false
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Client ID Metadata Document identifier: HTTPS, explicit path, no userinfo, fragment or dot segments. */
|
|
16
|
+
export function isCimdClientId(value: unknown): value is string {
|
|
17
|
+
if (!isUriText(value) || value.includes('#') || uriAuthority(value).includes('@')) return false
|
|
18
|
+
try {
|
|
19
|
+
const url = new URL(value)
|
|
20
|
+
const authorityAndPath = value.slice(value.indexOf('://') + 3).split(/[?#]/)[0] ?? ''
|
|
21
|
+
const pathStart = authorityAndPath.indexOf('/')
|
|
22
|
+
if (url.protocol !== 'https:' || pathStart === -1) return false
|
|
23
|
+
const segments = authorityAndPath.slice(pathStart).split('/').map((segment) => segment.replace(/%2e/gi, '.'))
|
|
24
|
+
return !segments.some((segment) => segment === '.' || segment === '..')
|
|
25
|
+
} catch {
|
|
26
|
+
return false
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** RFC 6749 scope-token syntax; duplicates and empty sets are refused. */
|
|
31
|
+
export function parseOAuthScopes(value: unknown): string[] | null {
|
|
32
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > 64) return null
|
|
33
|
+
const scopes: string[] = []
|
|
34
|
+
for (const item of value) {
|
|
35
|
+
if (typeof item !== 'string' || item.length === 0 || item.length > 200 || !/^[\x21\x23-\x5b\x5d-\x7e]+$/.test(item) || scopes.includes(item)) {
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
scopes.push(item)
|
|
39
|
+
}
|
|
40
|
+
return scopes
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isUriText(value: unknown): value is string {
|
|
44
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 2048 && !/[\s\\<>"{}|^`]/.test(value)
|
|
45
|
+
&& !/%(?![A-Fa-f0-9]{2})/.test(value) && /^https?:\/\/[^/?#]+(?:[/?#]|$)/i.test(value)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function uriAuthority(value: string): string {
|
|
49
|
+
return value.split('://')[1]?.split(/[/?#]/)[0] ?? ''
|
|
50
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const PARAMETER_SEGMENT = /^:([A-Za-z_][A-Za-z0-9_]*)$/
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The name of a `:name` path segment, or null for any other segment. Every endpoint table, an application's and an
|
|
5
|
+
* installation service's, reads a parameter by this rule: it matches exactly one non-empty segment.
|
|
6
|
+
*/
|
|
7
|
+
export function parameterName(segment: string): string | null {
|
|
8
|
+
return PARAMETER_SEGMENT.exec(segment)?.[1] ?? null
|
|
9
|
+
}
|