security

object

%account

/phlo/resources/security/account.phlo

Accounts on the app's own user model: sign in, stay signed in, activate and reset. Schema: resources/security/account.sql

account works on your user model (prop %account.model, default user) and its email and password columns (emailColumn, passwordColumn), so it adds no user table of its own. signIn() checks the password with a rate limit and an equal-time miss, renews the session id and upgrades the hash when PHP's default moves on; failure then says why it did not (unknown, inactive, throttled), so the message stays yours. user is the signed-in record, signOut() ends it. With remember, a rotating cookie keeps someone signed in across browser restarts. With activeColumn set, a record that is switched off is signed out on its next request, by session and by cookie alike. issue() makes a single-use token for an activation or reset link and claim() spends it: once, also when two requests bring it at the same moment, and a wrong secret leaves it for the person it was sent to. For a second factor with an authenticator app, enable security/totp, store totp::secret() on the user, show qr::svg(totp::uri($secret, $email)), and name the column in prop %account.totpColumn: signIn() then wants code: as well and fails with 'code' without it. Pages, texts and mail stay in the app: send the link with mail::send().

accountloginauthenticationpasswordrememberresetactivation2fatotp
prop

%account -> model

line 9
'user'
prop

%account -> emailColumn

line 10
'email'
prop

%account -> passwordColumn

line 11
'password'
prop

%account -> activeColumn

line 13
A column that must be true to sign in, such as active; null signs in any record.
null
prop

%account -> totpColumn

line 15
A column with the user's TOTP secret, which makes a code part of signing in (the totp resource); null has no second factor.
null
prop

%account -> rateStorage

line 17
Where attempts are counted, as rate::check takes it: apcu on one server, db across several.
'apcu'
prop

%account -> rememberDays

line 18
30
prop

%account -> failure

line 19
null
prop

%account -> db

line 20
$this->model::DB()
prop

%account -> user

line 23
The signed-in record, from the session or else from a remember cookie.
if (!($id = %session->account ?? null)) return $this->fromCookie()
if (($user = $this->model::record(...[$this->model::idColumn() => $id])) && $this->active($user)) return $user
unset(%session->account)
return null
method

%account -> active ($user):bool

line 30
!$this->activeColumn || (bool)($user->{$this->activeColumn})
static

account :: hash (string $password):string

line 32
password_hash($password, PASSWORD_DEFAULT)
method

%account -> signIn (string $email, string $password, bool $remember = false, ?string $code = null):?object

line 34
$this->failure = null
if (!rate::check('account:'.%req->ip, 10, 300, $this->rateStorage)) return $this->fail('throttled')
// Every candidate is checked, because an address may sit on more than one record; without one a
// dummy hash at the default cost is, so an unknown address takes as long as a wrong password.
$candidates = $this->model::records(...[$this->emailColumn => trim($email)])
$user = current(array_filter($candidates, fn($u) => password_verify($password, (string)$u->{$this->passwordColumn}))) ?: null
$candidates || password_verify($password, sprintf('$2y$%02d$', PASSWORD_BCRYPT_DEFAULT_COST).str_repeat('a', 53))
if (!$user) return $this->fail('unknown')
if (!$this->active($user)) return $this->fail('inactive')
if ($this->totpColumn && ($secret = (string)$user->{$this->totpColumn}) !== void && !$this->spendCode($user, $secret, (string)$code)) return $this->fail($code === null ? 'code' : 'wrong code')
$pk = $this->model::idColumn()
password_needs_rehash((string)$user->{$this->passwordColumn}, PASSWORD_DEFAULT) && $this->model::change("$pk=?", $user->$pk, ...[$this->passwordColumn => static::hash($password)])
%session->objRegenerateId()
%session->account = $user->$pk
$remember && $this->remember($user)
return $this->user = $user
method

%account -> fail (string $failure):null

line 53
$this->failure = $failure
return null
method

%account -> spendCode ($user, string $secret, string $code):bool

line 59
A code works once: its step is kept as a token of the user, and the key lets one request write it.
if (($step = totp::step($secret, $code)) === null) return false
$pk = $user->{$this->model::idColumn()};
$id = substr(md5($pk.colon.$step), 0, 20)
$mine = hash('sha256', token(32))
$this->db->query('DELETE FROM account_tokens WHERE expires < ?', time())
$this->db->create('account_tokens', ignore: true, id: $id, user: (string)$pk, kind: 'totp', hash: $mine, expires: time() + 3600)
return $this->db->query('SELECT hash FROM account_tokens WHERE id = ?', $id)->fetchColumn() === $mine
method

%account -> signOut:void

line 69
if ($selector = strstr((string)(%cookies->account ?? void), colon, true)) $this->db->delete('account_tokens', 'id=?', $selector)
unset(%cookies->account, %session->account)
%session->objRegenerateId()
method

%account -> remember ($user):void

line 77
A selector names the row and a validator proves it; only the validator's hash is stored, and
$selector = token(20)
$validator = token(32)
$this->store($selector, $user, 'remember', $validator, $this->rememberDays * 24)
%cookies->objSet('account', $selector.colon.$validator, ['expires' => time() + $this->rememberDays * 86400])
method

%account -> fromCookie

line 84
[$selector, $validator] = explode(colon, (string)(%cookies->account ?? void), 2) + [void, void]
if ($selector === void || !($user = $this->spend($selector, 'remember', $validator)) || !$this->active($user)) return null
%session->objRegenerateId()
%session->account = $user->{$this->model::idColumn()};
$this->remember($user)
return $user
method

%account -> issue ($user, string $kind, int $hours = 48):string

line 94
A single-use token for a link: issue() gives it, claim() returns its user once while it lasts.
$id = token(20)
$secret = token(32)
$this->store($id, $user, $kind, $secret, $hours)
return $id.$secret
method

%account -> claim (string $token, string $kind):?object

line 101
strlen($token) === 52 ? $this->spend(substr($token, 0, 20), $kind, substr($token, 20)) : null
method

%account -> store (string $id, $user, string $kind, string $secret, int $hours):void

line 103
$this->db->query('DELETE FROM account_tokens WHERE expires < ?', time())
$this->db->create('account_tokens', id: $id, user: (string)$user->{$this->model::idColumn()}, kind: $kind, hash: hash('sha256', $secret), expires: time() + $hours * 3600)
method

%account -> spend (string $id, string $kind, string $secret):?object

line 108
$row = $this->db->query('SELECT * FROM account_tokens WHERE id = ? AND kind = ?', $id, $kind)->fetchObject() ?: null
if ($row && (int)$row->expires < time()){
	$this->db->delete('account_tokens', 'id=?', $id)
	return null
}
if (!$row || !hash_equals((string)$row->hash, hash('sha256', $secret))) return null
if ($this->db->delete('account_tokens', 'id=?', $id) !== 1) return null
return $this->model::record(...[$this->model::idColumn() => $row->user])
object

%audit

/phlo/resources/security/audit.phlo

Audit log for model mutations (opt-in via static idColumn/objAudit). Schema: resources/security/audit.sql

Off unless a model sets objAudit, and then every create, change and delete is written: an update as the difference between before and after, a create as the new row, a delete as the row that went. Pass exclude for columns you would rather not keep, a password hash or a token; the log outlives the record, so what goes in is a decision, not a detail. purge() is there because a log nobody prunes eventually costs more than the table it watches.

auditlogcompliancetraceability
static

audit :: log ($model, $action, $before = [], $after = [], $exclude = []):void

