Skip to content

feat: add validFor function to return the validity interval #388

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
"./validator": {
"types": "./dist/src/validator.d.ts",
"import": "./dist/src/validator.js"
},
"./pb": {
"types": "./dist/src/pb/ipns.d.ts",
"import": "./dist/src/pb/ipns.js"
}
},
"eslintConfig": {
Expand Down
46 changes: 43 additions & 3 deletions src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,23 @@
import { logger } from '@libp2p/logger'
import NanoDate from 'timestamp-nano'
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
import { InvalidEmbeddedPublicKeyError, RecordExpiredError, RecordTooLargeError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'
import {
InvalidEmbeddedPublicKeyError,
RecordExpiredError,
RecordTooLargeError,
SignatureVerificationError,
UnsupportedValidityError
} from './errors.js'
import { IpnsEntry } from './pb/ipns.js'
import { extractPublicKeyFromIPNSRecord, ipnsRecordDataForV2Sig, isCodec, multihashFromIPNSRoutingKey, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from './utils.js'
import {
extractPublicKeyFromIPNSRecord,
ipnsRecordDataForV2Sig,
isCodec,
multihashFromIPNSRoutingKey,
multihashToIPNSRoutingKey,
unmarshalIPNSRecord
} from './utils.js'
import type { IPNSRecord } from './index.js'
import type { PublicKey } from '@libp2p/interface'

const log = logger('ipns:validator')
Expand All @@ -18,7 +32,7 @@
* Validates the given IPNS Record against the given public key. We need a "raw"
* record in order to be able to access to all of its fields.
*/
export const validate = async (publicKey: PublicKey, marshalledRecord: Uint8Array): Promise<void> => {
export async function validate (publicKey: PublicKey, marshalledRecord: Uint8Array): Promise<void> {
// unmarshal ensures that (1) SignatureV2 and Data are present, (2) that ValidityType
// and Validity are of valid types and have a value, (3) that CBOR data matches protobuf
// if it's a V1+V2 record.
Expand Down Expand Up @@ -92,3 +106,29 @@
// Record validation
await validate(recordPubKey, marshalledRecord)
}

/**
* Returns the number of milliseconds until the record expires.
* If the record is already expired, throws an error.
*
* @param record - The IPNS record to validate.
* @returns The number of milliseconds until the record expires.
*/
export function validFor (record: IPNSRecord): number {
if (record.validityType !== IpnsEntry.ValidityType.EOL) {
throw new UnsupportedValidityError()
}

if (record.validity == null) {
throw new UnsupportedValidityError()

Check warning on line 123 in src/validator.ts

View check run for this annotation

Codecov / codecov/patch

src/validator.ts#L123

Added line #L123 was not covered by tests
}

const validUntil = NanoDate.fromString(record.validity).toDate().getTime()
const now = Date.now()

if (validUntil < now) {
throw new RecordExpiredError('The record has expired')
}

return validUntil - now
}
40 changes: 38 additions & 2 deletions test/validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { randomBytes } from '@libp2p/crypto'
import { generateKeyPair, publicKeyToProtobuf } from '@libp2p/crypto/keys'
import { expect } from 'aegir/chai'
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
import { InvalidEmbeddedPublicKeyError, RecordTooLargeError, SignatureVerificationError } from '../src/errors.js'
import { InvalidEmbeddedPublicKeyError, RecordTooLargeError, SignatureVerificationError, RecordExpiredError, UnsupportedValidityError } from '../src/errors.js'
import { createIPNSRecord, marshalIPNSRecord, multihashToIPNSRoutingKey } from '../src/index.js'
import { ipnsValidator } from '../src/validator.js'
import { ipnsValidator, validFor } from '../src/validator.js'
import type { PrivateKey } from '@libp2p/interface'

describe('validator', function () {
Expand Down Expand Up @@ -91,4 +91,40 @@ describe('validator', function () {
await expect(ipnsValidator(key, marshalledData)).to.eventually.be.rejected()
.with.property('name', RecordTooLargeError.name)
})

describe('validFor', () => {
it('should return the number of milliseconds until the record expires', async () => {
const record = await createIPNSRecord(privateKey1, contentPath, 0, 1000000)
const result = validFor(record)
expect(result).to.be.greaterThan(0)
})

it('should throw RecordExpiredError for expired records', async () => {
const record = await createIPNSRecord(privateKey1, contentPath, 0, 0)

expect(() => validFor(record)).to.throw(RecordExpiredError)
})

it('should throw UnsupportedValidityError for non-EOL validity types', async () => {
const record = await createIPNSRecord(privateKey1, contentPath, 0, 1000000)
record.validityType = 5 as any

expect(() => validFor(record)).to.throw(UnsupportedValidityError)
})

it('should throw UnsupportedValidityError for null validity', async () => {
const record = await createIPNSRecord(privateKey1, contentPath, 0, 1000000)
record.validityType = null as any

expect(() => validFor(record)).to.throw(UnsupportedValidityError)
})

it('should return correct milliseconds until expiration', async () => {
const record = await createIPNSRecord(privateKey1, contentPath, 0, 5000)

const result = validFor(record)

expect(result).to.be.within(4900, 5000)
})
})
})