line 8
$class = is_object($model) ? get_class($model) : (string)$model
$pk = (is_string($class) && class_exists($class) && property_exists($class, 'idColumn')) ? $class::$idColumn : 'id'
$id = is_object($model) ? ($model->$pk ?? $model->id ?? null) : null
if ($id === null) return
$before = (array)$before
$after = (array)$after
foreach ($exclude AS $col) unset($before[$col], $after[$col])
$changes = $action === 'update' ? static::diff($before, $after) : ($action === 'create' ? $after : $before)
$class::DB()->query(
	'INSERT INTO audit_log (ts, '.$class::DB()->quoteId('user').', model, record_id, action, changes, ip) VALUES (?, ?, ?, ?, ?, ?, ?)',
	time(),
	class_exists('session') && isset(%session->user) ? (int)%session->user : null,
	$class,
	(string)$id,
	$action,
	json_encode($changes, jsonFlat),
	(string)($_SERVER['REMOTE_ADDR'] ?? null),
)
static

audit :: diff ($before, $after):array

line 29
计算两组数据之间的差异,返回一个包含更改属性及其旧值和新值的数组。
$changed = []
foreach ($after AS $col => $newVal){
	$oldVal = $before[$col] ?? null
	if ($oldVal !== $newVal) $changed[$col] = ['from' => $oldVal, 'to' => $newVal]
}
return $changed
static

audit :: history ($model, $recordId, $limit = 50):array

line 38
从audit_log表中检索特定模型和记录ID的审计历史,按时间戳降序排序,并限制结果数量。
$class = is_object($model) ? get_class($model) : (string)$model
return $class::DB()->query(
	'SELECT * FROM audit_log WHERE model=? AND record_id=? ORDER BY ts DESC LIMIT ?',
	$class, (string)$recordId, (int)$limit,
)->fetchAll(\PDO::FETCH_OBJ)
static

audit :: byUser ($model, $userId, $fromTs = 0, $limit = 100):array

line 46
检索特定用户的审计日志条目,按时间戳过滤,并限制为指定数量的结果。
return $model::DB()->query(
	'SELECT * FROM audit_log WHERE '.$model::DB()->quoteId('user').'=? AND ts >= ? ORDER BY ts DESC LIMIT ?',
	(int)$userId, (int)$fromTs, (int)$limit,
)->fetchAll(\PDO::FETCH_OBJ)
static

audit :: purge ($model, $olderThanSeconds = 31536000)

line 53
删除审计日志表中超过指定秒数的条目。
$model::DB()->query('DELETE FROM audit_log WHERE ts < ?', time() - $olderThanSeconds)
object

%captcha

/phlo/resources/security/captcha.phlo

Self-contained interactive slider-puzzle captcha (no external service). The server picks a secret gap position and renders the background plus a loose piece with GD; the client drags the piece into place. verify() checks the end position plus human drag behaviour (time, path, variation). Single-use and session-bound; the gap position never leaves the server.

Runs entirely on your own server, so no visitor is handed to a third party and nothing has to be disclosed in a privacy statement. The gap position never leaves the server, and it judges the drag as well as the endpoint, so a script that jumps straight to the answer is refused. verify() does not consume the puzzle: call consume() yourself, and only on success, or a failed attempt costs the visitor their challenge. It needs GD.

captchaspambothuman-verificationsecurity
static

captcha :: W

line 9
生成宽度为300像素的验证码图像。
300
static

captcha :: H

line 10
此常量表示CAPTCHA图像的高度(以像素为单位)。
180
static

captcha :: P

line 11
captcha::$P 是一个常量,保存用于 Phlo 应用程序验证的验证码参数值。
56
static

captcha :: tol

line 12
captcha::$tol 返回 CAPTCHA 验证过程的容忍度,决定系统在评估用户响应时的宽容程度。
8
static

captcha :: ttl

line 13
设置验证码的生存时间(TTL),单位为秒。
600
static

captcha :: issue:array

line 15
生成一个随机间隙用于验证码挑战,并将间隙值与过期时间存储在会话中。
$gapX = random_int(static::$P + 14, static::$W - static::$P - 6)
$gapY = random_int(12, static::$H - static::$P - 12)
%session->captcha = arr(gap: $gapX, exp: time() + static::$ttl)
return arr(gapX: $gapX, gapY: $gapY)
static

captcha :: images ($gapX, $gapY):array

line 22
生成一个验证码图像和一个拼图块,并将其作为base64编码的PNG数据返回。背景图像具有渐变和随机椭圆,而拼图块是背景的裁剪部分。
$w = static::$W
$h = static::$H
$p = static::$P
$bg = imagecreatetruecolor($w, $h)
$r0 = random_int(50, 170)
$g0 = random_int(50, 170)
$b0 = random_int(50, 170)
for ($x = 0; $x < $w; $x++){
	$col = imagecolorallocate($bg, (int)($r0 + $x * 0.5) % 256, (int)($g0 + $x * 0.2 + 30) % 256, (int)($b0 + ($w - $x) * 0.4) % 256)
	imagefilledrectangle($bg, $x, 0, $x, $h, $col)
}
imagealphablending($bg, true)
for ($i = 0; $i < 7; $i++){
	$col = imagecolorallocatealpha($bg, random_int(0, 255), random_int(0, 255), random_int(0, 255), random_int(55, 95))
	imagefilledellipse($bg, random_int(0, $w), random_int(0, $h), random_int(50, 130), random_int(50, 130), $col)
}
$piece = imagecreatetruecolor($p, $p)
imagecopy($piece, $bg, 0, 0, $gapX, $gapY, $p, $p)
imagerectangle($piece, 0, 0, $p - 1, $p - 1, imagecolorallocate($piece, 245, 245, 245))
imagefilledrectangle($bg, $gapX, $gapY, $gapX + $p - 1, $gapY + $p - 1, imagecolorallocatealpha($bg, 0, 0, 0, 95))
imagerectangle($bg, $gapX, $gapY, $gapX + $p - 1, $gapY + $p - 1, imagecolorallocate($bg, 255, 255, 255))
ob_start()
imagepng($bg)
$bgData = base64_encode(ob_get_clean())
ob_start()
imagepng($piece)
$pieceData = base64_encode(ob_get_clean())
return arr(bg: 'data:image/png;base64,'.$bgData, piece: 'data:image/png;base64,'.$pieceData)
static

captcha :: verify ($x, $telemetry):bool

line 57
Judges the drag as much as where it ended.
$c = %session->captcha ?? null
if (!$c || time() > (int)($c['exp'] ?? 0)) return false
if (abs((int)round((float)$x) - (int)($c['gap'] ?? -999)) > static::$tol) return false
$t = json_decode((string)$telemetry, true)
if (!is_array($t)) return false
$d = (int)($t['d'] ?? 0)
$n = (int)($t['n'] ?? 0)
$xs = is_array($t['x'] ?? null) ? array_values($t['x']) : []
if ($d < 200 || $d > 60000) return false
if ($n < 5 || count($xs) < 4) return false
$deltas = []
for ($i = 1; $i < count($xs); $i++) $deltas[] = (float)$xs[$i] - (float)$xs[$i - 1]
if (array_sum(array_map('abs', $deltas)) < 30) return false
$mean = array_sum($deltas) / count($deltas)
$var = 0
foreach ($deltas AS $dd) $var += ($dd - $mean) ** 2
if (sqrt($var / count($deltas)) < 0.5) return false
return true
static

captcha :: consume:void

line 78
从会话中移除验证码数据,实际上消耗了它。
unset(%session->captcha)
method

%captcha -> widget:string

line 82
通过发出挑战并使用指定参数创建图像来生成 CAPTCHA 小部件。
$ch = static::issue()
$img = static::images($ch['gapX'], $ch['gapY'])
return (string)$this->field($img['bg'], $img['piece'], $ch['gapY'], static::$W, static::$H, static::$P)
view

%captcha -> field ($bg, $piece, $gapY, $w, $h, $p)

line 88
生成一个CAPTCHA视图,包含一个可拖动的滑块供用户完成拼图,从而增强对自动提交的安全性。
<div#captcha data-w="$w" data-h="$h" data-p="$p" data-gapy="$gapY">
	<div.stage>
		<img.bg src="{{ $bg }}" alt="">
		<img.piece src="{{ $piece }}" alt="" draggable="false">
	</div>
	<div.track>
		<div.fill></div>
		<button.thumb type="button" tabindex="-1" aria-label="{{ en('Drag the slider until the piece fits') }}">&#8250;&#8250;</button>
	</div>
	<p.hint>{en: Drag the slider until the piece snaps into place}</p>
	<input type=hidden name=captcha_x>
	<input type=hidden name=captcha_t>
</div>
view

style

line 103
定义验证码组件的CSS样式,包括布局、颜色和交互元素。
#captcha {
	margin: 14px 0 4px
	max-width: 300px
}
#captcha .stage {
	border-radius: 8px
	line-height: 0
	overflow: hidden
	position: relative
	touch-action: none
	user-select: none
	width: 100%
}
#captcha .bg {
	display: block
	height: auto
	pointer-events: none
	width: 100%
}
#captcha .piece {
	box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.25), 0 2px 6px rgba(0, 0, 0, 0.4)
	left: 6px
	pointer-events: none
	position: absolute
	top: 0
}
#captcha .track {
	background: #e7e5e4
	border-radius: 8px
	height: 42px
	margin-top: 10px
	position: relative
	touch-action: none
}
#captcha .fill {
	background: #fed7aa
	border-radius: 8px
	height: 100%
	left: 0
	position: absolute
	top: 0
	width: 0
}
#captcha .thumb {
	align-items: center
	appearance: none
	background: #ea580c
	border: 0
	border-radius: 8px
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3)
	color: #fff
	cursor: grab
	display: flex
	font-family: inherit
	font-size: 18px
	font-weight: 700
	height: 42px
	justify-content: center
	left: 0
	margin: 0
	padding: 0
	position: absolute
	top: 0
	touch-action: none
	width: 42px
}
#captcha .thumb:active: cursor: grabbing
#captcha .thumb:hover: background: #c2410c
#captcha .hint {
	color: #78716c
	font-size: 12px
	margin: 6px 0 0
}
view

script

line 179
const captcha = {
	scale: 1, startCss: 6, travelMax: 0, maxThumb: 0,
	dragging: false, t0: 0, samples: [],
	cap: null, bg: null, piece: null, thumb: null, track: null, fill: null, xField: null, tField: null, submit: null,
	grab(){
		this.cap = obj('#captcha')
		if (!this.cap) return false
		this.bg = obj('.bg', this.cap)
		this.piece = obj('.piece', this.cap)
		this.thumb = obj('.thumb', this.cap)
		this.track = obj('.track', this.cap)
		this.fill = obj('.fill', this.cap)
		this.xField = obj('[name=captcha_x]', this.cap)
		this.tField = obj('[name=captcha_t]', this.cap)
		this.submit = obj('#registerSubmit')
		return true
	},
	layout(){
		if (!this.grab()) return
		const Wr = this.bg.clientWidth || +this.cap.dataset.w
		this.scale = Wr / +this.cap.dataset.w
		const pieceCss = +this.cap.dataset.p * this.scale
		this.piece.style.width = pieceCss + 'px'
		this.piece.style.height = pieceCss + 'px'
		this.piece.style.top = (+this.cap.dataset.gapy * this.scale) + 'px'
		this.startCss = 6 * this.scale
		this.piece.style.left = this.startCss + 'px'
		this.travelMax = Wr - pieceCss - this.startCss
		this.maxThumb = this.track.clientWidth - this.thumb.clientWidth
		if (this.submit) this.submit.disabled = true
	},
	set(tx){
		tx = Math.max(0, Math.min(this.maxThumb, tx))
		this.thumb.style.left = tx + 'px'
		this.fill.style.width = (tx + this.thumb.clientWidth) + 'px'
		const frac = this.maxThumb > 0 ? tx / this.maxThumb : 0
		const pl = this.startCss + frac * (this.travelMax - this.startCss)
		this.piece.style.left = pl + 'px'
		return pl / this.scale
	},
	down(e){
		if (!this.grab()) return
		this.dragging = true
		this.t0 = performance.now()
		this.samples = []
		e.preventDefault()
	},
	move(e){
		if (!this.dragging) return
		const px = e.touches ? e.touches[0].clientX : e.clientX
		const rect = this.track.getBoundingClientRect()
		const nx = this.set(px - rect.left - this.thumb.clientWidth / 2)
		this.samples.push({x: nx, t: performance.now() - this.t0})
	},
	up(){
		if (!this.dragging) return
		this.dragging = false
		const xs = this.samples.map(s => Math.round(s.x))
		this.xField.value = xs.length ? xs[xs.length - 1] : 0
		const step = Math.max(1, Math.ceil(xs.length / 24))
		this.tField.value = JSON.stringify({d: Math.round(this.samples.length ? this.samples[this.samples.length - 1].t : 0), n: this.samples.length, x: xs.filter((_, i) => i % step === 0)})
		if (this.submit) this.submit.disabled = false
	}
}

onExist('#captcha', () => captcha.layout())
on('load', '#captcha .bg', () => captcha.layout())
on('resize', window, () => captcha.layout())
on('mousedown touchstart', '#captcha .thumb', (el, e) => captcha.down(e))
on('mousemove touchmove', window, (el, e) => last(captcha.move(e), false))
on('mouseup touchend', window, (el, e) => captcha.up())
object

%creds

/phlo/resources/security/creds.phlo

Credentials resolver from env and ini sources

One place for every secret, filled from data/creds.ini and from the environment, where PHLO__Section__key sets a value and PHLO_<HOST>__Section__key overrides it for one host, with <HOST> the request host uppercased and every other character an underscore. Values are wrapped so a var_dump or an error page shows stars instead of the secret. Keep the ini file out of the repository and let the environment win on a server.

credentialsenvinisecretsconfiguration
method

%creds -> __construct (?array $values = null)

line 8
初始化creds对象,如果未提供值则解析值,并将每个值分配给相应的属性,根据需要创建static或SensitiveParameterValue的新实例。
$values ??= $this->resolve()
foreach ($values AS $key => $value){
	$this->$key = is_array($value) ? new static($value) : new \SensitiveParameterValue((string)$value)
}
method

%creds -> resolve:array

line 15
此函数解析并合并来自INI文件和环境变量的凭据数据,返回合并后的数据数组。
$data = []
$this->merge($data, $this->loadINI(data.'creds.ini'))
$this->merge($data, $this->envValues(false))
$this->merge($data, $this->envValues(true))
return $data
method

%creds -> loadINI (string $file):array

line 23
从指定的文件路径加载INI文件中的配置设置,并将其作为关联数组返回。如果文件不存在或无法解析,则返回一个空数组。
if (!is_file($file)) return []
$ini = parse_ini_file($file, true, INI_SCANNER_RAW)
return is_array($ini) ? $ini : []
method

%creds -> envValues (bool $hostScoped = false):array

line 29
提取以指定前缀开头的环境变量值,选项上限于主机,并将其作为关联数组返回。
$out = []
$prefix = $hostScoped ? ('PHLO_'.$this->hostKey().'__') : 'PHLO__'
$sources = []
is_array($_ENV ?? null) && $sources[] = $_ENV
is_array($_SERVER ?? null) && $sources[] = $_SERVER
is_array($env = getenv()) && $sources[] = $env
foreach ($sources AS $source){
	foreach ($source AS $key => $value){
		$key = (string)$key
		if (!str_starts_with($key, $prefix)) continue
		$path = substr($key, strlen($prefix))
		if (!$path) continue
		$this->envAssign($out, explode('__', $path), (string)$value)
	}
}
return $out
method

%creds -> hostKey:string

line 48
该函数处理请求中的主机,将其转换为大写,移除非字母数字字符,并修剪任何前导或尾随分隔符。
$host = strtoupper(%req->host)
$host = preg_replace('/[^A-Z0-9]+/', us, $host)
return trim($host, us)
method

%creds -> envAssign (array &$target, array $parts, string $value):void

line 54
根据提供的部分将值分配给嵌套数组结构,必要时创建中间数组。
$parts = array_values(array_filter(loop($parts, fn($part) => trim($part)), 'strlen'))
if (!$parts) return
$node = &$target
$last = count($parts) - 1
foreach ($parts AS $i => $part){
	if ($i === $last){
		$node[$part] = $value
		return
	}
	if (!isset($node[$part]) || !is_array($node[$part])) $node[$part] = []
	$node = &$node[$part]
}
method

%creds -> merge (array &$base, array $add):void

line 69
将$add数组的内容合并到$base数组中,如果两个都是数组,则递归地组合值。
foreach ($add AS $key => $value){
	if (isset($base[$key]) && is_array($base[$key]) && is_array($value)){
		$this->merge($base[$key], $value)
		continue
	}
	$base[$key] = $value
}
method

%creds -> objGet ($key)

line 79
从对象中检索与指定键关联的值,以安全的方式返回敏感值。
if ($key === 'toArray') return loop($this->objData, fn($value) => is_a($value, 'SensitiveParameterValue') ? $value->getValue() : $value)
if (isset($this->objData[$key]) && is_a($this->objData[$key], '\SensitiveParameterValue')) return $this->objData[$key]->getValue()
method

%creds -> objInfo:array

line 84
此函数处理objData中的每个项目,将SensitiveParameterValue的实例替换为与其长度相对应的星号,同时保持其他值不变。
loop($this->objData, fn($value) => is_a($value, '\SensitiveParameterValue') ? str_repeat('*', strlen($value->getValue())) : $value)
object

%CSRF

/phlo/resources/security/CSRF.phlo

CSRF protection for every state-changing request of the app

Enabled, it guards the whole app before any route runs: a POST, PUT, PATCH or DELETE from a browser, which shows by a cookie, HTTP basic auth, an Origin or a Sec-Fetch-Site header, needs the session's token, which phlo.js sends as the X-CSRF-Token header and a plain form sends as a csrf field (%CSRF->field). Put %CSRF in your head view for the meta tag the frontend reads. A request with none of those, such as a webhook with a signature or an API call with a token from a server, is no browser and passes; except is for a post from another site's page or from the system, such as an OAuth provider posting back or a share target. A public form starts the session on its GET and carries %CSRF->field. update() answers with a fresh token the page applies, which makes a stolen token worth one request; verify() is there for a check of your own: it is true after the guard validated the token, also when it took a csrf field out of the payload, or when the request itself carries a valid token, as on an except path; without a token where the guard checked nothing, it is false. It protects a session, so it says nothing about an API authenticated with a bearer token. %CSRF in the head starts a session on every page it is on: each visitor, a crawler too, gets a session cookie and a session file, and under PHP's default cache limiter the page is sent no-store, so a public site without forms that change something can leave the resource off.

csrfsecurityasyncforms
view

%CSRF -> view

line 10
生成一个包含CSRF令牌的meta标签,用于安全的表单提交。
<meta name=csrf content="$this->token">
view

%CSRF -> field

line 11
<input type=hidden name=csrf value="$this->token">
prop

%CSRF -> token:string

line 12
如果会话中尚不存在,则生成一个32个字符的CSRF令牌。
%session->csrf ??= token(32)
prop

%CSRF -> except:array

line 15
Path prefixes that a browser posts to from outside the app, such as an OAuth callback: prop %CSRF.except => ['auth/']
[]
prop

%CSRF -> passed

line 17
false
method

%CSRF -> verify:bool

line 18
$this->passed || hash_equals($this->token, (string)(%req->header('X-CSRF-Token') ?? %payload->csrf ?? void))
static

CSRF :: beforeRoute

line 21
Runs before the app's routes (beforeRoute): a state-changing request without the token stops here.
if (%req->cli || in_array(%req->method, ['GET', 'HEAD', 'OPTIONS', 'QUERY'], true) || !static::ambient()) return
foreach (%CSRF->except AS $prefix) if (str_starts_with(%req->route, ltrim($prefix, slash))) return
%CSRF->verify || error('Invalid CSRF token', 403)
%CSRF->passed = true
// The token is this guard's, so a route's @keys match what the form is about.
if (%req->header('X-CSRF-Token') === null) unset(%payload->csrf)
method

%CSRF -> update:array

line 29
更新会话中的CSRF令牌并将其分配给csrf属性。
arr(csrf: $this->token = %session->csrf = token(32))
static

CSRF :: ambient:bool

line 30
%req->header('Cookie') !== null || isset($_SERVER['PHP_AUTH_USER']) || stripos((string)%req->header('Authorization'), 'basic ') === 0 || %req->header('Origin') !== null || %req->header('Sec-Fetch-Site') !== null
view

script

line 32
app.mod.csrf = value => obj('meta[name="csrf"]').content = value
app.requests.push(xhr => {
	const token = obj('meta[name="csrf"]')?.content
	token && xhr.setRequestHeader('X-CSRF-Token', token)
})
object

%JWT

/phlo/resources/security/JWT.phlo

Sign and verify compact HS256 JSON Web Tokens (RFC 7519), secure by default

HS256 only, and a token that claims another algorithm is refused rather than tried, which is the classic way these are broken. The secret must be at least 32 bytes, an expiry is always written, and verify() throws with a 401 instead of returning false, so a route can simply call it. Name an issuer and it is checked as well. A signed token is readable by anyone holding it, so keep secrets out of the claims.

jwtjwshs256tokenauthsecurity
method

%JWT -> __construct (public string $secret, public string $issuer = void, public int $leeway = 30)

line 9
构造一个JWT实例,指定密钥、发行者和宽限时间。它确保密钥至少为32个字节长,如果不满足此条件,则抛出错误。
strlen($this->secret) >= 32 || error('JWT secret must be at least 32 bytes', 500)
method

%JWT -> sign (array $claims, int $ttl = 3600):string

line 11
通过使用指定的生存时间(TTL)对提供的声明进行签名来生成 JSON Web Token(JWT)。该令牌包括签发时间(iat)和到期时间(exp)时间戳,并可以选择性地包含发行者(iss)。
$now = time()
$claims['iat'] = $now
$claims['exp'] = $now + $ttl
if ($this->issuer !== void) $claims['iss'] = $this->issuer
$body = $this->encode(['alg' => 'HS256', 'typ' => 'JWT']).dot.$this->encode($claims)
return $body.dot.$this->sig($body)
method

%JWT -> verify (string $token):array

line 20
通过检查其结构、签名和声明(如过期时间和发行者)来验证 JSON Web Token (JWT)。
$token = preg_replace('/^Bearer\s+/i', void, trim($token))
$parts = explode(dot, $token)
count($parts) === 3 || error('JWT malformed', 401)
[$h, $p, $s] = $parts
$header = (array)json_decode((string)$this->decode($h), true)
($header['alg'] ?? void) === 'HS256' || error('JWT algorithm not allowed', 401)
hash_equals($this->sig($h.dot.$p), $s) || error('JWT signature invalid', 401)
$claims = (array)json_decode((string)$this->decode($p), true)
$now = time()
isset($claims['nbf']) && $now + $this->leeway < $claims['nbf'] && error('JWT not yet valid', 401)
isset($claims['exp']) && $now - $this->leeway >= $claims['exp'] && error('JWT expired', 401)
$this->issuer === void || ($claims['iss'] ?? void) === $this->issuer || error('JWT issuer mismatch', 401)
return $claims
method

%JWT -> sig (string $body):string

line 36
使用HMAC和SHA-256及秘密密钥为给定主体生成签名。
$this->encode(hash_hmac('sha256', $body, $this->secret, true))
method

%JWT -> encode ($data):string

line 37
rtrim(strtr(base64_encode(is_string($data) ? $data : (string)json_encode($data, jsonFlat)), '+/', '-_'), eq)
method

%JWT -> decode (string $data):string

line 38
从 base64 编码的字符串解码 JSON Web Token (JWT),将 URL 安全字符替换为标准 base64 字符。
(string)base64_decode(strtr($data, '-_', '+/'))
object

%OAuth2

/phlo/resources/security/OAuth2.phlo

Stateless OAuth2 client: build the authorize URL and exchange/refresh tokens. Token storage and config are the caller's responsibility. The protocol primitive under TokenStore and OAuthConnector.

The bare protocol: build an authorize URL, trade a code for tokens, refresh. It keeps nothing and knows nothing about your app, which is what makes it usable for any provider. For a connector you almost never need it directly, since TokenStore and OAuthConnector do the keeping for you; reach for it when you run the login yourself.

oauthoauth2tokenauthorizationrefreshauthentication
static

OAuth2 :: authorizeUrl ($endpoint, array $params):string

line 9
通过将查询参数附加到端点生成OAuth2流程的授权URL。
$endpoint.(str_contains($endpoint, '?') ? '&' : '?').http_build_query($params)
static

OAuth2 :: token ($tokenUrl, $clientId, $clientSecret, $grantType, array $extra = []):array

line 11
通过向指定的令牌URL发送请求,使用必要的凭据和参数来检索OAuth2令牌,处理错误并将响应作为关联数组返回。
$body = ['grant_type' => $grantType, 'client_id' => (string)$clientId, 'client_secret' => (string)$clientSecret]
foreach ($extra AS $key => $value){
	if ($value !== null && $value !== void) $body[$key] = $value
}
try {
	$res = HTTP($tokenUrl, ['Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'], POST: http_build_query($body))
}
catch (\Throwable $e){
	return ['error' => $e->getMessage()]
}
return json_decode((string)$res, true) ?: ['error' => 'Invalid token response']
static

OAuth2 :: exchangeCode ($tokenUrl, $clientId, $clientSecret, $code, $redirectUri = null, array $extra = []):array

line 25
使用OAuth2协议将授权码兑换为访问令牌。
static::token($tokenUrl, $clientId, $clientSecret, 'authorization_code', ['code' => $code, 'redirect_uri' => $redirectUri] + $extra)
static

OAuth2 :: refresh ($tokenUrl, $clientId, $clientSecret, $refreshToken, array $extra = []):array

line 27
此方法使用提供的刷新令牌和附加参数刷新OAuth2访问令牌。
static::token($tokenUrl, $clientId, $clientSecret, 'refresh_token', ['refresh_token' => $refreshToken] + $extra)
object

%rate

/phlo/resources/security/rate.phlo

Rate-limit (fixed window) on the rate_limit table. Schema: resources/security/rate.sql

A fixed window, counted in one atomic statement, so two requests arriving together cannot both slip past the limit. Storage db survives a restart and is shared across machines; apcu is faster but lives in one server's shared memory, so it is gone after a restart and says nothing about a second machine. Because the window is fixed rather than sliding, a caller can spend a full limit at the end of one window and again at the start of the next.

ratelimitthrottleabuse
static

rate :: check ($key, $limit, $windowSeconds, $storage = 'db'):bool

line 9
if ($storage === 'apcu') return static::checkApcu($key, $limit, $windowSeconds)
$now = time()
// One atomic upsert: increment within the window or reset to a new one, and carry the
// resulting per-request count out via LAST_INSERT_ID. A separate read-then-write would
// let two requests arriving together both pass the limit.
%MySQL->query('INSERT INTO rate_limit (rkey, count, window_start) VALUES (?, LAST_INSERT_ID(1), ?) ON DUPLICATE KEY UPDATE count = LAST_INSERT_ID(IF(? - window_start < ?, count + 1, 1)), window_start = IF(? - window_start < ?, window_start, ?)', $key, $now, $now, $windowSeconds, $now, $windowSeconds, $now)
return (int)%MySQL->query('SELECT LAST_INSERT_ID()')->fetchColumn() <= $limit
static

rate :: checkApcu ($key, $limit, $windowSeconds):bool

line 19
$window = (int)floor(time() / $windowSeconds) * $windowSeconds
$apcuKey = 'rate/'.substr(md5(app), 0, 8).colon.$key.colon.$window
apcu_add($apcuKey, 0, $windowSeconds)
return apcu_inc($apcuKey, 1) <= $limit
static

rate :: status ($key, $limit, $windowSeconds):obj

line 26
检索当前的速率限制状态,包括已使用的请求数量、限制和重置限制的时间。
$now = time()
$row = %MySQL->query('SELECT count, window_start FROM rate_limit WHERE rkey=?', $key)->fetchObject('obj') ?: null
if (!$row || ($now - (int)$row->window_start) >= $windowSeconds) return obj(used: 0, limit: $limit, resetIn: 0)
return obj(used: (int)$row->count, limit: $limit, resetIn: max(0, ((int)$row->window_start + $windowSeconds) - $now))
static

rate :: reset ($key)

line 33
此方法通过从MySQL数据库中的rate_limit表中删除相应条目来重置速率限制。
%MySQL->query('DELETE FROM rate_limit WHERE rkey=?', $key)
static

rate :: purge ($olderThanSeconds = 604800)

line 34
从rate_limit表中删除window_start早于指定时间(以秒为单位)的条目。
%MySQL->query('DELETE FROM rate_limit WHERE window_start < ?', time() - $olderThanSeconds)
object

%security

/phlo/resources/security/security.phlo

Generic security resource

Pick a profile per app rather than writing headers yourself: strict allows only nonced scripts and styles, basic allows your own files, marketing also allows images from anywhere, and api shuts everything off and marks the response as an API. Async responses get no policy, because the page they land in already has one. Add a source per directive to allow, such as 'img-src' => ['https://cdn.example.com'], 'frame-src' => ['https://*.youtube.com'] or 'connect-src' => ['wss://example.com']; everything else stays closed. sandbox() is the profile for a file someone uploaded: it runs and loads nothing. Under debug, basic and marketing let inline scripts through so the debug console runs, so a production site with debug on is running a weaker policy than it thinks.

securitycspnonceheaders
prop

%security -> allow:array

line 11
Sources per directive on top of the profile, such as 'connect-src' => ['wss://example.com'] or
[]
method

%security -> setNonce:string

line 13
使用指定长度的生成令牌为应用程序设置一个随机数值。
%app->nonce = token(8)
method

%security -> frameProtect ($mode = 'DENY')

line 15
设置 X-Frame-Options 头部以控制页面是否可以在框架中显示,默认模式为 'DENY'。
%res->header('X-Frame-Options', $mode)
method

%security -> page:array

line 18
What every page profile starts from: own files, data: images and blob: media.
[
	'default-src' => ["'self'"],
	'script-src' => ["'self'", ...(debug ? ["'unsafe-inline'"] : [])],
	'style-src' => ["'self'", "'unsafe-inline'"],
	'img-src' => ["'self'", 'data:'],
	'media-src' => ["'self'", 'blob:'],
	'font-src' => ["'self'"],
	'connect-src' => ["'self'"],
	'form-action' => ["'self'"],
	'object-src' => ["'none'"],
	'frame-src' => ["'self'"],
	'frame-ancestors' => ["'none'"],
	'base-uri' => ["'self'"],
]
method

%security -> policy (array $directives):void

line 33
foreach ($this->allow AS $directive => $sources) $directives[$directive] = array_values(array_unique([...($directives[$directive] ?? []), ...(array)$sources]))
%res->header('Content-Security-Policy', loop($directives, fn($sources, $directive) => trim($directive.space.implode(space, $sources)), '; '))
method

%security -> strict:void

line 39
Only nonced scripts and styles.
$this->base
if (%req->async) return
%res->header('Cache-Control', 'no-store')
$nonce = "'nonce-".$this->setNonce."'"
$this->policy(array_replace($this->page, ['script-src' => [$nonce], 'style-src' => ["'self'", $nonce], 'worker-src' => ["'self'"]]))
method

%security -> basic:void

line 48
Under debug, basic and marketing let inline scripts through so the debug console runs. Whether
$this->base
if (%req->async) return
$this->policy($this->page)
method

%security -> marketing:void

line 53
$this->base
if (%req->async) return
$this->policy(array_replace($this->page, ['img-src' => ["'self'", 'data:', 'https:']]))
method

%security -> api:void

line 58
为API响应设置与安全相关的HTTP头,增强对各种网络漏洞的保护。
%res->api = true
%res->header('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'")
%res->header('X-Content-Type-Options', 'nosniff')
%res->header('Referrer-Policy', 'no-referrer')
method

%security -> sandbox:void

line 66
For a file someone uploaded, served from the app's own origin: it runs nothing, loads nothing and
%res->header('Content-Security-Policy', "default-src 'none'; sandbox; frame-ancestors 'none'")
%res->header('X-Content-Type-Options', 'nosniff')
%res->header('Referrer-Policy', 'no-referrer')
method

%security -> base:void

line 72
为响应设置各种与安全相关的HTTP头,包括Referrer-Policy、X-Content-Type-Options、跨源策略和X-Frame-Options,以增强对跨源攻击的防护。
%res->header('Referrer-Policy', 'strict-origin-when-cross-origin')
%res->header('X-Content-Type-Options', 'nosniff')
%req->async || %res->header('Cross-Origin-Opener-Policy', 'same-origin')
%req->async || %res->header('Cross-Origin-Resource-Policy', 'same-origin')
%req->async || %res->header('Access-Control-Allow-Origin', %req->base)
%req->async || %res->header('X-Frame-Options', 'DENY')
object

%social

/phlo/resources/security/social.phlo

Reusable social login (OIDC) on top of OAuth2: build the authorize URL and turn a callback code into a verified profile. Google, Microsoft and Apple. No user, session or route handling - that is the caller's responsibility.

The id_token is verified against the provider's JWKS (RS256 only, key looked up by kid) before any claim is read, on top of issuer, audience (must equal client_id), expiry and, when supplied, nonce. `verified` reports what the provider actually proved: Microsoft omits email_verified, so it counts only when the optional xms_edov claim states the tenant owns the address. Treat an unverified email as a claim, never as an identity: match users on provider + sub. Apple's client_secret is an ES256 JWT signed with the .p8 key (team_id/key_id/client_id + key from creds).

oauthoidcsociallogingooglemicrosoftappleauthentication
static

social :: providers:array

line 9
arr(
	google: arr(
		label: 'Google',
		authorize: 'https://accounts.google.com/o/oauth2/v2/auth',
		token: 'https://oauth2.googleapis.com/token',
		jwks: 'https://www.googleapis.com/oauth2/v3/certs',
		scope: 'openid email profile',
		issuer: 'https://accounts.google.com',
	),
	microsoft: arr(
		label: 'Microsoft',
		authorize: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
		token: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
		jwks: 'https://login.microsoftonline.com/common/discovery/v2.0/keys',
		scope: 'openid email profile',
		issuer: 'https://login.microsoftonline.com/',
	),
	apple: arr(
		label: 'Apple',
		authorize: 'https://appleid.apple.com/auth/authorize',
		token: 'https://appleid.apple.com/auth/token',
		jwks: 'https://appleid.apple.com/auth/keys',
		scope: 'name email',
		issuer: 'https://appleid.apple.com',
	),
)
static

social :: config ($provider):?array

line 36
$p = static::providers()[$provider] ?? null
if (!$p) return null
$section = %creds->{$provider} ?? null
$creds = is_object($section) ? (array)$section->toArray : []
return $p + arr(
	client_id: (string)($creds['client_id'] ?? void),
	client_secret: (string)($creds['client_secret'] ?? void),
	redirect_uri: (string)($creds['redirect_uri'] ?? ('https://'.%req->host.'/auth/'.$provider.'/callback')),
)
static

social :: configured ($provider):bool

line 48
检查给定提供者的社交配置是否已设置,以及客户端ID是否不为空。
$c = static::config($provider)
return $c && $c['client_id'] !== void
static

social :: authUrl ($provider, $state, $nonce = void):string

line 53
$c = static::config($provider)
$params = arr(
	client_id: $c['client_id'],
	redirect_uri: $c['redirect_uri'],
	response_type: 'code',
	scope: $c['scope'],
	state: $state,
)
if ($nonce !== void) $params['nonce'] = $nonce
if ($provider === 'apple') $params['response_mode'] = 'form_post'
return OAuth2::authorizeUrl($c['authorize'], $params)
static

social :: profile ($provider, $code, $nonce = void):?array

line 67
$cfg = static::config($provider)
if (!$cfg || $cfg['client_id'] === void) return null
$secret = $provider === 'apple' ? static::appleSecret() : $cfg['client_secret']
$token = OAuth2::exchangeCode($cfg['token'], $cfg['client_id'], $secret, $code, $cfg['redirect_uri'])
$jwt = (string)($token['id_token'] ?? void)
if (!static::verifySignature($provider, $jwt)) return null
$claims = static::decodeIdToken($jwt)
if (!$claims || !static::verifyClaims($provider, $cfg, $claims, $nonce)) return null
$profile = static::normalize($provider, $claims)
if ($provider === 'apple' && !$profile['name']){
	$u = json_decode((string)(%payload->user ?? void), true)
	if (is_array($u) && !empty($u['name'])) $profile['name'] = trim(((string)($u['name']['firstName'] ?? void)).space.((string)($u['name']['lastName'] ?? void)))
}
return $profile
static

social :: decodeIdToken ($jwt):?array

line 84
$parts = explode(dot, (string)$jwt)
if (count($parts) < 2) return null
$claims = json_decode(static::b64urlDecode($parts[1]), true)
return is_array($claims) ? $claims : null
static

social :: algs:array

line 94
RS256 only, and deliberately so.
arr(RS256: OPENSSL_ALGO_SHA256)
static

social :: verifySignature ($provider, $jwt):bool

line 96
$parts = explode(dot, (string)$jwt)
if (count($parts) !== 3) return false
$header = json_decode(static::b64urlDecode($parts[0]), true)
if (!is_array($header)) return false
$alg = static::algs()[(string)($header['alg'] ?? void)] ?? null
$kid = (string)($header['kid'] ?? void)
if (!$alg || !$kid) return false
$pem = static::key($provider, $kid)
if (!$pem) return false
return openssl_verify($parts[0].dot.$parts[1], static::b64urlDecode($parts[2]), $pem, $alg) === 1
static

social :: jwks ($provider):array

line 109
$cached = %req->socialJwks ?? []
if (isset($cached[$provider])) return $cached[$provider]
$url = (string)(static::providers()[$provider]['jwks'] ?? void)
$keys = []
if ($url){
	$data = json_decode((string)HTTP($url, ['Accept: application/json']), true)
	if (is_array($data) && is_array($data['keys'] ?? null)) $keys = $data['keys']
}
$cached[$provider] = $keys
%req->socialJwks = $cached
return $keys
static

social :: key ($provider, $kid):string

line 123
foreach (static::jwks($provider) AS $jwk){
	if ((string)($jwk['kid'] ?? void) === $kid) return static::jwkToPem((array)$jwk)
}
return void
static

social :: jwkToPem (array $jwk):string

line 130
if ((string)($jwk['kty'] ?? void) !== 'RSA') return void
$n = static::b64urlDecode((string)($jwk['n'] ?? void))
$e = static::b64urlDecode((string)($jwk['e'] ?? void))
if (!$n || !$e) return void
$key = static::der(0x30, static::derInt($n).static::derInt($e))
$bits = static::der(0x03, "\x00".$key)
$algo = static::der(0x30, "\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00")
$spki = static::der(0x30, $algo.$bits)
return '-----BEGIN PUBLIC KEY-----'.lf.chunk_split(base64_encode($spki), 64, lf).'-----END PUBLIC KEY-----'.lf
static

social :: der ($tag, $content):string

line 142
$len = strlen($content)
if ($len < 0x80) return chr($tag).chr($len).$content
$bytes = ltrim(pack('N', $len), "\x00")
return chr($tag).chr(0x80 | strlen($bytes)).$bytes.$content
static

social :: derInt ($bytes):string

line 149
$bytes = ltrim((string)$bytes, "\x00")
if ($bytes === void) $bytes = "\x00"
if (ord($bytes[0]) & 0x80) $bytes = "\x00".$bytes
return static::der(0x02, $bytes)
static

social :: b64urlDecode ($data):string

line 156
$data = strtr((string)$data, '-_', '+/')
$pad = strlen($data) % 4
if ($pad) $data .= str_repeat(eq, 4 - $pad)
return (string)base64_decode($data)
static

social :: verifyClaims ($provider, array $cfg, array $claims, $nonce = void):bool

line 163
if ((int)($claims['exp'] ?? 0) <= time()) return false
$aud = $claims['aud'] ?? void
if (!in_array((string)($cfg['client_id'] ?? void), array_map('strval', is_array($aud) ? $aud : [$aud]), true)) return false
if ($nonce !== void && !hash_equals((string)$nonce, (string)($claims['nonce'] ?? void))) return false
return static::verifyIssuer($provider, $claims)
static

social :: verifyIssuer ($provider, array $claims):bool

line 171
$iss = (string)($claims['iss'] ?? void)
if ($provider === 'microsoft'){
	$tid = (string)($claims['tid'] ?? void)
	return $tid !== void && $iss === 'https://login.microsoftonline.com/'.$tid.'/v2.0'
}
$expected = (string)(static::providers()[$provider]['issuer'] ?? void)
if ($expected === void) return false
return $iss === $expected || ($provider === 'google' && $iss === 'accounts.google.com')
static

social :: normalize ($provider, array $claims):array

line 182
$ev = $claims['email_verified'] ?? null
$verified = $ev === true || $ev === 'true'
if ($provider === 'microsoft'){
	$edov = $claims['xms_edov'] ?? null
	$verified = $edov === true || $edov === 'true' || $edov === 1 || $edov === '1'
}
$name = (string)($claims['name'] ?? void)
if (!$name) $name = trim(((string)($claims['given_name'] ?? void)).space.((string)($claims['family_name'] ?? void)))
return arr(
	provider: $provider,
	uid: (string)($claims['sub'] ?? void),
	email: strtolower(trim((string)($claims['email'] ?? void))),
	verified: $verified,
	name: trim($name),
)
static

social :: b64url ($data):string

line 200
将给定数据编码为base64 URL安全格式,通过将'+'替换为'-',将'/'替换为'_',并修剪任何尾随的等号。
rtrim(strtr(base64_encode((string)$data), '+/', '-_'), eq)
static

social :: appleSecret

line 202
$section = %creds->apple ?? null
$creds = is_object($section) ? (array)$section->toArray : []
$teamId = (string)($creds['team_id'] ?? void)
$keyId = (string)($creds['key_id'] ?? void)
$clientId = (string)($creds['client_id'] ?? void)
$keyData = (string)($creds['private_key'] ?? void)
if (!$keyData && !empty($creds['key_file']) && is_file((string)$creds['key_file'])) $keyData = (string)file_get_contents((string)$creds['key_file'])
if (!$teamId || !$keyId || !$clientId || !$keyData) return void
$key = openssl_pkey_get_private($keyData)
if (!$key) return void
$now = time()
$input = static::b64url(json_encode(arr(alg: 'ES256', kid: $keyId))).dot.static::b64url(json_encode(arr(iss: $teamId, iat: $now, exp: $now + 15552000, aud: 'https://appleid.apple.com', sub: $clientId)))
$der = void
if (!openssl_sign($input, $der, $key, OPENSSL_ALGO_SHA256)) return void
return $input.dot.static::b64url(static::derToJose($der))
static

social :: derToJose ($der):string

line 220
从DER编码的签名中提取'r'和's'值,并将其填充到32字节。
$rlen = ord($der[3])
$r = substr((string)$der, 4, $rlen)
$slen = ord($der[4 + $rlen + 1])
$s = substr((string)$der, 4 + $rlen + 2, $slen)
return static::pad32($r).static::pad32($s)
static

social :: pad32 ($x):string

line 228
该方法在字符串左侧填充空字节,以确保其长度为32个字符,在填充之前去除任何前导空字节。
$x = ltrim((string)$x, "\x00")
return str_pad($x, 32, "\x00", STR_PAD_LEFT)
object

%totp

/phlo/resources/security/totp.phlo

Codes from an authenticator app (TOTP, RFC 6238): a secret, the link to scan and the check

secret() makes a secret to keep on the user, uri() is the otpauth: link an authenticator app reads (as a QR code, or typed in), and step() checks a code: one step either side is accepted, for a clock that drifts. It answers which step the code belongs to, so the caller can refuse the same code a second time; %account does that for you when its totpColumn is set.

totp2faotpauthenticator
static

totp :: secret:string

line 8
static::base32(random_bytes(20))
static

totp :: uri (string $secret, string $label, string $issuer = host):string

line 10
'otpauth://totp/'.rawurlencode($issuer.colon.$label).'?secret='.$secret.'&issuer='.rawurlencode($issuer).'&digits=6&period=30'
static

totp :: step (string $secret, string $code, ?int $time = null):?int

line 12
$code = preg_replace('/\s+/', void, $code)
if (!preg_match('/^\d{6}$/', $code)) return null
$key = static::unbase32($secret)
$now = intdiv($time ?? time(), 30)
foreach ([$now - 1, $now, $now + 1] AS $step) if (hash_equals(static::code($key, $step), $code)) return $step
return null
static

totp :: code (string $key, int $step):string

line 21
$hash = hash_hmac('sha1', pack('J', $step), $key, true)
$offset = ord($hash[19]) & 15
return str_pad((string)((unpack('N', substr($hash, $offset, 4))[1] & 0x7fffffff) % 1000000), 6, '0', STR_PAD_LEFT)
static

totp :: base32 (string $bytes):string

line 27
implode(array_map(fn($chunk) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'[bindec(str_pad($chunk, 5, '0'))], str_split(implode(array_map(fn($c) => sprintf('%08b', ord($c)), str_split($bytes))), 5)))
static

totp :: unbase32 (string $text):string

line 29
$bits = implode(array_map(fn($c) => sprintf('%05b', (int)strpos('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', $c)), str_split(strtoupper(preg_replace('/[^A-Za-z2-7]/', void, $text)))))
return implode(array_map(fn($byte) => chr(bindec($byte)), array_filter(str_split($bits, 8), fn($byte) => strlen($byte) === 8)))
object

%webhook

/phlo/resources/security/webhook.phlo

Verify a signed webhook: a signature over the raw body, within a time window, handled once

Check the signature before you read anything from the body. hmac() is a signature over the body alone (GitHub and Meta send sha256= and hex); stripe(), slack() and standard() (Standard Webhooks, as Svix and Resend send it) also refuse a timestamp outside the window, five minutes by default, so a captured request cannot be sent again later. Each reads its header and the raw body itself and returns true or false; the answer is yours, usually a 400. once($id) is true the first time it sees a delivery id, so a retried event is handled once; it needs the apcu resource and lets everything through without it. A webhook carries no cookie and no browser header, so the CSRF guard lets it through without an except.

webhooksignaturehmacstripeslackreplay
static

webhook :: hmac (string $secret, string $header = 'X-Hub-Signature-256', string $algo = 'sha256'):bool

line 10
A signature over the raw body, in hex or base64, with or without the name of its algorithm in front (sha256=, hmacsha256=).
$given = preg_replace('/^(?:hmac-?)?sha(?:1|224|256|384|512)=/i', void, trim((string)%req->header($header)))
$mac = hash_hmac($algo, %req->body, $secret, true)
return $given !== void && (hash_equals(bin2hex($mac), strtolower($given)) || hash_equals(base64_encode($mac), $given))
static

webhook :: stripe (string $secret, int $tolerance = 300):bool

line 17
Stripe-Signature: t=<time>,v1=<hex HMAC of "t.body">. Any v1 may match, so a rolled secret works.
$t = 0
$given = []
foreach (explode(comma, (string)%req->header('Stripe-Signature')) AS $part){
	[$key, $value] = explode('=', trim($part), 2) + [void, void]
	if ($key === 't') $t = (int)$value
	elseif ($key === 'v1') $given[] = $value
}
return static::fresh($t, $tolerance) && static::matches(hash_hmac('sha256', $t.dot.%req->body, $secret), $given)
static

webhook :: slack (string $secret, int $tolerance = 300):bool

line 29
X-Slack-Signature: v0=<hex HMAC of "v0:timestamp:body">, with X-Slack-Request-Timestamp.
$t = (int)%req->header('X-Slack-Request-Timestamp')
return static::fresh($t, $tolerance) && static::matches('v0='.hash_hmac('sha256', "v0:$t:".%req->body, $secret), [trim((string)%req->header('X-Slack-Signature'))])
static

webhook :: standard (string $secret, int $tolerance = 300):bool

line 36
webhook-id, webhook-timestamp and webhook-signature, "v1,<base64 HMAC of id.timestamp.body>",
$id = (string)%req->header('webhook-id')
$t = (int)%req->header('webhook-timestamp')
$key = str_starts_with($secret, 'whsec_') ? (string)base64_decode(substr($secret, 6)) : $secret
$given = loop(array_filter(explode(space, (string)%req->header('webhook-signature')), fn($s) => str_starts_with($s, 'v1,')), fn($s) => substr($s, 3))
return $id !== void && static::fresh($t, $tolerance) && static::matches(base64_encode(hash_hmac('sha256', "$id.$t.".%req->body, $key, true)), $given)
static

webhook :: fresh (int $timestamp, int $tolerance):bool

line 44
$timestamp > 0 && abs(time() - $timestamp) <= $tolerance
static

webhook :: matches (string $expected, array $given):bool

line 46
(bool)array_filter($given, fn($g) => hash_equals($expected, (string)$g))
static

webhook :: once (string $id, int $ttl = 86400):bool

line 49
True the first time this delivery id comes by within $ttl seconds.
apcu_add(apcu_key('webhook/'.$id), 1, $ttl)

Functions

function

decrypt($encrypted, $key):string|false

/phlo/resources/security/encryption.phlo line 11

Encrypt and decrypt secretbox payloads using a key

Authenticated encryption through libsodium: a fresh nonce per call travels with the value, so encrypting the same text twice gives different output and a changed ciphertext refuses to decrypt rather than returning rubbish. decrypt() gives false on a failure, so test with === false and not on falsiness. The key is hashed to the right length, which means any string works, but a short one is still a short secret.

encryptdecryptencryptionsodiumsecretboxcrypto
使用提供的密钥解密给定的 base64 编码的加密字符串,返回原始数据或在解密失败时返回 false。
($d = base64_decode($encrypted, true)) !== false && strlen($d) >= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ? sodium_crypto_secretbox_open(substr($d, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), substr($d, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES), hash('sha256', $key, true)) : false
function

encrypt($data, $key):string

/phlo/resources/security/encryption.phlo line 9

Encrypt and decrypt secretbox payloads using a key

Authenticated encryption through libsodium: a fresh nonce per call travels with the value, so encrypting the same text twice gives different output and a changed ciphertext refuses to decrypt rather than returning rubbish. decrypt() gives false on a failure, so test with === false and not on falsiness. The key is hashed to the right length, which means any string works, but a short one is still a short secret.

encryptdecryptencryptionsodiumsecretboxcrypto
使用秘密密钥加密给定数据并返回 base64 编码的结果。
base64_encode(($nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES)).sodium_crypto_secretbox($data, $nonce, hash('sha256', $key, true)))
function

token(int $length = 8, ?string $input = null):string

/phlo/resources/security/token.phlo line 14

Generate deterministic or random lowercase token

Lowercase letters only, so a token survives being read aloud, typed by hand or used in a URL without escaping. Pass an input and the token is derived from it, so the same input always gives the same token: exactly what you want for a file or a record, and exactly what you do not want for a secret. Leave the input out for anything that must be unguessable.

tokenrandomdeterministicsecurity
Bytes from the last incomplete block of 256 are thrown away rather than wrapped around.
	$length || error('Token must have a minimum length above 0', 500)
	$alphabet = 'abcdefghijklmnopqrstuvwxyz'
	$alphabetLength = strlen($alphabet)
	$limit = intdiv(256, $alphabetLength) * $alphabetLength
	$token = void
	$buffer = void
	$state = is_null($input) ? null : hash('sha256', (string)$input, true)
	while (strlen($token) < $length){
		if ($buffer === void){
			if (is_null($state)) $buffer = random_bytes(32)
			else {
				$state = hash('sha256', $state, true)
				$buffer = $state
			}
		}
		$byte = ord($buffer[0])
		$buffer = substr($buffer, 1)
		if ($byte >= $limit) continue
		$token .= $alphabet[$byte % $alphabetLength]
	}
	return $token

最近更新于 2026年11月4日

我们使用必要的cookie来使该网站正常工作。在您的许可下,我们还使用分析工具来改善网站。